我正在尝试将值加载到android上的SQLite表中。当我点击按钮时,我得到了nullpointer异常。请查找logcat.so的附加图像,以将值存储到sqlite数据库表中。
public class MainActivity extends Activity {
EditText edt1,edt2;
DataAdapter adapter;
//String valueName,valueAddress;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// database =new DataAdapter(this);
edt1 =(EditText)findViewById(R.id.editText1);
edt2 =(EditText)findViewById(R.id.editText2);
// sdb = database.getWritableDatabase();
Button button =(Button)findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String valueName =edt1.getText().toString().trim();
String valueAddress =edt2.getText().toString().trim();
long value = adapter.insertData(valueName,valueAddress);
if (value < 0) {
Toast.makeText(getApplicationContext(), "Data not Added ",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Data Added",Toast.LENGTH_SHORT).show();
}
}
});
}
}
public class DataAdapter {
DataBase database;
SQLiteDatabase db;
public DataAdapter(Context context) {
// TODO Auto-generated constructor stub
database =new DataBase(context);
}
public long insertData(String name ,String address){
SQLiteDatabase db= database.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DataBase.NAME, name);
values.put(DataBase.ADDRESS, address);
return db.insert(DataBase.TABLENAME, null,values);
}
public static class DataBase extends SQLiteOpenHelper{
public static final String DATABASE="DataBase";
public static final String TABLENAME="TableName";
public static final int VERSION = 5;
public static final String NAME="name";
public static final String ADDRESS="address";
public static final String ID="_id";
public static final String CREATE_TABLE = "create table "+TABLENAME+"("+ID+"" +
"INTEGER PRIMARY KEY AUTOINCREMENT,"+NAME+" VARCHAR(255),"+ADDRESS+" VARCHAR(255));";
private Context context;
public DataBase(Context context) {
super(context, DATABASE, null, VERSION);
this.context =context;
// TODO Auto-generated constructor stub
Toast.makeText(context, "onDataBase",Toast.LENGTH_SHORT).show();
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
try {
Toast.makeText(context, "oncreate",Toast.LENGTH_SHORT).show();
db.execSQL(CREATE_TABLE);
} catch (SQLException e) {
// TODO: handle exception
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
try {
Toast.makeText(context, "oncUpgrade",Toast.LENGTH_SHORT).show();
db.execSQL("DROP TABLE IF EXITS"+TABLENAME);
onCreate(db);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}][1]
答案 0 :(得分:3)
DataAdapter adapter;
未在您的代码中初始化,请将其初始化,然后使用.. like
adapter = new DataAdapter(this);