I'm implementing a class which extends AsyncTask
and I perform an http request within this class. The class is not an Activity
and is located in a seperate java file because I want to use this class several times.
I instantiate an object of this class in my Activity
, to execute the http request in a separate thread. When the thread executes, I want to call a method of my Activity
.
How do I implement this? I need the result of the http request in my Activity
but I can't handle this so far.
This is the code for the thread task...
public class PostRequest extends AsyncTask<String, Void, String> {
public String result = "";
@Override
protected String doInBackground(String... urls) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://bla/index.php?" + urls[0]);
// httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
// convert response to string
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
@Override
protected void onPostExecute(String result) {
}
}
And this is part of my Activity
code that creates the thread class...
public class ListActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
PostRequest task = new PostRequest();
task.execute(new String[] { "action=getUsers" });
task.onPostExecute(task.result) {
}
}
public void Display(String result) {
try {
JSONArray jArray = new JSONArray(result);
JSONObject json_data = jArray.getJSONObject(0);
String value = json_data.getString("name");
TextView text = (TextView) findViewById(R.id.value);
text.setText(value);
} catch (JSONException e) {
e.printStackTrace();
}
}
}