0

我实际上是在尝试创建一个链接到登录页面的android SQLite DB,以便在oncreate 方法期间在sqlite 数据库中有一个条目,即管理员和他的密码(假设前缀为“密码”)。但是,当我尝试使用 ContentValues cv(我最初设置为 null)...之后是 cv.put.. 我在 onCreate 处得到一个空指针异常(并不感到惊讶)。这对我来说是正确的方法吗?我想避免使用 sql 命令,因为我根本不熟悉它,但作为最后的手段使用它没有问题。(这里是代码这是我用于创建数据库的 DB2 Java 类

public class DB2 {
//column details
public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "name";
public static final String KEY_NUMBER = "number";
public static final String KEY_EMAIL = "email"; 
public static final String KEY_PASSWORD = "password";
//db details
public static final String DATABASE_NAME = "Phonebook2DB";
public static final String DATABASE_TABLE = "contacts";
public static final int DATABASE_VERSION = 1;

private DBHelper ourHelper;
public final Context ourContext;
private static SQLiteDatabase ourDatabase;

//检查我们的数据库变量以防出现问题 //test-ERROR MAY BE HERE static ContentValues cv;

private static class DBHelper extends SQLiteOpenHelper{

    public DBHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        //Now we access the db and execute sql code
        db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" + //sql commands have to be precise(note the spaces)
                    KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +//NOW SEtup 1st col with ensuring the keyid be incremented
                    KEY_NAME + " TEXT NOT NULL, " + //2nd col all in blue are sql code
                    KEY_NUMBER +" TEXT NOT NULL, " +//3rd col
                    KEY_EMAIL + " TEXT NOT NULL, " +
                    KEY_PASSWORD + " TEXT NOT NULL);"
                );
        cv.put(KEY_NAME,"admin");
        cv.put(KEY_NUMBER, "12345");
        cv.put(KEY_EMAIL,"admin@admin.com");
        cv.put(KEY_PASSWORD,"hello12345");

        }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        db.execSQL("DROP TABLE IF EXISTS" + DATABASE_TABLE);
        onCreate(db);

    }
}

    public DB2(Context c){
        ourContext = c;
    }

    public DB2 open(){
        ourHelper = new DBHelper(ourContext);
        ourDatabase = ourHelper.getWritableDatabase();
        return this;
    }

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

    public long createEntry(String name,String number,String email,String password){
        cv.put(KEY_NAME, name);
        cv.put(KEY_NUMBER, number);
        cv.put(KEY_EMAIL, email);
        cv.put(KEY_PASSWORD, password);
        return ourDatabase.insert(DATABASE_TABLE, null, cv);
    }

    public void deleteEntry(String name1){
        ourDatabase.delete(DATABASE_TABLE, KEY_NAME + '=' + name1, null);
    }

    public String  getdatabase(){
        String columns[] = new String[]{KEY_ROWID,KEY_NAME,KEY_NUMBER,KEY_EMAIL,KEY_PASSWORD};
        Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
        String output = "";
        int iRowid = c.getColumnIndex(KEY_ROWID);
        int iName = c.getColumnIndex(KEY_NAME);
        int iNumber = c.getColumnIndex(KEY_NUMBER);
        int iEmail = c.getColumnIndex(KEY_EMAIL);
        for(c.moveToFirst();!c.isAfterLast();c.moveToNext())
        output = output + " " + c.getString(iRowid) + "\t" + c.getString(iName) +"\t" + c.getString(iNumber) + "\t" + c.getString(iEmail) + "\n";

        return output;
    }



    public String getPasswordByName(String lName){//getting password using from name for loginpage activity purposes
        String columns[] = new String[]{KEY_ROWID,KEY_NAME,KEY_NUMBER,KEY_EMAIL,KEY_PASSWORD};
        Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_NAME + '=' + lName, null, null, null,null);
        if(c!=null){
            c.moveToFirst();String Password = c.getString(4);return Password;
        }
        return null;
    }

    public String getName(String lName){//to check if login name exists??
        String columns[] = new String[]{KEY_ROWID,KEY_NAME,KEY_NUMBER,KEY_EMAIL,KEY_PASSWORD};
        Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_NAME + '=' + lName, null, null, null, null);
        if(c!=null){
            c.moveToFirst();String Name = c.getString(1);return Name;
        }
        return null;
    }



}

这是我的 LoginPage Java CLass 的定义

public class LoginPage extends Activity implements OnClickListener{

Button login,forgotpass;
EditText user,pass;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.loginpage);
    login = (Button) findViewById (R.id.BLogin);
    forgotpass = (Button) findViewById (R.id.BForgotPass);
    user = (EditText) findViewById (R.id.ETUsername);
    pass = (EditText) findViewById (R.id.ETPasswd);
    login.setOnClickListener(this);
    forgotpass.setOnClickListener(this);
}

@Override
public void onClick(View arg0) {
    // TODO Auto-generated method stub
    switch(arg0.getId()){
    case R.id.BLogin:
        String usernameinput = user.getText().toString();
        String password = pass.getText().toString();
        //now if usernameinput and password input match with entries in database then we r good to go
         //long l = Long.parseLong(usernameinput); 
        DB2 dbname = new DB2(this);
        dbname.open();
        String returnedName;
        returnedName = dbname.getName(usernameinput);
        if(returnedName == "true" && password == dbname.getPasswordByName(usernameinput)){//here authenticating username and password

        try{
        Intent i = new Intent(LoginPage.this,MainStuff.class);
        LoginPage.this.startActivity(i);
        }catch(Exception e){e.printStackTrace();}
        }
        break;

    case R.id.BForgotPass:
        finish();//for now exit the function
        break;
    }

}

}

And here is the logcat
06-18 09:05:46.237: W/dalvikvm(802): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
06-18 09:05:46.247: E/AndroidRuntime(802): FATAL EXCEPTION: main
06-18 09:05:46.247: E/AndroidRuntime(802): java.lang.NullPointerException
06-18 09:05:46.247: E/AndroidRuntime(802):  at com.example.phonebook2.DB2$DBHelper.onCreate(DB2.java:49)
06-18 09:05:46.247: E/AndroidRuntime(802):  at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:252)
06-18 09:05:46.247: E/AndroidRuntime(802):  at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
06-18 09:05:46.247: E/AndroidRuntime(802):  at com.example.phonebook2.DB2.open(DB2.java:71)
06-18 09:05:46.247: E/AndroidRuntime(802):  at com.example.phonebook2.LoginPage.onClick(LoginPage.java:39)
06-18 09:05:46.247: E/AndroidRuntime(802):  at android.view.View.performClick(View.java:4204)
06-18 09:05:46.247: E/AndroidRuntime(802):  at android.view.View$PerformClick.run(View.java:17355)
06-18 09:05:46.247: E/AndroidRuntime(802):  at android.os.Handler.handleCallback(Handler.java:725)
06-18 09:05:46.247: E/AndroidRuntime(802):  at android.os.Handler.dispatchMessage(Handler.java:92)
06-18 09:05:46.247: E/AndroidRuntime(802):  at android.os.Looper.loop(Looper.java:137)
06-18 09:05:46.247: E/AndroidRuntime(802):  at android.app.ActivityThread.main(ActivityThread.java:5041)
06-18 09:05:46.247: E/AndroidRuntime(802):  at java.lang.reflect.Method.invokeNative(Native Method)
06-18 09:05:46.247: E/AndroidRuntime(802):  at java.lang.reflect.Method.invoke(Method.java:511)
06-18 09:05:46.247: E/AndroidRuntime(802):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
06-18 09:05:46.247: E/AndroidRuntime(802):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
06-18 09:05:46.247: E/AndroidRuntime(802):  at dalvik.system.NativeStart.main(Native Method)

我是 android 的初学者,所以请随时提出改进我的代码的方法。谢谢

4

2 回答 2

0

在你的类DBHelperpublic long createEntry()方法中,

只需在顶部添加这一行

ContentValues cv = new ContentValues();

于 2013-06-18T09:44:31.090 回答
0

在创建数据库期间触发该DBHelper.onCreate()方法时,该变量cv不存在。要填充主数据,您可以使用简单的插入语句。

代替

cv.put(KEY_NAME,"admin");
cv.put(KEY_NUMBER, "12345");
cv.put(KEY_EMAIL,"admin@admin.com");
cv.put(KEY_PASSWORD,"hello12345");

用一个简单的插入语句

string sql = "INSERT INTO " + DATABASE_TABLE + "(" + KEY_NAME + ", " + KEY_NUMBER + ", " + KEY_EMAIL + ", " + KEY_PASSWORD + ") VALUES('admin', '12345', 'admin@admin.com', 'hello12345');";
db.execSQL(sql);
于 2013-06-18T09:38:10.950 回答