当我插入记录时,我面临以下问题:
java.lang.runtimeexception unable to start activity componentinfo java.lang.nullpointerexception
.我在将值插入 sqlite 数据库时遇到空指针异常。当我尝试通过放置断点检查其值时,dh inDatabaseHelper dh = new DatabaseHelper(this)
为空。下面是我的 DatabaseHelper 类的代码和我试图插入值的类。
第一个活动:DbActivity.java
package com.example.dbhelpersimple;
import android.os.Bundle;
import android.provider.Contacts;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import android.support.v4.app.NavUtils;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;
public class DbActivity extends SQLiteOpenHelper {
public static final String COL_NAME = "name";
public static final String COL_CNT = "contact";
private static final String DATABASE_TABLE = "test";
private static String DATABASE_NAME = "PERSONS.db";
private static final String DATABASE_CREATE="CREATE TABLE test"+
"(name VARCHAR(10), contact VARCHAR(10));";
SQLiteDatabase db;
public DbActivity(Context context) {
super(context, DATABASE_NAME, null, 1);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL(DATABASE_NAME);
onCreate(db);
}
void addrecord(String name, String contact)
{
ContentValues cv=new ContentValues();
cv.put(COL_NAME, name);
cv.put(COL_CNT, contact);
db.insert(DATABASE_TABLE, null, cv);
db.close();
}
void getrecords()
{
int i;
//String query="SELECT * FROM test";
Cursor c=db.query(DATABASE_TABLE, null, null, null, null, null, null);
c.moveToFirst();
while(c.isAfterLast()==false)
{
Log.d("Name", c.getString(0));
Log.d("Contact", c.getString(1));
}
}
}
第二个活动:operatedActivity.java
package com.example.dbhelpersimple;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class manipulateActivity extends Activity{
Button btn1,btn2,btn3;
EditText edt1,edt2;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_db);
edt1=(EditText)findViewById(R.id.edittextname);
edt2=(EditText)findViewById(R.id.edittextcontact);
DbActivity dbact= new DbActivity(this);
dbact.addrecord("sagar", "111");
}
}