AsyncTaskLoader调用onLoadFinished的方法不正确

时间:2013-03-18 19:16:15

标签: android

我正在尝试处理AsyncTaskLoader。我实现了Interface LoaderCallbacks如下:

public class MainActivity extends Activity implements LoaderCallbacks<String> {
...
...
@Override
public Loader<String> onCreateLoader(int id, Bundle args) {
    Log.w("loader","onCreate");
    return new JSONLoader(this);
}


@Override
public void onLoadFinished(Loader<String> arg0, String arg1) {
        Log.w("loader","finish");

}

@Override
public void onLoaderReset(Loader<String> arg0) {
    Log.w("loader","onReset");
    // TODO Auto-generated method stub

}


public void useLoader() {

    Log.w("loader","useLoader");
      Bundle args = new Bundle();
      // ...
      // fill in args
      // ...


      Loader loader = 
         this.getLoaderManager().initLoader(0, args, this);

      Log.w("HashLoader",String.valueOf(loader.hashCode()));
      // with support library: 
      // Loader loader = 
      //    context2.getSupportLoaderManager().initLoader(0, args, this);
      // call forceLoad() to start processing
      loader.forceLoad();

   } 

我收到按钮的挂起事件:

btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            useLoader();
        }
    });

当我第一次按下按钮时,在加载器之后调用onLoadFinished()方法。但是当第二次按下按钮时,它会调用第一个onLoadFinished()。

Logcat:

useLoader
onCreate
1087415440
good
finish
useLoader
finish
1087415440
good

关于AsyncTaskLoader的一点点:

public class JSONLoader extends AsyncTaskLoader<String> {

public JSONLoader(Context context) {
    super(context);
    // TODO Auto-generated constructor stub
}

@Override
public String loadInBackground() {
            try {
        Thread.sleep(5000);
    } catch (InterruptedException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    Log.w("loader","good");
        return " ";}

为什么onLoadFinished()方法不等待Thread的结束?

1 个答案:

答案 0 :(得分:3)

我认为initLoader函数不会销毁并且创建新的加载器。然后在第二次运行时,您的自定义加载程序已经被“加载”=&gt;它调用onLoadFinish()

尝试销毁它并仅通过用initLoader替换restartLoader调用来重新创建它 (Reference

Loader loader = this.getLoaderManager().restartLoader(0, args, this);