我认为这是一个非常常见的问题,但在查看所有回复之后我无法解决这个问题。我正在创建一个Android应用程序,我们可以在其中保存主题(壁纸,铃声,通知声音)。当我尝试在按钮单击时保存数据库中的三个东西时,它强制关闭并且存在许多错误,包括“无法打开堆栈跟踪”
Code:
public class HelloGallery extends Activity
{
private ThemeAdapter ta;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ta=new ThemeAdapter(this);
final Button save=(Button)findViewById(R.id.save);
save.setText(R.string.save);
// some amount of code
save.setOnClickListener(new OnClickListener(){
public void onClick(View v)
{
themename=tv.toString(); //tv is EditText
ta.createTheme(themename, resID, uri,uri2);
Toast.makeText(HelloGallery.this,"Theme Saved", Toast.LENGTH_SHORT).show();
}
});
}
}
public class ThemeAdapter {
private SQLiteDatabase db;
private myThemeHelper mth;
String[] columns={myThemeHelper.KEY_ID,myThemeHelper.NAME,myThemeHelper.RING,myThemeHelper.SYS};
public ThemeAdapter(Context _con)
{
mth=new myThemeHelper(_con);
}
public ThemeAdapter open()
{
try
{
db=mth.getWritableDatabase();
}
catch(SQLiteException e)
{
db=mth.getReadableDatabase();
}
return this;
}
public void close()
{
db.close();
}
public void createTheme(String name,int wallId,Uri ring,Uri sys)
{
ContentValues val=new ContentValues();
val.put(myThemeHelper.NAME,name);
val.put(myThemeHelper.WALL,wallId);
val.put(myThemeHelper.RING,ring.toString());
val.put(myThemeHelper.SYS,sys.toString());
long id=db.insert(myThemeHelper.DB_TABLE, null, val);
Cursor cursor=db.query(myThemeHelper.DB_TABLE,columns,myThemeHelper.KEY_ID+ "= "
+ id, null,null, null, null);
cursor.moveToFirst();
}
}
public class myThemeHelper extends SQLiteOpenHelper
{
//initializing all db names, colum names
public myThemeHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DB_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(myThemeHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);
onCreate(db);
}
}
堆栈跟踪给出了NullPointerException,无法打开堆栈跟踪等。我也给了WRITE_EXTERNAL_STORAGE权限。
答案 0 :(得分:0)
我没有在ThemeAdapter的任何地方看到open()。所以你的db在createTheme()中为null,因此是NPE