我正在尝试在新线程中显示 toast。我研究了它,显然我需要在 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();
对我可以做什么有什么建议吗?
最佳答案
请引用这个问题..
它展示了如何让应用程序的任何部分以静态方式访问Context
。
[Static way to get 'Context' on Android? ]
为什么它没有内置到 API 中?我们永远不会知道..
HTH
关于java - 在新线程中 toast ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15725320/