我正在实现一个扩展 AsyncTask
的类,并在该类中执行 http 请求。该类不是 Activity
,而是位于单独的 java 文件中,因为我想多次使用该类。
我在我的Activity
中实例化此类的对象,以在单独的线程中执行http请求。当线程执行时,我想调用我的 Activity
的方法。
我该如何实现这个?我需要 Activity
中的 http 请求结果,但到目前为止我无法处理这个问题。
这是线程任务的代码...
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) {
}
}
这是我创建线程类的 Activity
代码的一部分...
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();
}
}
}
最佳答案
在构造函数中传递 Activity 引用......
作为
public class PostRequest extends AsyncTask<String, Void, String> {
public String result = "";
private Activity mActivity;
public PostRequest(Activity activity){
super();
mActivity = activity;
}
......
关于java - 从android中的非 Activity 类调用 Activity 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10902682/