Skip to content

Instantly share code, notes, and snippets.

@ayushhgoyal
Last active December 13, 2015 18:58
Show Gist options
  • Save ayushhgoyal/4958964 to your computer and use it in GitHub Desktop.
Save ayushhgoyal/4958964 to your computer and use it in GitHub Desktop.
Sample async task class..sends params and gets data in json format.
class LoginUser extends AsyncTask<String, Integer, String> {
HttpClient client = new DefaultHttpClient();
JSONObject json;
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
final static String URL = "http://www.your-url-here.com";
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
json = sendJSONtoUrl();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
setStudentId(Integer.parseInt(json.getString("id").toString()
.trim()));
return json.getString("success").toString().trim();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
myPd_ring.dismiss();
// myPd_ring.setVisibility(View.INVISIBLE);
if (result.equals("0")) {
// username and password do not match
Toast.makeText(context, "Username and password do not match!!",
Toast.LENGTH_SHORT).show();
} else if (result.equals("1")) {
// success
Toast.makeText(context, "Login Successful", Toast.LENGTH_SHORT)
.show();
setSignedIn(1);
Intent intent = new Intent("startScreenActivity");
startActivity(intent);
} else {
Log.e("value of result: ", " shayad result is null ");
}
}
}
public JSONObject sendJSONtoUrl() throws ClientProtocolException,
IOException, JSONException {
HttpPost httpPost = new HttpPost(URL);
params.add(new BasicNameValuePair("tag", "Login"));
params.add(new BasicNameValuePair("Password", loginDetails));
Log.v("value in params", params.toString() + "");
try {
httpPost.setEntity(new UrlEncodedFormEntity(params));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpResponse r = client.execute(httpPost);
int status = r.getStatusLine().getStatusCode();
if (status == 200) {
Log.e("my", "status verified");
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
Log.e("data", data.toString());
JSONArray datastream1 = new JSONArray(data);
JSONObject message = datastream1.getJSONObject(0);
return message;
} else {
Log.e("-----", "in else part of sendJsontoUrl");
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment