Java – Application crashes due to NullPointerException

Application crashes due to NullPointerException… here is a solution to the problem.

Application crashes due to NullPointerException

I’m using a ListView and clicking it opens a dialog with an edit text and a button. When the button is clicked, the value entered in editText is saved in the textView of the previously pressed ListView item. The problem is that if I reopen the app, the value will no longer be saved. I tried saving it with sharedPrefences, but it crashes and shows 3 nullpointerexceptions and can’t handle them.

Here’s mine:

Carnet.java

package com.cngcnasaud.orar;

import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;

@SuppressWarnings("deprecation")
public class Carnet extends TabActivity {
     TabSpec Names
    private static final String NOTA_SPEC = "Note";
    private static final String ABSENTE_SPEC = "Absente";
    private static final String MEDII_SPEC = "Medii";

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.carnet);

TabHost tabHost = getTabHost();

TabSpec NotaSpec = tabHost.newTabSpec(NOTA_SPEC);
         Tab Icon
        NotaSpec.setIndicator(NOTA_SPEC, getResources().getDrawable(R.drawable.nota_open));
        Intent notaIntent = new Intent(this, Note.class);
         Tab Content
        NotaSpec.setContent(notaIntent);

TabSpec AbsenteSpec = tabHost.newTabSpec(ABSENTE_SPEC);
        AbsenteSpec.setIndicator(ABSENTE_SPEC, getResources().getDrawable(R.drawable.nota_open));
        Intent absenteIntent = new Intent(this, Absente.class);
        AbsenteSpec.setContent(absenteIntent);

TabSpec MediiSpec = tabHost.newTabSpec(MEDII_SPEC);
        AbsenteSpec.setIndicator(MEDII_SPEC, getResources().getDrawable(R.drawable.nota_open));
        Intent mediiIntent = new Intent(this, MediiL.class);
        AbsenteSpec.setContent(mediiIntent);

 Adding all TabSpec to TabHost
        tabHost.addTab(NotaSpec); 
        tabHost.addTab(AbsenteSpec); 
        tabHost.addTab(MediiSpec);

}
}

Note.java

package com.cngcnasaud.orar;

import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.view.Menu;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class Note extends Activity {

private static final ListAdapter NoteAdapter = null;
    ListView lv;
    Context context;
    ArrayList<?> prgmName;
    TextView text;

public static String[] prgmNameList = { "Romana   - ", "Matematica   - ",
            "Lb. Engleza   - ", "Lb. Germana/Franceza - ", "Istorie   - ",
            "Geografie   - ", "Biologie   - ", "Fizica   - ", "Ed. Fizica   - " };

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

text = (TextView) findViewById(R.id.textView2);

context = this;

lv = (ListView) findViewById(R.id.listView);
        lv.setAdapter(new NoteAdapter(this, prgmNameList, null));

}

@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;
    }

@Override
    protected void onStop() {
         TODO Auto-generated method stub

NoteAdapter adapter = (NoteAdapter) lv.getAdapter();

 Variable is public for clarity.
        String toSave = EncodeDecode.encode(adapter.savedEntries);
        SharedPreferences.Editor editor = getSharedPreferences("LV Data",
                MODE_PRIVATE).edit();
        editor.putString("TVEntries", toSave);
        editor.commit();
    }

@Override
    protected void onResume() {
         TODO Auto-generated method stub

SharedPreferences prefs = getSharedPreferences("LV Data", MODE_PRIVATE);
        String encoded = prefs.getString("TVEntries", "");

String[] entries;
        if (encoded.equals(""))
            entries = null;
        else
            entries = EncodeDecode.decode(encoded);

NoteAdapter adapter = (NoteAdapter) lv.getAdapter();
        adapter.savedEntries = entries;
        lv.setAdapter(adapter);

super.onResume();
    }

}

and NoteAdapter .java:

package com.cngcnasaud.orar;

import java.util.Arrays;

import android.app.Dialog;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

public class NoteAdapter extends BaseAdapter {

String[] result;
    Context context;
    int[] imageId;
    private static LayoutInflater inflater = null;
    private Dialog dialog;
    String[] savedEntries;
    String[] saved = null;

public NoteAdapter(Note note, String[] saved, String[] prgmNameList) {
         TODO Auto-generated constructor stub
        result = prgmNameList;
        context = note;
        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

if (saved == null) {
            savedEntries = new String[result.length];
            Arrays.fill(savedEntries, "");
        } else
            savedEntries = saved;

}

@Override
    public int getCount() {
         TODO Auto-generated method stub
        return result.length;
    }

@Override
    public Object getItem(int position) {
         TODO Auto-generated method stub
        return savedEntries[position];
    }

@Override
    public long getItemId(int position) {
         TODO Auto-generated method stub
        return position;
    }

public class Holder {
        TextView tv;
        ImageView img;
        public TextView text;
    }

@Override
    public View getView(final int position, View convertView, ViewGroup parent) {
         TODO Auto-generated method stub

final Holder holder = new Holder();
        View rowView;
        rowView = inflater.inflate(R.layout.note_items, null);
        holder.tv = (TextView) rowView.findViewById(R.id.textView1);
        holder.text = (TextView) rowView.findViewById(R.id.textView2);
        holder.text.setText(savedEntries[position]);
        holder.img = (ImageView) rowView.findViewById(R.id.imageView1);

rowView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                 TODO Auto-generated method stub
                dialog = new Dialog(context);
                dialog.setContentView(R.layout.dialog);
                dialog.setTitle("Materie:" + result[position]);

final EditText txtMode = (EditText) dialog
                        .findViewById(R.id.dialog);
                Button btnSave = (Button) dialog.findViewById(R.id.bsave);

btnSave.setOnClickListener(new OnClickListener() {

@Override
                    public void onClick(View v) {

String data = txtMode.getText().toString();
                        holder.text.setText(data);

savedEntries[position] = data;

dialog.dismiss();
                        Log.d("data", data);
                    }
                });
                dialog.show();
            }

});
        return rowView;
    }

}

Log:

04-18 19:27:28.558: E/AndroidRuntime(1419): FATAL EXCEPTION: main
04-18 19:27:28.558: E/AndroidRuntime(1419): Process: com.cngcnasaud.orar, PID: 1419
04-18 19:27:28.558: E/AndroidRuntime(1419): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.cngcnasaud.orar/com.cngcnasaud.orar.Carnet}: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.cngcnasaud.orar/com.cngcnasaud.orar.Note}: java.lang.NullPointerException
04-18 19:27:28.558: E/AndroidRuntime(1419):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
04-18 19:27:28.558: E/AndroidRuntime(1419):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
04-18 19:27:28.558: E/AndroidRuntime(1419):     at android.app.ActivityThread.access$800(ActivityThread.java:135)
04-18 19:27:28.558: E/AndroidRuntime(1419):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
04-18 19:27:28.558: E/AndroidRuntime(1419):     at android.os.Handler.dispatchMessage(Handler.java:102)
04-18 19:27:28.558: E/AndroidRuntime(1419):     at android.os.Looper.loop(Looper.java:136)
04-18 19:27:28.558: E/AndroidRuntime(1419):     at android.app.ActivityThread.main(ActivityThread.java:5017)
04-18 19:27:28.558: E/AndroidRuntime(1419):     at java.lang.reflect.Method.invokeNative(Native Method)
04-18 19:27:28.558: E/AndroidRuntime(1419):     at java.lang.reflect.Method.invoke(Method.java:515)
04-18 19:27:28.558: E/AndroidRuntime(1419):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-18 19:27:28.558: E/AndroidRuntime(1419):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-18 19:27:28.558: E/AndroidRuntime(1419):     at dalvik.system.NativeStart.main(Native Method)
04-18 19:27:28.558: E/AndroidRuntime(1419): Caused by: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.cngcnasaud.orar/com.cngcnasaud.orar.Note}: java.lang.NullPointerException
04-18 19:27:28.558: E/AndroidRuntime(1419):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
04-18 19:27:28.558: E/AndroidRuntime(1419):     at android.app.ActivityThread.startActivityNow(ActivityThread.java:2035)
04-18 19:27:28.558: E/AndroidRuntime(1419):     at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:135)
04-18 19:27:28.558: E/AndroidRuntime(1419):     at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:347)
04-18 19:27:28.558: E/AndroidRuntime(1419):     at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:749)
04-18 19:27:28.558: E/AndroidRuntime(1419):     at android.widget.TabHost.setCurrentTab(TabHost.java:413)
04-18 19:27:28.558: E/AndroidRuntime(1419):     at android.widget.TabHost.addTab(TabHost.java:240)
04-18 19:27:28.558: E/AndroidRuntime(1419):     at com.cngcnasaud.orar.Carnet.onCreate(Carnet.java:45)
04-18 19:27:28.558: E/AndroidRuntime(1419):     at android.app.Activity.performCreate(Activity.java:5231)
04-18 19:27:28.558: E/AndroidRuntime(1419):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-18 19:27:28.558: E/AndroidRuntime(1419):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
04-18 19:27:28.558: E/AndroidRuntime(1419):     ... 11 more
04-18 19:27:28.558: E/AndroidRuntime(1419): Caused by: java.lang.NullPointerException
04-18 19:27:28.558: E/AndroidRuntime(1419):     at com.cngcnasaud.orar.NoteAdapter.getCount(NoteAdapter.java:46)
04-18 19:27:28.558: E/AndroidRuntime(1419):     at android.widget.ListView.setAdapter(ListView.java:480)
04-18 19:27:28.558: E/AndroidRuntime(1419):     at com.cngcnasaud.orar.Note.onCreate(Note.java:34)
04-18 19:27:28.558: E/AndroidRuntime(1419):     at android.app.Activity.performCreate(Activity.java:5231)
04-18 19:27:28.558: E/AndroidRuntime(1419):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-18 19:27:28.558: E/AndroidRuntime(1419):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
04-18 19:27:28.558: E/AndroidRuntime(1419):     ... 21 more

Carnet.java line 45:

tabHost.addTab(NotaSpec);

NoteAdapter.java line 46:

return result.length;

Note.java line 34:

 lv.setAdapter(new NoteAdapter(this, prgmNameList, null));

Solution

Your array of strings is empty here:

NoteAdapter.java line 46:

return result.length;

Because it is a class field, you populate it from the parameter into the constructor:

public NoteAdapter(Note note, String[] saved, String[] prgmNameList) {
     TODO Auto-generated constructor stub
    result = prgmNameList;

You pass as null here (as the second parameter, it should be the third):

Note.java Line 34:

lv.setAdapter(new NoteAdapter(this, prgmNameList, null));

It doesn’t make sense to pass it as a parameter because it’s a public static final.

Related Problems and Solutions