【发布时间】:2013-03-31 01:13:34
【问题描述】:
我正在尝试在新线程中显示祝酒词。我对其进行了研究,显然我需要在 UI 线程中运行 toast。我需要这个新线程,因为 Android 不希望我在主线程中运行 HTTPclient。我可以处理一个处理程序,但我的问题是,我想不出办法将 MainActivity 上下文获取到我所在的类。它扩展了 SherlockFragment 并且构造函数可能不允许它覆盖。
这是我目前的可运行文件
new Thread(new Runnable() {
@Override
public void run() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://www.example.com/API/events/add.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(16);
httppost.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);
// Adding data
nameValuePairs.add(new BasicNameValuePair("token", "admin"));
nameValuePairs.add(new BasicNameValuePair("eventTitle", title));
nameValuePairs.add(new BasicNameValuePair("categories", Integer.toString(catId)));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
String status = EntityUtils.toString(response.getEntity());
JSONObject jObj = null;
try {
jObj = new JSONObject(status);
} catch (JSONException e) {
Log.e(MainActivity.class.getName(), "Error Parsing Data: " + e.toString());
}
try {
//Want to toast this string here, jObj.getString("status"))
} catch (JSONException e) {
Log.e(MainActivity.class.getName(), "Error Reading Status String: " + e.toString());
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}).start();
对我可以做什么有什么建议吗?
【问题讨论】:
-
只需调用
getActivity()即可获取上下文。
标签: java android multithreading toast runnable