当前位置: 首页 > 知识库问答 >
问题:

Sqlite上的getWritableDatabase()错误

孙书
2023-03-14

我想把一些数据存储到sqlite数据库中,但是在我的DBHandler和DBGen类中发生了错误,我无法找到这个错误,我想存储用户名,密码,确认密码,手机号码和电子邮件ID。

public class UserDetailsDTO 
{
private String userName;
private String password;
private String confirmPassword;
private String mobileNumber;
private String emailId;

public String getUserName(){
    return userName;
}
public void setUserName(String userName){
    this.userName = userName;
}
public String getPasssword(){
    return password;
}
public void setPassword(String password){
    this.password = password;
}
public String getConfirmPassword(){
    return confirmPassword ;
}
public void setConfirmPassword(String confirmPassword){
    this.confirmPassword = confirmPassword;
}
public String getMobileNumber(){
    return mobileNumber;
}
public void setMobileNumber(String mobileNumber){
    this.mobileNumber = mobileNumber;
}
public String getEmailId(){
    return emailId;
}
public void setEmailId(String emailId){
    this.emailId = emailId;
}
  }
     public class DBGen 
      {

      private Context ctx;

    //constants
    public final static int MODE_READ=0;
    public final static int MODE_WRITE=1;

    //SQLite Database 
    private SQLiteDatabase myDB = null;

    private DBHelper dbHelper;

    private DBHandler dbHandler;

    private static boolean isClosed = false;

    private static DBGen dbGen = null;
    private DBGen(Context ctx, DBHandler dbHandler){
        this.ctx=ctx;
        this.dbHandler=dbHandler;
        this.dbHelper = new DBHelper(ctx, dbHandler.getDatabase(), null, dbHandler.getVersion());
    }

    public static DBGen getInstance(Context ctx, DBHandler dbHandler){
        if(dbGen == null || isClosed){
            dbGen = new DBGen(ctx, dbHandler);
            isClosed = false;
        }
        return dbGen;
    }

    public SQLiteDatabase open(int mode){
        // To close the connection before opening a new one.
        if(myDB != null){
            close();
        }
        if(mode == MODE_WRITE){
           myDB = dbHelper.getWritableDatabase();
        }
        else{
            myDB = dbHelper.getReadableDatabase();
        }
        return myDB;
    }

    public SQLiteDatabase open(){
        if((myDB == null)|| (! myDB.isOpen())){
            myDB = dbHelper.getWritableDatabase();
        }
        return myDB;
    }

    public boolean isDBExists(){
        boolean isDBExist=false;

        try{
            File dbPath=ctx.getDatabasePath(dbHandler.getDatabase());
            isDBExist = dbPath.exists();
        }
        catch(Exception e){
            e.printStackTrace();
            Log.e(dbHandler.getLogTag(),"ERROR DELETING THE FILE",e);
        }

        return isDBExist;
    }

    public boolean removeDB(){
        boolean isDBClosed=removeHardDB();
        return isDBClosed;
    }

    private boolean removeHardDB(){
        boolean isDBdeleted = false;

        try{
            File dbFilePath=ctx.getDatabasePath(dbHandler.getDatabase());
            close();
            isDBdeleted=dbFilePath.delete();
        }
        catch(Exception e){
            e.printStackTrace();
            Log.e(dbHandler.getLogTag(),"EXCEPTION RAISED IN DELETING DB");
        }

        return isDBdeleted;
    }

    public static void closeCursor(Cursor c){
        if(c != null){
            c.close();
        }
    }


    public void close(){
        isClosed = true;
        try{
            myDB.close();
        }
        catch(SQLException sqlex){
            Log.e(dbHandler.getLogTag(),sqlex.getMessage(),sqlex);
        }

        try{
            dbHelper.close();
        }
        catch(SQLException sqlex){
            Log.e(dbHandler.getLogTag(),sqlex.getMessage(),sqlex);
        }
    }

    class DBHelper extends SQLiteOpenHelper{

        public DBHelper(Context context, String name, CursorFactory factory, int                          

           version) {
            super(context, name, factory, version);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            dbHandler.onCreate(db);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            dbHandler.onUpgrade(db, oldVersion, newVersion);
        }
    }
}
public abstract class DBHandler {

    private int version;
    private String database;
    private String logTag;

    private DBGen dbGen;

    @SuppressWarnings("unused")
    private DBHandler(){}

    public DBHandler(Context context, String database, int version, String logTag){
        this.database=database;
        this.version=version;
        this.logTag=logTag;

        dbGen = DBGen.getInstance(context, this);
    }

    public String getDatabase() {
        return database;
    }

    public void setDatabase(String database) {
        this.database = database;
    }

    public int getVersion() {
        return version;
    }

    public void setVersion(int version) {
        this.version = version;
    }

    public String getLogTag() {
        return logTag;
    }

    public void setLogTag(String logTag) {
        this.logTag = logTag;
    }

    public SQLiteDatabase getReadDB(){
        return dbGen.open();
    }

    public SQLiteDatabase getWriteDB(){

        return dbGen.open();
    }

    public void close(){
        try{
            dbGen.close();
        }
        catch(SQLException sqlEx){
            Log.e(logTag, "Exception while closing connection",sqlEx);
        }
    }

    public abstract void onCreate(SQLiteDatabase db);
    public abstract void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion);

      }
public class UserDBHandler extends DBHandler {

// DataBase Name
    public final static String DATABASE = "UserDetails";

    // DataBase Table Name's
    public final static String USER_TABLE = "TABLE_USER";

    // Field names of MALLS Table

    public static final String USER_NAME = "username";
    public static final String PASSWORD = "password";
    public static final String CONFIRM_PASSWORD = "confirmpassword";
    public static final String USER_MOBILE_NUMBER = "mobilenumber";
    public static final String USER_EMAIL = "email";

    private String CREATE_TABLE_USER = "CREATE TABLE IF NOT EXISTS "
            + USER_TABLE+ " (" + USER_NAME
            + " VARCHAR," + PASSWORD + " VARCHAR,"
            + CONFIRM_PASSWORD + " VARCHAR," + USER_MOBILE_NUMBER + "    
                              VARCHAR,"
            + USER_EMAIL+ " VARCHAR," 
             + ")";




    public UserDBHandler(Context context) {
        super(context,DATABASE, Constants.DB_VERSION, Constants.TAG);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE_USER);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        try {
            onCreate(db);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
     }

 UserDaoImlp.java

  public class UserDaoImpl implements UserDao{
private SQLiteDatabase myDB;
private UserDBHandler dbHandler;
private String TAG = "ItopperDaoImpl";

public UserDaoImpl(Context context){
    dbHandler = new UserDBHandler(context);
    myDB = dbHandler.getWriteDB();
}


@Override
public void beginTransaction() {
    // TODO Auto-generated method stub
    myDB.beginTransaction();

}

@Override
public void setTransactionSuccessful() {
    // TODO Auto-generated method stub
    myDB.setTransactionSuccessful();
}

@Override
public void endTransaction() {
    // TODO Auto-generated method stub
    myDB.endTransaction();

}
public long insertUserDetails(UserDetailsDTO userDetails) {

    ContentValues contentValues = new ContentValues();
    contentValues.put(UserDBHandler.USER_NAME, userDetails.getUserName());
    contentValues.put(UserDBHandler.PASSWORD, userDetails.getPasssword());
    contentValues.put(UserDBHandler.CONFIRM_PASSWORD,
          userDetails.getConfirmPassword());

     contentValues.put(UserDBHandler.USER_MOBILE_NUMBER,userDetails.getMobileNumber());
    contentValues.put(UserDBHandler.USER_EMAIL,userDetails.getEmailId());

    return myDB.insert(UserDBHandler.USER_TABLE, null,
            contentValues);

}
   }

启动活性

  public class StartActivity extends Activity {

private EditText   
 userNameEdit,passwordEdit,confirmPasswordEdit,emailEdit,mobileNoEdit;
private Button sbtButton;
private Button cancelButton;


private String userName;
private String password;
private String confirmPwd;
private String mobileNo;
private String email;

private UserDaoImpl userDaoImpl;
private Context mContext;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_start);

    userNameEdit = (EditText)findViewById(R.id.userNameedt);
    passwordEdit = (EditText)findViewById(R.id.paswordEdit);
    confirmPasswordEdit = (EditText)findViewById(R.id.confirmPaswordEdit);
    emailEdit    = (EditText)findViewById(R.id.emailedt);
    mobileNoEdit = (EditText)findViewById(R.id.mobileNoedt);

    sbtButton   = (Button)findViewById(R.id.submitbtn);
    cancelButton = (Button)findViewById(R.id.cancel);


}
@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    sbtButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            UserDetailsDTO userDetailsDto = new UserDetailsDTO();

            userName  = userNameEdit.getText().toString().trim();
            password  = passwordEdit.getText().toString().trim();
            confirmPwd = confirmPasswordEdit.getText().toString().trim();
            email    = emailEdit.getText().toString().trim();
            mobileNo   = mobileNoEdit.getText().toString().trim();

           userDetailsDto.setUserName(userName);
           userDetailsDto.setPassword(password);
           userDetailsDto.setConfirmPassword(confirmPwd);   
           userDetailsDto.setMobileNumber(mobileNo);
           userDetailsDto.setEmailId(email);

          userDaoImpl = new UserDaoImpl(mContext);
           userDaoImpl.insertUserDetails(userDetailsDto);

        }
    });
      }
   }

下面是LogCat特定的问题代码

12-31 12:09:17.749:E/AndroidRuntime(962):java.lang.nullPointerException 12-31 12:09:17.749:E/AndroidRuntime(962):at android.database.sqlite.sqliteOpenHelper.getWritableDatabase(SqliteOpenHelper.java:157)12-31 12:09:17.749:E/AndroidRuntime(962):at com.technowellServices.mobileUapp.dabase.dbgen.open(dbgen.java:63)12-31 database.dbhandler.getwritedb(dbhandler.java:59)12-31 12:09:17.749:e/androidruntime(962):at com.technowellservices.mobileuapp.database.userdaoimpl.(userdaoimpl.java:20)12-31 12:09:17.749:e/androidruntime(962):at com.technowellservices.mobileuapp.activities.startactivity 12:09:17.749:e/AndroidRuntime(962):at Android.view.view$performClick.run(view.java:13983)12-31 12:09:17.749:e/AndroidRuntime(962):at Android.os.handler.handleCallback(handler.java:605))12-31 12:09:17.749:e/AndroidRuntime(962):at Android.os.handler.dispatchMessage(handler.java:92)12-31 12:09:17.749:e/AndroidRuntime(962):at Android.os.looper.loop(looper.java:137)12-31 12:09:17.749:e/AndroidRuntime(962):at Android.app.activitythread.main(activitythread.java:4340)12-31 12:09:17.749:e/AndroidRuntime(962):at-31 12:09:17.749:e/androidruntime(962):at java.lang.reflect.Method.invoke(Method.java:511)12:09:17.749:e/androidruntime(962):at com.android.internal.os.zygoteinit$methodandargscaller.run(zygoteinit.java:784)12-31 12:09:17.749:e/androidruntime(962):at com.android.internal.os.zygoteinite.java:551)12-31):位于dalvik.system.nativeStart.main(本机方法)

共有1个答案

孟振
2023-03-14

错误最可能的原因是无效的上下文,在代码中,在类声明下面放一行:

 UserDaoImpl userDaoImpl;

然后在onCreate中初始化它,如下所示:

 userDaoImpl = new   UserDaoImpl (this)
 类似资料:
  • 本文向大家介绍Android getReadableDatabase() 和 getWritableDatabase()分析对比,包括了Android getReadableDatabase() 和 getWritableDatabase()分析对比的使用技巧和注意事项,需要的朋友参考一下 Android getReadableDatabase() 和 getWritableDatabase()分

  • 我目前正在移植一个Android应用程序到codename one。对于新的应用程序,这是一个在iOS、Android和Windows Phone上工作的要求。在默认的codename one数据库类的描述中,它说Windows Phone不被支持,应该只用于“非常大的数据处理”。相反,更便携的存储类别应该用于小型存储。 本机应用程序目前使用几个具有相当困难的查询的SQLite表。我不会说数据量很

  • 问题内容: 更新:我只是检查了我使用的最新的JDBC jar,并且缺少地图/Linux/arm/libsqlitejdbc.so,可以通过从某个地方下载该文件来解决此问题吗?在任何地方都找不到。 编辑:问题似乎是这个,但是我不知道如何解决这个问题。 我正在尝试在树莓派上使用SQLite数据库。但是我无法使其正常工作。我得到下面发布的输出。我正在使用JDBC驱动程序。该代码在我的主计算机上工作正常。

  • 我遇到了一个奇怪的问题。我正在查询数据库表中的单词列表,并能够获得该列表。但是我无法更新该表。奇怪的是,logcat显示Code 14错误。我卸载了应用程序,重新运行它,所以数据库是新复制的,但是什么都没有改变。 以下是dbHandler代码: } 这是服务代码: 字符串兽医显示在烤面包中,我可以看到表格第一列中的所有单词。但是我无法更新行。 我已经给了它存储权限,并对其进行了双重检查。 清单文件

  • 问题内容: 我正在开发一个短信应用程序,我试图从每次对话中获取最新的短信。 这是我的SQL语句: 我在SQLite Expert中运行了查询,并且得到了正确的响应: 但是,当我在应用程序中运行它时,我得到: 这是我的桌子 这是我的Datamanipulator类: 问题答案: 使用时,结果的每一行对应于原始表的多行。这些结果的计算有三种可能性: 具有聚合函数的列类似于或计算组中所有行的值; 子句中