带游标的NullPointException

时间:2016-01-22 06:39:56

标签: android

我在项目中使用Cursor时遇到1个问题。 这是我的DatabaseHelper

package com.example.khuatduytan.quanlytaichinh;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * Created by Khuat Duy Tan on 1/17/2016.
 */
public class DatabaseHelper extends SQLiteOpenHelper {
    private static String DATABASE_NAME = "QuanLyTaiChinh";
    private static String TABLE_USER = "User";
    private static String TABLE_FAMILY_MEMBER = "Family_Member";
    private static String TABLE_TYPE_NOTE = "Type_Note";
    private static String TABLE_NOTE = "Note";
    //Common column name
    public static String KEY_ID = "_id";

    //User table
    private static String KEY_USERNAME = "Username";
    private static String KEY_PASSWORD = "Password";
    private static String KEY_QUESTION = "Question";
    private static String KEY_ANSWER = "Answer";
    private static String KEY_TOTAL_MONEY ="Total_Money";
    private static String KEY_INSERT_FAMILYMEMBER_STATUS = "InsertMember_Status";
    private static String KEY_INSERT_TYPENOTES_STATUS = "Insert_TypeNotes_Status";
    private static String KEY_INSERT_TOTALMONEY_STATUS = "Insert_Money_Status";

    //Family Member table
    public static String KEY_NAME = "Name";
    public static String KEY_AGE = "Age";
    public static String KEY_ID_FAMILY = "Id_Family";

    //Type Notes table
    private static String KEY_NAME_TYPE_NOTES = "Type_Note";

    //Note table
    private static String KEY_CONTENT_NOTE = "Content";
    private static String KEY_DATE_NOTE = "Date_Created";
    private static String KEY_ID_MEMBER_IN_NOTE = "ID_Family_Member";
    private static String KEY_ID_TYPE_NOTE = "ID_Type_Note";
    private static String KEY_MONEY = "Money";

    //User table create statement
    private static String CREATE_USER_TABLE = "CREATE TABLE " + TABLE_USER + " (" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_USERNAME +
            " TEXT, " + KEY_PASSWORD + " TEXT, " + KEY_QUESTION + " TEXT, " + KEY_ANSWER + " TEXT, " + KEY_TOTAL_MONEY + " TEXT, " + KEY_INSERT_FAMILYMEMBER_STATUS +
            " TEXT, " + KEY_INSERT_TYPENOTES_STATUS + " TEXT, " + KEY_INSERT_TOTALMONEY_STATUS + " TEXT" + ")";

    //Family Member table create statement
    private static String CREATE_FAMILY_MEMBER_TABLE = "CREATE TABLE " + TABLE_FAMILY_MEMBER + " (" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_ID_FAMILY +
            " TEXT, " + KEY_NAME + " TEXT, " + KEY_AGE + " TEXT" + ")";

    //Type Note table create statement
    private static String CREATE_TYPE_NOTE_TABLE = "CREATE TABLE " + TABLE_TYPE_NOTE + " (" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_NAME_TYPE_NOTES + " TEXT" + ")";

    //Note table create statement
    private static String CREATE_NOTE_TABLE = "CREATE TABLE " + TABLE_NOTE + " (" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "+ KEY_CONTENT_NOTE + " TEXT, " + KEY_DATE_NOTE + " TEXT, " +
            KEY_ID_MEMBER_IN_NOTE + " TEXT, " + KEY_ID_TYPE_NOTE + " TEXT, " + KEY_MONEY + " TEXT" + ")";

//    private static String[] ALL_KEY_FAMILY_MEMBER_TABLE = new String[]{KEY_ID, KEY_ID_FAMILY, KEY_NAME, KEY_AGE};

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
    }


    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_USER_TABLE);
        db.execSQL(CREATE_FAMILY_MEMBER_TABLE);
        db.execSQL(CREATE_TYPE_NOTE_TABLE);
        db.execSQL(CREATE_NOTE_TABLE);
    }

    public Cursor getDataTableUser(){
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor res = db.rawQuery("SELECT * FROM " + TABLE_USER, null);
        return res;
    }

    public Cursor getDataTableMemberFamily(){
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor res = db.rawQuery("SELECT * FROM " + TABLE_FAMILY_MEMBER, null);
        return res;
    }

    public long insertUserTable(String username, String password, String question, String answer, String totalMoney, String insertMemberStatus, String insertTypeNoteStatus, String insertTotalMoneyStatus){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(KEY_USERNAME,username);
        contentValues.put(KEY_PASSWORD,password);
        contentValues.put(KEY_QUESTION,question);
        contentValues.put(KEY_ANSWER,answer);
        contentValues.put(KEY_TOTAL_MONEY, totalMoney);
        contentValues.put(KEY_INSERT_FAMILYMEMBER_STATUS, insertMemberStatus);
        contentValues.put(KEY_INSERT_TYPENOTES_STATUS, insertTypeNoteStatus);
        contentValues.put(KEY_INSERT_TOTALMONEY_STATUS, insertTotalMoneyStatus);

        long result = db.insert(TABLE_USER, null, contentValues);
        return result;
    }

    public long insertMemberFamilyTable(String idFamily, String name, String age){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(KEY_ID_FAMILY, idFamily);
        contentValues.put(KEY_NAME, name);
        contentValues.put(KEY_AGE, age);
        long result = db.insert(TABLE_FAMILY_MEMBER, null, contentValues);
        return result;
    }

    public long updateUserTable(long id, String username, String password, String question, String answer, String totalMoney, String insertMemberStatus, String insertTypeNoteStatus, String insertTotalMoneyStatus){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(KEY_USERNAME,username);
        contentValues.put(KEY_PASSWORD,password);
        contentValues.put(KEY_QUESTION,question);
        contentValues.put(KEY_ANSWER,answer);
        contentValues.put(KEY_TOTAL_MONEY, totalMoney);
        contentValues.put(KEY_INSERT_FAMILYMEMBER_STATUS, insertMemberStatus);
        contentValues.put(KEY_INSERT_TYPENOTES_STATUS, insertTypeNoteStatus);
        contentValues.put(KEY_INSERT_TOTALMONEY_STATUS, insertTotalMoneyStatus);
        long result = db.update(TABLE_USER, contentValues, KEY_ID + "=" + id, null);
        return result;
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXIST " + TABLE_USER);
        db.execSQL("DROP TABLE IF EXIST " + TABLE_FAMILY_MEMBER);
        db.execSQL("DROP TABLE IF EXIST " + TABLE_TYPE_NOTE);
        db.execSQL("DROP TABLE IF EXIST " + TABLE_NOTE);
        onCreate(db);
    }
}

我在1班

中打电话给Cursor res1 = db.getDataTableUser();
package com.example.khuatduytan.quanlytaichinh;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.TableRow.LayoutParams;
import android.widget.Toast;

public class InsertFamilyMember extends AppCompatActivity {
    Button btnResetInsertFamilyMember, btnSubmitInsertFamilyMember, btnCancelInsertFamilyMember, btnCompleteInsertFamilyMember;
    TextView editTextNameInsertFamilyMember, editTextAgeInsertFamilyMember;
    DatabaseHelper db;
    SimpleCursorAdapter dataAdapter;
    private static final int REQUEST_CODE = 10;
    Intent data;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_insert_family_member);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle("Insert Family Member");

        btnSubmitInsertFamilyMember = (Button) findViewById(R.id.button_submitInsertFamilyMember);
        btnResetInsertFamilyMember = (Button) findViewById(R.id.button_resetInsertFamilyMember);
        btnCancelInsertFamilyMember = (Button) findViewById(R.id.button_cancelInsertFamilyMember);
        btnCompleteInsertFamilyMember = (Button) findViewById(R.id.button_completeInsertFamilyMember);
        editTextNameInsertFamilyMember = (TextView) findViewById(R.id.editText_nameInsertFamilyMember);
        editTextAgeInsertFamilyMember = (TextView) findViewById(R.id.editText_ageInsertFamilyMember);

        db = new DatabaseHelper(this);
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        Bundle extras = getIntent().getExtras();
        final String idUser = extras.getString("IdUser");
        addDataListView();
        addFamilyMember(idUser);
        completeFamilyMember();
        cancelFamilyMember();
        resetFamilyMember();
    }

    public void addDataListView(){
        Cursor cursor = db.getDataTableMemberFamily();
        String form[] = new String []{db.KEY_NAME, db.KEY_AGE};
        int to[] = new int[] {R.id.textView_itemNameInsertFamilyMember, R.id.textView_itemAgeInsertFamilyMember};
        dataAdapter = new SimpleCursorAdapter(this, R.layout.item_memberfamily, cursor, form, to, 0);
        ListView listViewMemberFamily = (ListView) findViewById(R.id.listView_FamilyMember);
        listViewMemberFamily.setAdapter(dataAdapter);
    }

    public void completeFamilyMember(){
        btnCompleteInsertFamilyMember.setOnClickListener(
                new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        confirmDialog();
                    }
                }
        );
    }

    public void resetFamilyMember(){
        btnResetInsertFamilyMember.setOnClickListener(
                new View.OnClickListener(){

                    @Override
                    public void onClick(View v) {
                        editTextNameInsertFamilyMember.setText("");
                        editTextAgeInsertFamilyMember.setText("");
                    }
                }
        );
    }

    public void cancelFamilyMember(){
        btnCancelInsertFamilyMember.setOnClickListener(
                new View.OnClickListener(){

                    @Override
                    public void onClick(View v) {
                        doOpenLogin();
                    }
                }
        );
    }

    public void addFamilyMember(final String idFamily){
        btnSubmitInsertFamilyMember.setOnClickListener(
                new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        String name, age;
                        int temp = 0;
                        name = editTextNameInsertFamilyMember.getText().toString();
                        age = editTextAgeInsertFamilyMember.getText().toString();
                        Cursor res = db.getDataTableMemberFamily();
                        while (res.moveToNext()) {
                            if (res.getString(2).equals(name)) {
                                temp = 1;
                            }
                        }

                        if (temp == 1) {
                            Toast.makeText(InsertFamilyMember.this, "This member is available", Toast.LENGTH_LONG).show();
                            editTextNameInsertFamilyMember.setText("");
                            editTextAgeInsertFamilyMember.setText("");
                        } else {
                            long isInserted = db.insertMemberFamilyTable(idFamily, name, age);
                            if (isInserted == -1) {
                                Toast.makeText(InsertFamilyMember.this, "Insert Unsuccessful", Toast.LENGTH_LONG).show();
                            } else {
                                Toast.makeText(InsertFamilyMember.this, "Insert Successful", Toast.LENGTH_LONG).show();
                            }
                        }
                        addDataListView();
                    }
                }
        );
    }

    private void confirmDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder
                .setMessage("Are you sure?")
                .setPositiveButton("Yes",  new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        Cursor res = db.getDataTableMemberFamily();
                        Cursor res1 = db.getDataTableUser();

                        Bundle extras = getIntent().getExtras();
                        String idFamily = extras.getString("IdUser");
                        long id_User = 0;
                        String idUserSend = null;
                        String username = null;
                        String password = null;
                        String question = null;
                        String answer = null;
                        String totalMoney = null;
                        String insertMemberStatus = null;
                        String insertTypeNoteStatus = null;
                        String insertTotalMoneyStatus = null;
                        while (res1.moveToNext()){
                            String idUser = res1.getString(0);
                            if(idUser.equals(idFamily)){
                                id_User = Long.parseLong(idUser);
                                username = res1.getString(1);
                                password = res1.getString(2);
                                question = res1.getString(3);
                                answer = res1.getString(4);
                                totalMoney = res1.getString(5);
                                insertMemberStatus = "Complete";
                                insertTypeNoteStatus = res1.getString(7);
                                insertTotalMoneyStatus = res1.getString(8);
                                idUserSend = idUser;
                                break;
                            }
                        }
                        long isUpdated = db.updateUserTable(id_User, username, password, question, answer, totalMoney, insertMemberStatus, insertTypeNoteStatus, insertTotalMoneyStatus);
                        if (isUpdated == -1) {
                            Toast.makeText(InsertFamilyMember.this, "Update Unsuccessful", Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(InsertFamilyMember.this, "Update Successful", Toast.LENGTH_LONG).show();
                        }
//                        Bundle bundle = data.getExtras();
//                        User user = bundle.getParcelable("User");
                        doOpenInsertTotalMoney(idUserSend);
                    }
                })
                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                })
                .show();
    }

    public void doOpenLogin(){
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
    }

    public void doOpenInsertTotalMoney(String id){
        Intent intent = new Intent(this, InsertTotalMoney.class);
        intent.putExtra("idUser", id);
        startActivityForResult(intent, REQUEST_CODE);
//        Bundle b = new Bundle();
//        b.putParcelable("User", user);
//        intent.putExtras(b);
//        startActivityForResult(intent, REQUEST_CODE);
    }
}

它正常工作。我在另一个类中使用它,但是当我在这个类中使用时

package com.example.khuatduytan.quanlytaichinh;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class InsertTotalMoney extends AppCompatActivity {

    Button btnSubmitInsertTotalMoney, btnCancelInsertTotalMoney;
    EditText editTextInsertTotalMoney;
    DatabaseHelper db;
    private static final int REQUEST_CODE = 10;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_insert_total_money);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        btnSubmitInsertTotalMoney = (Button) findViewById(R.id.btn_submitInsertTotalMoney);
        btnCancelInsertTotalMoney = (Button) findViewById(R.id.btn_cancelInsertTotalMoney);
        editTextInsertTotalMoney = (EditText) findViewById(R.id.editText_insertTotalMoney);
        doOpenInsertFamilyMember();
        addTotalMoney();
    }

    public void doOpenInsertFamilyMember(){
        btnCancelInsertTotalMoney.setOnClickListener(
                new View.OnClickListener(){

                    @Override
                    public void onClick(View v) {
                        openInsertFamilyMember();
                    }
                }
        );
    }

    public void addTotalMoney(){
        btnSubmitInsertTotalMoney.setOnClickListener(
                new View.OnClickListener(){

                    @Override
                    public void onClick(View v) {
                        confirmDialog();
                    }
                }
        );
    }

    private void confirmDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder
                .setMessage("Are you sure?")
                .setPositiveButton("Yes",  new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {

                        long id_User = 0;
                        String idUserSend = null;
                        String username = null;
                        String password = null;
                        String question = null;
                        String answer = null;
                        String totalMoney = null;
                        String insertMemberStatus = null;
                        String insertTypeNoteStatus = null;
                        String insertTotalMoneyStatus = null;

                        Cursor res = db.getDataTableUser();
                        Bundle extras = getIntent().getExtras();
                        String idUser = extras.getString("idUser");

                        while (res.moveToNext()){
                            if(idUser.equals(res.getString(0))){
                                id_User = Long.parseLong(idUser);
                                username = res.getString(1);
                                password = res.getString(2);
                                question = res.getString(3);
                                answer = res.getString(4);
                                totalMoney = editTextInsertTotalMoney.getText().toString();
                                insertMemberStatus = res.getString(6);
                                insertTypeNoteStatus = res.getString(7);
                                insertTotalMoneyStatus = "Complete";
                                idUserSend = idUser;
                                break;
                            }
                        }
                        long isUpdated = db.updateUserTable(id_User, username, password, question, answer, totalMoney, insertMemberStatus, insertTypeNoteStatus, insertTotalMoneyStatus);
                        if (isUpdated == -1) {
                            Toast.makeText(InsertTotalMoney.this, "Update Unsuccessful", Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(InsertTotalMoney.this, "Update Successful", Toast.LENGTH_LONG).show();
                        }
                        doOpenInsertTypeNotes(idUserSend);
                    }
                })
                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                })
                .show();
    }

    public void openInsertFamilyMember(){
        Intent intent = new Intent(this, InsertFamilyMember.class);
        startActivity(intent);
    }

    public void doOpenInsertTypeNotes(String s){
        Intent intent = new Intent(this, InsertTypeNotes.class);
        intent.putExtra("idUser", s);
        startActivityForResult(intent, REQUEST_CODE);
    }

}

Cursor res = db.getDataTableUser();处出现NullPointException 你能帮我解决这个bug吗? 我的logcat

01-22 01:38:31.679 1331-1331/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                 Process: com.example.khuatduytan.quanlytaichinh, PID: 1331
                                                 java.lang.NullPointerException
                                                     at com.example.khuatduytan.quanlytaichinh.InsertTotalMoney$5.onClick(InsertTotalMoney.java:92)
                                                     at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
                                                     at android.os.Handler.dispatchMessage(Handler.java:102)
                                                     at android.os.Looper.loop(Looper.java:136)
                                                     at android.app.ActivityThread.main(ActivityThread.java:5001)
                                                     at java.lang.reflect.Method.invokeNative(Native Method)
                                                     at java.lang.reflect.Method.invoke(Method.java:515)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
                                                     at dalvik.system.NativeStart.main(Native Method)

3 个答案:

答案 0 :(得分:0)

  

NullPointException出现在Cursor res = db.getDataTableUser();

因为您在使用之前尚未初始化db变量。

添加以下语句以初始化db变量

db = new DatabaseHelper(InsertTotalMoney.this);
Cursor res = db.getDataTableUser();

答案 1 :(得分:0)

你已经在类的顶层声明了DatabaseHelper db;变量,但你确实在任何地方分配了db变量,请先分配你的db变量然后使用db。

即。 db = DatabaseHelper.getInstance(this);

答案 2 :(得分:0)

在confirmDialog()中,在对象db中生成DatabaseHelper参考。

db = new DatabaseHelper(this);
Cursor res = db.getDataTableUser();