0

在图片一中,在列表中选择一个项目后,说历史,一个新的活动开始。请看图二。图二中,点击返回List后,List中的项目会重复出现,如图三。

为什么会这样?

以下是我的代码的一部分:

public class CategoryListActivity extends ListActivity implements LoaderCallbacks<List<Category>> {

String url = "http://vlm1.uta.edu/~zhangzhong/questions.json";
private ArrayAdapter<Category> mListAdapter;
//private ListView listview;
//private ArrayList<Category> categories = new ArrayList<Category>();
private static final int LOADER_ID_CHECKS = 1;
private static final String TAG = "CategoryListActivity";
final Context context = this;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //listview = (ListView) findViewById(R.id.listview);
    mListAdapter = new ArrayAdapter<Category>(this, 
            android.R.layout.simple_list_item_1,
            android.R.id.text1,
            DataStore.categories);
    //listview.setOnItemClickListener(mOnItemClickListener);
    //listview.setAdapter(mListAdapter);
    setListAdapter(mListAdapter);       
    getLoaderManager().initLoader(LOADER_ID_CHECKS, null, this);   
}

@Override
protected void onListItemClick(ListView listView, View view, int position, long id) {
    Intent detailIntent = new Intent(this, ScreenSlideActivity.class);
    detailIntent.putExtra("category_id", id);
    startActivity(detailIntent);
}

@Override
public Loader<List<Category>> onCreateLoader(int id, Bundle args) {
    switch (id) {
        case LOADER_ID_CHECKS:              
            Loader<List<Category>> loader = new CategoryListLoader(this, url);
            loader.forceLoad();
            return loader;
    }
    return null;
}

@Override
public void onLoadFinished(Loader<List<Category>> loader, List<Category> result) {
    Log.d(TAG, "onLoadFinished");

    if (result != null) {
        Log.d(TAG, "items: " + result.size());
    }

    switch (loader.getId()) {
        case LOADER_ID_CHECKS:
            if (result != null) {
                for (Category category : result) {
                    DataStore.categories.add(category);
                }
            }   
            mListAdapter.notifyDataSetChanged();
            break;
    }
}

@Override
public void onLoaderReset(Loader<List<Category>> loader) {
    Log.d(TAG, "onLoaderReset");
    switch (loader.getId()) {
        case LOADER_ID_CHECKS:
            break;
    }
}        
}

在此处输入图像描述 在此处输入图像描述 在此处输入图像描述

4

2 回答 2

1
case LOADER_ID_CHECKS:
    if (result != null) {
        for (Category category : result) {
            DataStore.categories.add(category);
        }
    }   
    mListAdapter.notifyDataSetChanged();
    break;

应该

case LOADER_ID_CHECKS:
     DataStore.categories.clear();
     if (result != null) {
         DataStore.categories.addAll(result);
     }
     mListAdapter.notifyDataSetChanged();
     break;
于 2013-04-29T17:47:51.250 回答
0

检查 onLoadFinished() 是否再次调用。如果再次调用 onLoadFinishe(),您的数据将再次添加到数组列表中。

于 2013-04-29T17:31:21.540 回答