Android:getWritableDatabase()上的erro NullPointerException

时间:2015-03-17 02:38:34

标签: java android sqlite nullpointerexception

我在getWritableDatabase()

上遇到问题NullPointerException

数据库

我正在尝试构建一个将一些信息存储在SQLite表中的小应用程序。但是我总是在getWritableDatabase方法中收到“Java.lang.NullPointerException”异常。谁能帮我?所有代码都在下面。

public class PacienteDatabase extends SQLiteOpenHelper {

private static final String DB_NAME = "paciente.sqlite";
private static final int VERSION = 1;
private static final String TABLE = "paciente";


public PacienteDatabase(Context context) {
    super(context, DB_NAME, null, VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    // Crear tabla paciente
    db.execSQL("create table paciente (" +
            "_id integer primary key autoincrement, start_date integer)");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

}

激活

public class RegistroPaciente extends ActionBarActivity {

private Button mBotonOk;

private PacienteDatabase mPaciente;
private Context c;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_registro_paciente);
    mPaciente = new PacienteDatabase(c);

    mBotonOk = (Button)findViewById(R.id.boton_registro_ok);


    mBotonOk.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            ContentValues datos = new ContentValues();

            datos.put("start_date", 1000 );

            mPaciente.getWritableDatabase().insert("paciente", null, datos);

            finish();
        }
    });
}

log cat错误

03-16 22:22:46.531    1181-1181/com.example.franciscodelgadogarcia.projecto E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.franciscodelgadogarcia.projecto, PID: 1181
java.lang.NullPointerException
        at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:224)
        at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
        at com.example.franciscodelgadogarcia.projecto.RegistroPaciente$1.onClick(RegistroPaciente.java:84)
        at android.view.View.performClick(View.java:4438)
        at android.view.View$PerformClick.run(View.java:18422)
        at android.os.Handler.handleCallback(Handler.java:733)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5017)
        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:779)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
        at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:1)

c的{​​{1}}对象Context在将null传递给c类构造函数之前对其进行初始化:

PacienteDatabase