java.lang.NullPointerException,在 Android 应用程序上尝试从空对象引用上的字段读取

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32421273/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 12:30:47  来源:igfitidea点击:

java.lang.NullPointerException, Attempt to read from field on a null object reference, on an Android app

javaandroidsqlite

提问by

I need to add the share feature to my Android app (The app is for writing notes and store them in a SQLite database) (The share button only shares the body of the note). I did it, but when I press "Share" button, it shows FC (Force Close) and the app stops.

我需要将共享功能添加到我的 Android 应用程序(该应用程序用于编写笔记并将它们存储在 SQLite 数据库中)(共享按钮仅共享笔记的正文)。我做到了,但是当我按下“共享”按钮时,它显示 FC(强制关闭)并且应用程序停止。

The code of the share feature (It's in the MainActivity class):

分享功能的代码(在MainActivity类中):

...
@Override
    public boolean onContextItemSelected(final MenuItem item) {
        switch (item.getItemId()) {
            case R.id.share:
                String shareBody = NotesModel.actualNote.body;
                Intent shareIntent = new Intent("android.intent.action.SEND");
                shareIntent.setType("text/plain");
                shareIntent.putExtra("android.intent.extra.TEXT", shareBody);
                startActivity(shareIntent);
                return true;
                ...

The whole MainActivity class:

整个 MainActivity 类:

package com.twitter.i_droidi.mynotesdonation;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.List;
import com.oguzdev.circularfloatingactionmenu.library.FloatingActionButton;

public class MainActivity extends ActionBarActivity implements AdapterView.OnItemClickListener, View.OnClickListener {

    ListView lv;
    NotesDataSource nDS;
    List<NotesModel> notesList;
    String[] notes;
    int i;
    ArrayAdapter<String> adapter;
    FloatingActionButton actionButton;
    public static final String floatingButtonTag = "";
    CheckBox checkBox;

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

        View checkBoxView = View.inflate(this, R.layout.checkbox, null);
        checkBox = (CheckBox) checkBoxView.findViewById(R.id.checkboxDialog);
        checkBox.setOnClickListener(this);
        loadSavedPreferences();

        checkBox.setText(R.string.do_not_show_this_again);
        final Context context = this;
        AlertDialog.Builder mainDialog = new AlertDialog.Builder(context);
        mainDialog.setTitle(R.string.thanks);
        mainDialog.setMessage(R.string.main_dialog_body);
        mainDialog.setIcon(R.drawable.my_notes);
        mainDialog.setView(checkBoxView);
        mainDialog.setPositiveButton(R.string.welcome, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // Do Not Do Anything.
            }
        });
        AlertDialog alertDialog = mainDialog.create();
        if (checkBox.isChecked() == false) {
            alertDialog.show();
        }

        ImageView icon = new ImageView(this);
        icon.setImageDrawable(getResources().getDrawable(R.drawable.ic_action_new));

        actionButton = new FloatingActionButton.Builder(this)
                .setContentView(icon)
                .setBackgroundDrawable(R.drawable.the_selector)
                .build();
        actionButton.setOnClickListener(this);
        actionButton.setTag(floatingButtonTag);

        nDS = new NotesDataSource(this);
        lv = (ListView) findViewById(R.id.lv);

        nDS.open();
        notesList = nDS.getAllNotes();
        nDS.close();

        notes = new String[notesList.size()];

        for (i = 0; i < notesList.size(); i++) {
            notes[i] = notesList.get(i).getTitle();
        }

        adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1,
                android.R.id.text1, notes);
        lv.setAdapter(adapter);

        registerForContextMenu(lv);
        lv.setOnItemClickListener(this);
    }

    public void loadSavedPreferences() {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        boolean checkBoxStatus = prefs.getBoolean("Status", false);

        if (checkBoxStatus) {
            checkBox.setChecked(true);
        } else {
            checkBox.setChecked(false);
        }
    }

    public void savePreferences(String key, boolean status) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

        SharedPreferences.Editor editor = prefs.edit();
        editor.putBoolean(key, status);
        editor.commit();
    }

    @Override
    public void onClick(View v) {
        if (v.getTag() != null && v.getTag().equals(floatingButtonTag)) {
            Intent nNote = new Intent(this, CreateNote.class);
            startActivity(nNote);
        }

        savePreferences("Status", checkBox.isChecked());
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent nView = new Intent(this, ViewEditNote.class);
        nView.putExtra("id", notesList.get(position).getId());
        nView.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(nView);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_item_selected, menu);
        super.onCreateContextMenu(menu, v, menuInfo);
    }

    @Override
    public boolean onContextItemSelected(final MenuItem item) {
        switch (item.getItemId()) {
            case R.id.share:
                String shareBody = NotesModel.body;
                Intent shareIntent = new Intent("android.intent.action.SEND");
                shareIntent.setType("text/plain");
                shareIntent.putExtra("android.intent.extra.TEXT", shareBody);
                startActivity(shareIntent);
                return true;

            case R.id.delete:
                AlertDialog.Builder deleteDialog = new AlertDialog.Builder(this);
                deleteDialog.setTitle(getString(R.string.delete_title));
                deleteDialog.setMessage(R.string.delete_body);
                deleteDialog.setIcon(R.drawable.my_notes);
                deleteDialog.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface deleteDialog, int witch) {
                        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
                        nDS.open();
                        nDS.deleteNote(notesList.get(info.position).getId());
                        notesList = nDS.getAllNotes();
                        nDS.close();

                        notes = new String[notesList.size()];

                        for (i = 0; i < notesList.size(); i++) {
                            notes[i] = notesList.get(i).getTitle();
                        }

                        adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1,
                                android.R.id.text1, notes);
                        lv.setAdapter(adapter);

                        registerForContextMenu(lv);
                        lv.setOnItemClickListener(MainActivity.this);

                        Toast nDelete = Toast.makeText(MainActivity.this, R.string.deleted, Toast.LENGTH_LONG);
                        nDelete.show();
                        return;
                    }
                });
                deleteDialog.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface deleteDialog, int which) {
                        // Do Not Do Anything.
                    }
                });
                deleteDialog.show();
                return true;
        }
        return super.onContextItemSelected(item);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.mainMenuAbout:
                AlertDialog.Builder aboutDialog = new AlertDialog.Builder(this);
                aboutDialog.setTitle(getString(R.string.about_title));
                aboutDialog.setMessage(R.string.about_body);
                aboutDialog.setIcon(R.drawable.my_notes);
                aboutDialog.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface aboutDialog, int witch) {
                        // Do Not Do Anything.
                    }
                });

                aboutDialog.show();
                return true;

            case R.id.mainMenuBackupHelp:
                AlertDialog.Builder backupHelpDialog = new AlertDialog.Builder(this);
                backupHelpDialog.setTitle(getString(R.string.backup_help_title));
                backupHelpDialog.setMessage(R.string.backup_help_body);
                backupHelpDialog.setIcon(R.drawable.my_notes);
                backupHelpDialog.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface backupHelpDialog, int witch) {
                        // Do Not Do Anything.
                    }
                });

                backupHelpDialog.show();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

The NotesModel class:

NotesModel 类:

package com.twitter.i_droidi.mynotesdonation;

public class NotesModel {

    int id;
    String title;
    String body;
    static NotesModel actualNote;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }
}

The NotesDataSource class:

NotesDataSource 类:

package com.twitter.i_droidi.mynotesdonation;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;

public class NotesDataSource {

    DB myDB;
    SQLiteDatabase sql;
    public static NotesModel note;

    String[] getAllColumns = new String[]{DB.ID, DB.TITLE, DB.BODY};

    public NotesDataSource(Context context) {
        myDB = new DB(context);
    }

    public void open() {
        try {
            sql = myDB.getWritableDatabase();
        } catch (Exception ex) {
            Log.d("Error in your database!", ex.getMessage());
        }
    }

    public void close() {
        sql.close();
    }

    public void createNote(String title, String body) {
        ContentValues note = new ContentValues();
        note.put(myDB.TITLE, title);
        note.put(myDB.BODY, body);
        sql.insert(myDB.TABLE_NAME, null, note);
    }

    public NotesModel getNote(int id) {
        note = new NotesModel();

        Cursor cursor = sql.rawQuery("SELECT * FROM " + DB.TABLE_NAME + " WHERE " + DB.ID + " = ?", new String[]{id + ""});

        if (cursor.getCount() > 0) {
            cursor.moveToFirst();
            note.setId(cursor.getInt(0));
            note.setTitle(cursor.getString(1));
            note.setBody(cursor.getString(2));
            cursor.close();
        }
        return note;
    }

    public void updateNote(int id, String title, String body) {
        ContentValues note = new ContentValues();
        note.put(myDB.TITLE, title);
        note.put(myDB.BODY, body);
        sql.update(myDB.TABLE_NAME, note, myDB.ID + " = " + id, null);
    }

    public void deleteNote(Object id) {
        sql.delete(myDB.TABLE_NAME, myDB.ID + " = " + id, null);
    }

    public List<NotesModel> getAllNotes() {
        List<NotesModel> notesList = new ArrayList<NotesModel>();

        Cursor cursor = sql.query(myDB.TABLE_NAME, getAllColumns, null, null, null, null, null);
        cursor.moveToFirst();

        while (!cursor.isAfterLast()) {
            NotesModel notes = new NotesModel();
            notes.setId(cursor.getInt(0));
            notes.setTitle(cursor.getString(1));
            notes.setBody(cursor.getString(2));

            notesList.add(notes);
            cursor.moveToNext();
        }

        cursor.close();
        return notesList;
    }
}

The logcat:

日志猫:

09-06 01:53:10.263  24553-24553/com.twitter.i_droidi.mynotesdonation E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.twitter.i_droidi.mynotesdonation, PID: 24553
    java.lang.NullPointerException: Attempt to read from field 'java.lang.String com.twitter.i_droidi.mynotesdonation.NotesModel.body' on a null object reference
            at com.twitter.i_droidi.mynotesdonation.MainActivity.onContextItemSelected(MainActivity.java:144)
            at android.app.Activity.onMenuItemSelected(Activity.java:2905)
            at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:325)
            at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:147)
            at android.support.v7.internal.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:100)
            at com.android.internal.policy.impl.PhoneWindow$DialogMenuCallback.onMenuItemSelected(PhoneWindow.java:4701)
            at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:761)
            at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
            at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:904)
            at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:894)
            at com.android.internal.view.menu.MenuDialogHelper.onClick(MenuDialogHelper.java:167)
            at com.android.internal.app.AlertController$AlertParams.onItemClick(AlertController.java:1082)
            at android.widget.AdapterView.performItemClick(AdapterView.java:305)
            at android.widget.AbsListView.performItemClick(AbsListView.java:1146)
            at android.widget.AbsListView$PerformClick.run(AbsListView.java:3053)
            at android.widget.AbsListView.run(AbsListView.java:3860)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

回答by Apoorva

It seems like you haven't initialised the actualNote field in the NotesModel class. Try saying

您似乎还没有初始化 NotesModel 类中的 actualNote 字段。试着说

static NotesModel actualNote = new NotesModel();

回答by Kushal

Why you are making inner static object in this case, just use :

为什么在这种情况下要制作内部静态对象,只需使用:

public class NotesModel {

    int id;
    String title;
    public static String body;

    ...
}

and fetch like :

并获取如下:

NotesModel.body

EDIT :

编辑 :

Use Getter method if you do not want staticidentifier:

如果您不需要static标识符,请使用 Getter 方法:

NotesModel mModel = new NotesModel();
mModel.setBody(" String with your body ");
String shareBody = mModel.getBody();    // Getter method