【问题标题】:Application crashing because of NullPointerException由于 NullPointerException 导致应用程序崩溃
【发布时间】:2014-04-18 23:37:05
【问题描述】:

我正在使用一个列表视图,单击它会打开一个对话框,其中包含一个编辑文本和一个按钮。单击按钮时,在 editText 中输入的值将保存在之前按下的 listview 项的 textView 中。问题是,如果我重新打开应用程序,则不再保存该值。我尝试使用 sharedPrefences 保存它,但它崩溃并显示 3 个 nullpointerexception 并且无法处理它们。

这是我的:

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();
    }

}

还有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;
    }

}

logcat:

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 第 45 行:

tabHost.addTab(NotaSpec);

NoteAdapter.java 第 46 行:

return result.length;

Note.java 第 34 行:

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

【问题讨论】:

    标签: java android android-listview nullpointerexception


    【解决方案1】:

    你的字符串数组在这里为空:

    NoteAdapter.java 第 46 行:

    return result.length;
    

    因为是类字段,所以你从一个参数填充到构造函数中:

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

    你在这里作为null传递(作为第二个参数传递,它应该是第三个):

    Note.java 第 34 行:

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

    将它作为参数传递是没有意义的,因为它是一个公共常量(public static final)。

    【讨论】:

    • 这是工作.. 但现在我在这里得到 nullpointerexception: holder.text.setText(savedEntries[position]); .. NoteAdapter.java 中的第 76 行。非常感谢!
    • 我猜是文本变量(TextView 对象)为空。
    • 不应该填充数组。稍后将由用户填充。当应用程序启动时,TextView 应该为 null,并且只有在用户输入值后,它才应该填充该值。如何解决?
    • 您必须逐行调试才能发现这一点,或者尝试限制该问题并在 stackoverflow 上提出另一个问题。
    猜你喜欢
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 2012-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-17
    • 2016-08-05
    相关资源
    最近更新 更多