1

我认为这是一个非常常见的问题,但在查看所有回复后我无法解决。我正在创建一个 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 权限。

4

1 回答 1

0

我没有看到在 ThemeAdapter 的任何地方调用 open()。所以你的数据库在 createTheme() 中是空的,因此是 NPE

于 2014-07-25T08:29:49.000 回答