我有一个从 Activity QuizMap
调用的 AsyncTask 类 SearchForQuestions
。在 SearchForQuestions
中循环遍历数组时,我无法在 AsynTask 中找到正确的 toast 上下文。
标准 Toast.makeText(getApplicationContext(), "This is Toast!!!", Toast.LENGTH_SHORT).show();
给出错误 getApplicationContext()
未定义。
我已经尝试了 SO 提供的一些解决方案,其中大部分都已列出 here并关注获取 UiThread 并在其上运行。
但是我无法让它工作。这是我尝试过的示例代码 fragment 。我在 QuizMap
中放置了一个方法,并尝试从 SearchForQuestions
中调用它,但无法识别 SearchForQuestions
。我该如何解决这个问题? )还是java的新手...)
// QuizMap activity
public class QuizMap extends FragmentActivity
implements OnMarkerClickListener {
private GoogleMap map;
private static final String TAG = "QuizMap"; // debugging
...
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quizmap);
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
...
}
// make toast inside AsyncTask
public void showNotNearToast(final String toast) {
QuizMap.this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(QuizMap.this, "This is Toast!!!", Toast.LENGTH_SHORT).show();
}});
}
.
// SearchForQuestions class
private class SearchForQuestions extends AsyncTask<String, Void, DataHandler> {
// checks for proximity to question locations
Location location =
locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
@Override
protected DataHandler doInBackground(String... pointsList) {
String result = pointsList[0];
...
}
@Override
protected void onPostExecute(DataHandler result) {
ArrayList<String> resultsArray = result.results;
Integer numPoints = resultsArray.size();
for (int i =0;i<numPoints;i++){
String[] pointDetails = resultsArray.get(i).split("::");
...
// we can make use of the Android distanceTo function to calculate the distances
float distance = location.distanceTo(fixedLoc);
if (i > DIST) { // this is UCL
showNotNearToast("My Message"); // showNotNearToast undefined
if (distance < DIST) {
...
}
};
最佳答案
我不会结束这个问题。我还没有解决我的问题,但是在其他情况下显然有效的答案数量表明还有其他事情正在发生。我将重新构造这些类,以避免必须从 AsyncTask 内部调用。
关于java - Android:在 AsyncTask 中 toast ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29592392/