简体   繁体   中英

Why am I getting a NullPointerException on this line?

My code which previously worked fine, is now throwing a NPE. It's not on a new line either so I am pretty confused. Can someone point me in the right direction?

The problem line is identified about half way down.

public class FavouritesActivity extends Activity {

private String mFavourites;
ArrayAdapter <String> adapter;
List<String> list;

private ListView lv;

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

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

    SharedPreferences preferences = this.getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);
    list = new ArrayList<String>();         
    Map<String, ?> prefsMap = preferences.getAll();
    for (Map.Entry<String, ?> entry: prefsMap.entrySet()) {
        list.add(entry.getValue().toString());   //THIS IS THE PROBLEM <<<<<<<<<<<<<<<<<<
    } 

    adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list); 

    lv.setAdapter(adapter);

     lv.setOnItemLongClickListener(new OnItemLongClickListener() {
            // setting onItemLongClickListener and passing the position to the function
                      @Override
            public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                    int position, long arg3) {
                String mFavourites =(lv.getItemAtPosition(position).toString());
                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("Do you want delete this item?");
            alert.setPositiveButton("YES", new DialogInterface.OnClickListener() {

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

                        // main code on after clicking yes
                        list.remove(deletePosition);

                        Operator();


                        adapter.notifyDataSetChanged();
                        adapter.notifyDataSetInvalidated();


                }
            });
            alert.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    dialog.dismiss();
                }
            });


            alert.show();


        }

 protected void Operator() {
     SharedPreferences preferences = this.getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);

        SharedPreferences.Editor editor = preferences.edit();

        editor.remove(mFavourites);
        editor.commit();

    }

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

Here is the LogCat:

01-10 14:08:59.850: E/AndroidRuntime(2194): FATAL EXCEPTION: main
01-10 14:08:59.850: E/AndroidRuntime(2194): Process: com.LifeSchematics.msg, PID: 2194
01-10 14:08:59.850: E/AndroidRuntime(2194): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.LifeSchematics.msg/com.LifeSchematics.msg.FavouritesActivity}: java.lang.NullPointerException
01-10 14:08:59.850: E/AndroidRuntime(2194):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
01-10 14:08:59.850: E/AndroidRuntime(2194):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
01-10 14:08:59.850: E/AndroidRuntime(2194):     at android.app.ActivityThread.access$800(ActivityThread.java:135)
01-10 14:08:59.850: E/AndroidRuntime(2194):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
01-10 14:08:59.850: E/AndroidRuntime(2194):     at android.os.Handler.dispatchMessage(Handler.java:102)
01-10 14:08:59.850: E/AndroidRuntime(2194):     at android.os.Looper.loop(Looper.java:136)
01-10 14:08:59.850: E/AndroidRuntime(2194):     at android.app.ActivityThread.main(ActivityThread.java:5017)
01-10 14:08:59.850: E/AndroidRuntime(2194):     at java.lang.reflect.Method.invokeNative(Native Method)
01-10 14:08:59.850: E/AndroidRuntime(2194):     at java.lang.reflect.Method.invoke(Method.java:515)
01-10 14:08:59.850: E/AndroidRuntime(2194):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
01-10 14:08:59.850: E/AndroidRuntime(2194):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
01-10 14:08:59.850: E/AndroidRuntime(2194):     at dalvik.system.NativeStart.main(Native Method)
01-10 14:08:59.850: E/AndroidRuntime(2194): Caused by: java.lang.NullPointerException
01-10 14:08:59.850: E/AndroidRuntime(2194):     at com.LifeSchematics.msg.FavouritesActivity.onCreate(MySupplementsActivity.java:40)
01-10 14:08:59.850: E/AndroidRuntime(2194):     at android.app.Activity.performCreate(Activity.java:5231)
01-10 14:08:59.850: E/AndroidRuntime(2194):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
01-10 14:08:59.850: E/AndroidRuntime(2194):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)

You get NullPointerException because some preference values were stored as null and entry.getValue() is null. So add null checking before calling toString()

for (Map.Entry<String, ?> entry: prefsMap.entrySet()) {
    final Object value = entry.getValue();
    list.add(value == null ? "null" : value.toString());
} 

Or

for (Map.Entry<String, ?> entry: prefsMap.entrySet()) {
    final Object value = entry.getValue();
    if (value != null) {
        list.add(value.toString());
    }
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM