Android:AsyncTask里面的吐司

时间:2015-04-12 17:32:47

标签: java android android-asynctask toast android-2.3-gingerbread

我有一个从活动SearchForQuestions调用的AsyncTask类QuizMap。在SearchForQuestions中循环遍历数组时,我无法在AsynTask中找到正确的toast上下文。

标准Toast.makeText(getApplicationContext(), "This is Toast!!!", Toast.LENGTH_SHORT).show();错误getApplicationContext()未定义。

我已经尝试了SO提供的一些解决方案,其中大多数都列在here并且关注获取UiThread并在其上运行。

但是,我无法让它发挥作用。以下是我尝试过的示例代码片段。我在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) {

             ...
                 }
                    };

6 个答案:

答案 0 :(得分:1)

我要关闭这个问题。我还没有解决我的问题,但提供的答案数量显然在其他情况下工作表明还有其他事情正在发生。我将重新构造类,以便在AsyncTask中调用。

答案 1 :(得分:0)

Just Toast it,你为什么要为它创建一个函数? onPostExecute()已经在UI线程上。

您无法访问,因为除非您传递外部类的实例,否则内部类不能调用外部类的函数。

答案 2 :(得分:0)

  1. onPostExecute
  2. 中致电您的祝酒词
  3. 为回调创建一个界面。

  4. public interface ToastCallback {
        public void invoke(String text);
    }
    

    您的AsyncTask构造函数

    private ToastCallback toastCallback;
    public SearchQuestions(ToastCallback callback) {
        this.toastCallback = callback;
    }
    
    // in doInBackground() {
    
          toastCallback.invoke("Toast from background");
     }
    

    在您的活动中,

    private void showNotNearToast(String text) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
            }
       }); 
    }
    
    public class MyToastCallback implements ToastCallback {
         @Override
         public void invoke(String text) {
             showNotNearToast(text);
         }
    }
    
    // Asynctask call
    new SearchQuestion(new MyTosatCallback()).execute(<Your params here>);
    

答案 3 :(得分:0)

在AsyncTask中尝试:

myActivity.this.runOnUiThread(new Runnable() {
    public void run() {
        Toast.makeText(activity, "Hello", Toast.LENGTH_SHORT).show();
    }
});

你有

的地方
showNotNearToast("My Message"); // showNotNearToast undefined

myActivity替换为您的活动名称。

答案 4 :(得分:0)

(Ab)使用publishProgress方法

private class ToastAsyncTask extends AsyncTask<Void, String, Void>{
        @Override
        protected Void doInBackground(Void... voids) {
            SystemClock.sleep(1000);
            publishProgress("Toast msg string");
            SystemClock.sleep(1000);
            return null;
        }

        @Override
        protected void onProgressUpdate(String... values) {
            Toast.makeText(getApplicationContext(), values[0], Toast.LENGTH_SHORT).show();
        }
    }

**更新:**因为您因某些原因遇到上下文问题,请使用此版本。上面的实现很难对我有用。

private class ToastAsyncTask extends AsyncTask<Void, String, Void> {

        private WeakReference<Context> contextRef;

        public ToastAsyncTask(Context context) {
            contextRef = new WeakReference<Context>(context);
        }

        @Override
        protected Void doInBackground(Void... voids) {
            SystemClock.sleep(1000);
            publishProgress("Toast msg string");
            SystemClock.sleep(1000);
            return null;
        }

        @Override
        protected void onProgressUpdate(String... values) {
            if (contextRef.get() != null) {
                Toast.makeText(contextRef.get(), values[0], Toast.LENGTH_SHORT).show();
            } else {
                // The context was destroyed.. check what you are doing
            }
        }
    }

像这样使用

new ToastAsyncTask(MainActivity.this).execute();

答案 5 :(得分:-2)

将活动传递到AsyncTask。见下文。

private class SearchForQuestions extends AsyncTask<String, Void, DataHandler> {
    Activity activity;
    public void SearchForQuestions(Activity activity){
        this.activity = activity;
    }
//... rest of the code

  public class QuizMap extends FragmentActivity implements OnMarkerClickListener {
    /*...*/
    new SearchForQuestions(this).execute();
    /*...*/
    /*When calling the toast:*/
Toast.makeText(this.activity, "This is Toast!!!", Toast.LENGTH_SHORT).show();