How to delete list view items (when list is populated by SharedPreferences

若如初见. 提交于 2019-12-12 02:45:18

问题


I have a list view successfully being populated by SharedPreferences.

public class FavouritesActivity extends Activity {

ArrayAdapter<String> adapter;
List<String> List;
private ListView lv;

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

    lv = (ListView) findViewById(R.id.My_Favourites);

    SharedPreferences preferences = this.getSharedPreferences("MyPreferences",
                Context.MODE_PRIVATE);
    ArrayList<String> List = new ArrayList<String>();
    Map<String, ?> prefsMap = preferences.getAll();
    for (Map.Entry<String, ?> entry: prefsMap.entrySet()) {
        List.add(entry.getValue().toString());      
    } 
    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, List);

    lv.setAdapter(arrayAdapter);

This works great, but now I want to delete items from the list.

 lv.setOnItemLongClickListener(new OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                    int position, long arg3) {
                removeItemFromList(position);
                return true;
            }
        });
}

protected void removeItemFromList(int position) {
        final int deletePosition = position;
        AlertDialog.Builder alert = new AlertDialog.Builder(
                FavouritesActivity.this);

        alert.setTitle("Delete");
        alert.setMessage("Are you sure you want delete this item?");
        alert.setPositiveButton("YES", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                    List.remove(deletePosition);
                    adapter.notifyDataSetChanged();
                    adapter.notifyDataSetInvalidated();
            }
        });
        alert.setNegativeButton("CANCEL",new DialogInterface.OnClickListener(){

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        alert.show();
    }

Unfortunately this section does not work. The AlertView displays, but selecting confirm crashes the app.

I have a feeling it is something to do with the array adapter, but I'm struggling to spot it.

Can anyone point me in the right direction?

CRASH LOG:

01-10 10:35:45.950: E/AndroidRuntime(1370): FATAL EXCEPTION: main
01-10 10:35:45.950: E/AndroidRuntime(1370): Process: com.LifeSchematics.msg, PID: 1370
01-10 10:35:45.950: E/AndroidRuntime(1370): java.lang.NullPointerException
01-10 10:35:45.950: E/AndroidRuntime(1370):     at com.LifeSchematics.msg.FavouritesActivity$2.onClick(FavouritesActivity.java:78)
01-10 10:35:45.950: E/AndroidRuntime(1370):     at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
01-10 10:35:45.950: E/AndroidRuntime(1370):     at android.os.Handler.dispatchMessage(Handler.java:102)
01-10 10:35:45.950: E/AndroidRuntime(1370):     at android.os.Looper.loop(Looper.java:136)
01-10 10:35:45.950: E/AndroidRuntime(1370):     at android.app.ActivityThread.main(ActivityThread.java:5017)
01-10 10:35:45.950: E/AndroidRuntime(1370):     at java.lang.reflect.Method.invokeNative(Native Method)
01-10 10:35:45.950: E/AndroidRuntime(1370):     at java.lang.reflect.Method.invoke(Method.java:515)
01-10 10:35:45.950: E/AndroidRuntime(1370):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
01-10 10:35:45.950: E/AndroidRuntime(1370):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
01-10 10:35:45.950: E/AndroidRuntime(1370):     at dalvik.system.NativeStart.main(Native Method)

回答1:


Try this..

I guess you getting NPE because your not initialize both List<String> List; and ArrayAdapter<String> adapter;

Just replace it..

SharedPreferences preferences = this.getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);

    //correction here
    List = new ArrayList<String>();         
    Map<String, ?> prefsMap = preferences.getAll();
    for (Map.Entry<String, ?> entry: prefsMap.entrySet()) {
        List.add(entry.getValue().toString());      
    } 

    // correction here
    arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, List);     

    lv.setAdapter(arrayAdapter);



回答2:


Your arraylist is not initialized!

ArrayAdapter<String> adapter;
List<String> List;

to this:

ArrayAdapter<String> adapter = new ArrayList<String>();
List<String> List = new List<String>();

Also, from what i can read from your code your are using this array list only for remove things. But no things are added in this adapter since you are using another one to populate your list.




回答3:


Try This:

           @Override
            public void onClick(DialogInterface dialog, int which) {
                // TO DO Auto-generated method stub

                    List.remove(position);
                    adapter.notifyDataSetChanged();
                    adapter.notifyDataSetInvalidated();


            }
        });


来源:https://stackoverflow.com/questions/21048436/how-to-delete-list-view-items-when-list-is-populated-by-sharedpreferences

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!