我试图创建SQLiteDatabase时出现NullPointerException

时间:2014-01-17 20:20:57

标签: java android

我正在尝试创建sqlite数据库,这是我的代码。每次我尝试运行我的应用程序时,它都会向我发送很多错误。我认为这是模拟器问题,但这是我的代码和错误。 我需要帮助。我不知道该怎么办。

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class saeedHelperBD extends SQLiteOpenHelper {

private static final String DATABASE_NAME = "saeedDataBase";
private static final String TABLE_NAME = "saeedTable";
private static final int DATABASE_VERSION = 1;
private static final String UID = "_id";
private static final String NAME = "Name";
private static final String ADRESS = "Adress";
private static final String CREAT_TABLE ="CREATE TABLE " + TABLE_NAME + " (" + UID + "                INTEGER PRIMARY KEY AUTOINCREMENT , " + NAME + " VARCHAR(225));";
private static final String DROP_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME;
private Context context;
public saeedHelperBD(Context con) {
    super(con, DATABASE_NAME, null  , DATABASE_VERSION);
    this.context=con;
    Message.message(context, "constructor called");
}

@Override
public void onCreate(SQLiteDatabase db) {
    try {
        Message.message(context, "onCreate was called");
        db.execSQL(CREAT_TABLE);
    } catch (SQLException e) {
        Message.message(context, ""+e);
    }
}

@Override
public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
    db.execSQL(DROP_TABLE);
    try {
        Message.message(context, "onUpgrade was called");
        onCreate(db);
    } catch (SQLException e) {
        Message.message(context, ""+e);
    }
}

main()
}
saeedHelperBD firstBD;
SQLiteDatabase sqlBD = firstBD.
}`

例如

01-17 14:52:39.890: D/AndroidRuntime(1699): Shutting down VM
01-17 14:52:39.890: W/dalvikvm(1699): threadid=1: thread exiting with uncaught exception (group=0xb3abdb90)
01-17 14:52:39.910: E/AndroidRuntime(1699): FATAL EXCEPTION: main
01-17 14:52:39.910: E/AndroidRuntime(1699): Process: com.example.net.saeed.sqlitedb, PID: 1699
01-17 14:52:39.910: E/AndroidRuntime(1699): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.net.saeed.sqlitedb/com.example.net.saeed.sqlitedb.MainActivity}: java.lang.NullPointerException
01-17 14:52:39.910: E/AndroidRuntime(1699):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2176)
01-17 14:52:39.910: E/AndroidRuntime(1699):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2226)
01-17 14:52:39.910: E/AndroidRuntime(1699):     at android.app.ActivityThread.access$700(ActivityThread.java:135)
01-17 14:52:39.910: E/AndroidRuntime(1699):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1397)
01-17 14:52:39.910: E/AndroidRuntime(1699):     at android.os.Handler.dispatchMessage(Handler.java:102)
01-17 14:52:39.910: E/AndroidRuntime(1699):     at android.os.Looper.loop(Looper.java:137)
01-17 14:52:39.910: E/AndroidRuntime(1699):     at android.app.ActivityThread.main(ActivityThread.java:4998)
01-17 14:52:39.910: E/AndroidRuntime(1699):     at java.lang.reflect.Method.invokeNative(Native Method)
01-17 14:52:39.910: E/AndroidRuntime(1699):     at java.lang.reflect.Method.invoke(Method.java:515)
01-17 14:52:39.910: E/AndroidRuntime(1699):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
01-17 14:52:39.910: E/AndroidRuntime(1699):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
01-17 14:52:39.910: E/AndroidRuntime(1699):     at dalvik.system.NativeStart.main(Native Method)
01-17 14:52:39.910: E/AndroidRuntime(1699): Caused by: java.lang.NullPointerException
01-17 14:52:39.910: E/AndroidRuntime(1699):     at com.example.net.saeed.sqlitedb.MainActivity.onCreate(MainActivity.java:15)
01-17 14:52:39.910: E/AndroidRuntime(1699):     at android.app.Activity.performCreate(Activity.java:5243)
01-17 14:52:39.910: E/AndroidRuntime(1699):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
01-17 14:52:39.910: E/AndroidRuntime(1699):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2140)
01-17 14:52:39.910: E/AndroidRuntime(1699):     ... 11 more
01-17 14:52:45.450: I/Process(1699): Sending signal. PID: 1699 SIG: 9

好的,这里是主要活动

package com.example.net.saeed.sqlitedb;

import android.os.Bundle;
import android.app.Activity;
import android.database.sqlite.SQLiteDatabase;
import android.view.Menu;

public class MainActivity extends Activity {
saeedHelperBD firstBD;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

SQLiteDatabase sqlBD = firstBD.getWritableDatabase();

}

3 个答案:

答案 0 :(得分:0)

要帮助解决您的问题,请在运行查询的部分周围添加try catch。 在catch中添加e.printStackTrace();它将为您提供有关问题所在的更多更好的信息..

这是我使用的一些DB代码,它在VM中运行得很好

package com.jinx.dbs;

import android.content.*;
import android.database.*;
import android.database.sqlite.*;
import android.util.*;
import com.jinx.obj.User;
import java.util.*;

public class database {

    private Context mContext;
    private SQLiteDatabase mainDB = null;
    private final String dbName = "mainDB";
    private final String tblUserDetail = "tblUser";

    public database(Context context) {
        mContext = context;
    }

    boolean CreateOrOpenDB() {
        try {
            mainDB = mContext.openOrCreateDatabase(dbName, SQLiteDatabase.CREATE_IF_NECESSARY, null);
            return true;
        } catch (SQLiteException e) {
            e.printStackTrace();
            mainDB.close();
            return false;
        }
    }

    void CreateUserTable() {
        mainDB.execSQL("CREATE TABLE IF NOT EXISTS "
                + tblUserDetail
                + " (Username VARCHAR(50),"
                + " Password VARCHAR(100),"
                + " Name VARCHAR(100),"
                + " Surname VARCHAR(100));");
    }

    public void StoreUserData(User user) {
        //Open DB before running any queries
        if (CreateOrOpenDB()) {
            try {
                //Make sure the table exists
                CreateUserTable();
                //Only store one users info at a time
                mainDB.execSQL("DELETE FROM " + tblUserDetail);
                mainDB.execSQL("INSERT INTO "
                        + tblUserDetail
                        + " Values ('"
                        + user.getUsername().replace("'", "''") + "','"
                        + user.getPassword().replace("'", "''") + "','"
                        + user.getName().replace("'", "''") + "','"
                        + user.getSurname().replace("'", "''") + "');");

                mainDB.close();
            } catch (Exception e) {
                e.printStackTrace();
                mainDB.close();
            }
        } else {
            Log.i("DATABASE", "COULD NOT BE OPENED");
        }
    }

    public User ReadUserData() {
        User data = null;
        if (CreateOrOpenDB()) {
            try {
                Cursor c = mainDB.rawQuery("SELECT * FROM "
                        + tblUserDetail, null);

                if (c != null) {
                    if (c.moveToFirst()) {
                        data = new User(
                                c.getString(c.getColumnIndex("Username")),
                                c.getString(c.getColumnIndex("Password")),
                                c.getString(c.getColumnIndex("Name")),
                                c.getString(c.getColumnIndex("Surname")));
                    }
                }
                c.close();

                mainDB.close();
            } catch (Exception e) {
                e.printStackTrace();
                mainDB.close();
            }
        } else {
            Log.i("DATABASE", "COULD NOT BE OPENED");
        }

        return data;
    }

    public void ClearUserData() {
        if (CreateOrOpenDB()) {
            try {
                mainDB.execSQL("DELETE FROM " + tblUserDetail);
                mainDB.close();
            } catch (Exception e) {
                e.printStackTrace();
                mainDB.close();
            }
        } else {
            Log.i("DATABASE", "COULD NOT BE OPENED");
        }
    }
}

您可以添加/更改以满足您的需求,添加更多表格,加入它们,发疯。 使用它:

(new database(this)).StoreUserData(u); //Storing the new user -- u is User Object

User u = (new database(this)).ReadUserData(); //Get the user data

(new database(this)).ClearUserData(); //Clear the user data

编辑:

这是用户对象

package com.jinx.obj;
import java.io.Serializable;

public class User implements Serializable {
    private String _username;
    private String _password;
    private String _name;
    private String _surname;

    public User() {
    }
    public User(String Username, String Password, String Name, String Surname) {
        this._username = Username;
        this._password = Password;
        this._name = Name;
        this._surname = Surname;
    }
    public void setUsername(String Username) {
        this._username = Username;
    }
    public String getUsername() {
        return this._username;
    }
    public void setPassword(String Password) {
        this._password = Password;
    }
    public String getPassword() {
        return this._password;
    }
    public void setName(String Name) {
        this._name = Name;
    }
    public String getName() {
        return this._name;
    }    
    public void setSurname(String Surname) {
        this._surname = Surname;
    }
    public String getSurname() {
        return this._surname;
    }
}

答案 1 :(得分:0)

谢谢你们, 我解决了问题,问题是在MainActivity的第15行,我试图将空对象放在SQLiteDatabase对象中,所以我只是创建新对象然后我试图将对象放在SQLiteDatabase中,这里是固定代码

package com.example.net.saeed.sqlitedb;

import android.os.Bundle;
import android.app.Activity;
import android.database.sqlite.SQLiteDatabase;
import android.view.Menu;

    public class MainActivity extends Activity {
saeedHelperBD firstBD;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    firstBD = new saeedHelperBD(this);//this was added to solve the problem
    SQLiteDatabase sql = firstBD.getWritableDatabase();

}

答案 2 :(得分:0)

在您的代码中,您尝试拨打firstBD.getWritableDatabase();。但是,firstBD对象为空。您需要先初始化此对象 我更喜欢使用Singleton模式来初始化saeedHelperBD的对象,如同<
p>

private static saeedHelperBD firstDB;
    public static synchronized saeedHelperBD getInstance() {
        if (firstDB == null) {
            firstDB = new saeedHelperBD(context);
        }
        return firstDB;
    }

另外,你应该声明一个类名,最好是大写字母 例如:saeedHelperBD错误,您可以声明为SaeedHelperBD