从Android ListView中删除项目

时间:2012-05-30 11:04:56

标签: java android listview sharedpreferences

我为ListView创建了一个上下文菜单。在长按ListView中的项目时,将出现一个包含两个选项(编辑和删除)的上下文菜单。我的目的是,当单击“删除”时,只会从列表中删除ListView中的所选项目。但是我不知道为什么在完成后删除列表中的所有项目。

以下是我的代码行。 您能提供一些帮助吗?如果您能根据我的代码提供说明,那就太棒了。

非常感谢你。

public class HistoryView extends Activity {
private static final String HISTORY_TAG = "[AppName - HistoryView] ";
private ListView mLSTHistory = null;
private ArrayList<String> lstDict = null;
private ArrayList<Integer> lstId = null;
private ArrayAdapter<String> aptList = null;
private ArrayList<String> mWordHistory = null;
private SharedPreferences prefs;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.history);
    prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

    if (prefs.getBoolean("saveHistory", true))
    {
        String strHistory = prefs.getString("history", "");
        Log.i(HISTORY_TAG, "History loaded");
        if (strHistory != null && !strHistory.equals(""))
        {
            mWordHistory = new ArrayList<String>(Arrays.asList(strHistory.split(",")));
        }
        else
        {
            mWordHistory = new ArrayList<String>();
        }
    }
    else
    {
        mWordHistory = new ArrayList<String>();
    }

    Log.d(HISTORY_TAG,"mWordHistory = " + mWordHistory.size());

    if (lstDict == null)
    {
        lstDict = new ArrayList<String>();
        lstId = new ArrayList<Integer>();
        aptList = new ArrayAdapter<String>(getApplicationContext(),R.layout.customlist);
    }
    lstDict.clear();
    lstId.clear();
    aptList.clear();
    if (mWordHistory != null && mWordHistory.size() > 0)
    {
        try
        {
            for (int i=0; i < mWordHistory.size(); i++)
            {
                Log.i(HISTORY_TAG,"item = " + mWordHistory.get(i));
                String arrPart[] = mWordHistory.get(i).split("::");
                if (arrPart.length == 3)
                {
                    //Log.i(CONTENT_TAG, "loaded content " +arrPart.length + ", wordId = " + arrPart[1]);
                    //Log.i(CONTENT_TAG, "loaded 0");
                    lstDict.add(i,arrPart[0]);
                    //Log.i(CONTENT_TAG, "loaded 1");
                    lstId.add(i,Integer.parseInt(arrPart[1]));
                    //Log.i(CONTENT_TAG, "loaded 2");
                    aptList.add(arrPart[2]);
                }
                else
                {
                    Log.i(HISTORY_TAG,"Wrong entry: " + mWordHistory.get(i));
                }
            } 
        }
        catch (Exception ex)
        {
            Log.i(HISTORY_TAG,"Wrong entry found!");
        }
    }

    mLSTHistory = (ListView) findViewById(R.id.lstHistory); 
    registerForContextMenu(mLSTHistory);
    mLSTHistory.setAdapter(aptList);

    mLSTHistory.setOnItemClickListener(new AdapterView.OnItemClickListener() 
    {
        public void onItemClick(AdapterView<?> arg0, View v, int arg2, long arg3)
        {
            Intent i = new Intent();
            i.putExtra("dict", lstDict.get(arg2));
            i.putExtra("wordId", lstId.get(arg2));
            setResult(RESULT_OK,i);
            finish();
        }
    });
}

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.context_menu, menu);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
    switch (item.getItemId()) {
        case R.id.edit:
            editItem(info.id);
            return true;
        case R.id.delete:
            deleteItem(info.id);
            return true;
        default:
            return super.onContextItemSelected(item);
    }
    }
private void deleteItem(long id) {
    // TODO Auto-generated method stub
    mWordHistory.clear();
    aptList.clear();
    mLSTHistory.setAdapter(aptList);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString("history", "");
    editor.commit();
    setResult(RESULT_OK);
    finish();
    }
private void editItem(long id) {
    //Edit item...
    }
}

更新

感谢 raju ,现在可以使用了(从列表中删除了所选项目)。但是,不会从SharedPreferences中删除所选项目。这就是重新加载列表时重新出现的原因。

我使用以下代码行将项目保存到SharedPreferences。任何人都可以告诉我如何更新SharedPreferences,以便它反映使用raju的代码行从列表中删除项目时的更改。非常感谢你。

if (prefs.getBoolean("saveHistory", true) && mWordHistory != null && mWordHistory.size() >= 1)
        prefs =   PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        StringBuilder sbHistory = new StringBuilder();
        for (String item : mWordHistory)
        {
            sbHistory.append(item);
            sbHistory.append(",");

        String strHistory = sbHistory.substring(0, sbHistory.length()-1);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString("history", strHistory);
        editor.commit();
        }

2 个答案:

答案 0 :(得分:2)

aptList.clear();

此行清除适配器...所以所有项目都被删除.. 改为使用

               aptlist.remove(//the selected item);

代替这个

   deleteItem(info.id);

  String content =getListView().getItemAtPosition(info.position);
   aptList.remove(content);
   aptList.notifyDataSetChanged();

答案 1 :(得分:0)

我遵循了你的建议,在我的情况下,它看起来像下面;

活动类中的适配器声明:

  private MyObjectAdapter adapter;

在活动类的onCreate中创建适配器和设置适配器:

adapter = new MyObjectAdapter(MainActivity.this, MyObject.getList(this));
setListAdapter(adapter);

getList是我自己的方法。

从列表视图中删除项目的代码

MyObject myObjectToRemove = (MyObject)getListView().getItemAtPosition(positionAtList);
adapter.remove(myObjectToRemove);
adapter.notifyDataSetChanged();