Android AsyncTaskLoaderが注意しなければならない問題

6995 ワード

AsyncTaskLoaderを使用すると、次の2つの問題が発生します.
1.AsyncTaskLoaderを継承して必要な方法を実現した後、loadInBackground()が実行されていないことを発見する
インターネットで検索すると、次のような解決策が得られます.
AsyncTaskLoaderを継承すると、システム呼び出しのために次の方法を再ロードする必要があります.
@Override
protected void onStartLoading() {
	// TODO Auto-generated method stub
	super.onStartLoading();
	forceLoad();
}

2.問題1の解決策を使った後、Loaderは仕事を始めましたが、また新しい問題に遭遇しました.ActivityにListViewを書きました.ListViewのデータはAsyncTaskLoaderを通じて
を入力し、現在のActivityから別のActivityにジャンプしてbackキーを押して戻ると問題ありませんが、ListViewのいずれかをクリックすると、次のエラーが表示されます.
  E/AndroidRuntime(1141): java.lang.IllegalStateException: The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread. [in ListView(16908298, class android.widget.ListView) with Adapter(class com.study.ActivityAdapter)]
以下は私がAsyncTaskLoaderをカスタマイズしたコードです.
public class ActivityListLoader extends AsyncTaskLoader{
	
	private Context context;
	private Bundle args;
	private String path;
	
	private List> data;

	public ActivityListLoader(Context context,Bundle args) {
		super(context);
		this.context = context;
		this.args = args;
		path = args.getString("path");
		data = new ArrayList>();
	}

	@Override
	public Integer loadInBackground() {
		
		PackageManager pm = context.getPackageManager();
		Intent matchIntent = new Intent();
		matchIntent.setAction(Constants.ACTION_MAIN);
		matchIntent.addCategory(Constants.CATEGORY_STUDY);
		matchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		
		List list = pm.queryIntentActivities(matchIntent,0);
		String label = null;
		for(ResolveInfo info:list)
		{
			label = info.loadLabel(pm).toString();
			if(label.startsWith(path))
			{
				String[] paths = path.split("/");
				String[] files = label.split("/");
				Map map = new HashMap();
				Intent intent = new Intent();
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				
				int pathlen = paths.length;
				
				if(path.equals(""))
				{
					pathlen = 0;
				}
				
				if(files.length - pathlen == 1)
				{
					map.put("isFile", true);
					intent.setComponent(new ComponentName(info.activityInfo.packageName, info.activityInfo.name));
					map.put("intent", intent);
				}else
				{
					map.put("isFile", false);
					intent.setClass(context, MainActivity.class);
					intent.putExtra("path", path+files[pathlen]+"/");
					map.put("intent", intent);
				}
				data.add(map);
			}
		}
		
		return 0;
	}

	@Override
	protected void onStartLoading() {
		// TODO Auto-generated method stub
		super.onStartLoading();
		forceLoad();
	}
	
	public List> getData()
	{
		return data;
	}
	
}

MainActivity   :
public class MainActivity extends ListActivity implements
		LoaderCallbacks {

	private ListActivity context;
	private List> datalist;

	enum Type {
		ShowProgress, DismissProgress,UpdateAdapter
	};
	
	private ProgressDialog progress;

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			Type type = (Type) msg.obj;
			switch (type) {
			case ShowProgress:
				progress.show();
				break;
			case DismissProgress:
				if(progress.isShowing())
					progress.dismiss();
				break;
			case UpdateAdapter:
				ActivityAdapter adapter = new ActivityAdapter(context, datalist);
				setListAdapter(adapter);
				adapter.notifyDataSetChanged();
				break;
			default:
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		context = this;
		initProgressDialog();
		
		Intent intent = getIntent();
		String path = intent.getStringExtra("path");
		if (path == null)
			path = "";
		Bundle args = new Bundle();
		args.putString("path", path);
		getLoaderManager().initLoader(0, args, this);
		Message msg = Message.obtain(handler, 0, Type.ShowProgress);
		msg.sendToTarget();
		
		setListAdapter(new ActivityAdapter(this, new ArrayList>()));
		
		getListView().setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView> parent, View view,
					int position, long id) {
				@SuppressWarnings("unchecked")
				Map map = (Map) getListAdapter().getItem(position);
				Intent intent = (Intent)map.get("intent");	
				startActivity(intent);
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	private void initProgressDialog()
	{
		progress = new ProgressDialog(this);
		progress.setMessage("     Activity  ");
		progress.setCanceledOnTouchOutside(false);
	}

	@Override
	public Loader onCreateLoader(int id, Bundle args) {
		return new ActivityListLoader(context, args);
	}

	@Override
	public void onLoadFinished(Loader loader, Integer data) {
		ActivityListLoader aloader = (ActivityListLoader) loader;
		datalist = aloader.getData();
		LogUtils.e("debug");
		
		Message msg = Message.obtain(handler, 0, Type.DismissProgress);
		msg.sendToTarget();
		
		Message msgUpdate = Message.obtain(handler, 0, Type.UpdateAdapter);
		msgUpdate.sendToTarget();
	}

	@Override
	public void onLoaderReset(Loader loader) {
		LogUtils.e("debug");
		Message msgUpdate = Message.obtain(handler, 0, Type.UpdateAdapter);
		msgUpdate.sendToTarget();
	}

}

ListViewデータを更新する操作はUIスレッドで行われるので、システムが知らないところでデータを更新してListViewに通知しないはずです.
Activityを表示JAvaのソースコードは次のように表示されます.
protected void onStart() {
	if (DEBUG_LIFECYCLE) Slog.v(TAG, "onStart " + this);
	mCalled = true;
	if (!mLoadersStarted) {
		mLoadersStarted = true;
		if (mLoaderManager != null) {
			mLoaderManager.doStart(); //     Loader onStartLoading  
		} else if (!mCheckedForLoaderManager) {
			mLoaderManager = getLoaderManager(null, mLoadersStarted, false);
		}
		mCheckedForLoaderManager = true;
	}
	getApplication().dispatchActivityStarted(this);
}

Activityが回復すると、onStart関数が再呼び出され、最終的には私たちのLoaderのonStartLoading関数が呼び出されます.
私たちのonStartLoading関数はこうです.
@Override
protected void onStartLoading() {
	// TODO Auto-generated method stub
	super.onStartLoading();
	forceLoad();
}

つまり、いずれにしてもバックグラウンドでデータを再ロードし、システム呼び出しであるため、ListViewに通知することなく、データの不同期を招く.
ここで、ソリューションは次のようになります.
以下のように変更します.
@Override
protected void onStartLoading() {
	// TODO Auto-generated method stub
	super.onStartLoading();
	if(data.size() == 0)
		forceLoad();
}