SQLite数据库表在每次应用程序重新启动时重新创建

时间:2012-07-09 06:20:05

标签: java android

我是Android开发的新手。我的申请中有问题。我的SQLite数据库表 在每次系统重启时重新创建,并从表中删除所有保存的内容。有人可以帮我解决这个问题吗?

这是我的数据库类......

package Nsh.android.sms;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.SyncStateContract.Helpers;

public class Database {

public static final String MYDATABASENAME="Mylanguagedbnew.db";
 public static final String MYDATABASETABLE="Mylanguagedb_table1";
public static final int MYDATABASEVERSION=1;
 public static final String KEY_id="_id";
public static final String KEY_language="languages";
public static final String KEY_description="languagedescription";
private static final String SCRIPT_CREATE_DATABASE="create table if not exists
"+MYDATABASETABLE+" ("+KEY_id+" integer primary key autoincrement, "+KEY_language+" 
text not null, "+KEY_description+ " text not null);";
private datahelper sqliteopenhelper;
public static String userselectedlang;
private SQLiteDatabase sqlitedatabase;
private Context context;
 public Database(Context c){
System.out.println("DBcontext!!!1111");
 context=c; 
  }
 public Database openToread()throws android.database.SQLException{
System.out.println("DBINSERTTTTTTTTT!!!OPENREAD22222");
    sqliteopenhelper=new datahelper(context,MYDATABASENAME,null,MYDATABASEVERSION);
    System.out.println("DBINSERTTTTTTTTT!!!OPENREAD22222");
    sqlitedatabase=sqliteopenhelper.getReadableDatabase();
    System.out.println("DBINSERTTTTTTTTT!!!OPENREAD22222");
    return this;
     }
  public Database openTowrite()throws android.database.SQLException{
System.out.println("DBINSERTTTTTTTTT!!!OPENWRITE22222");
sqliteopenhelper=new datahelper(context,MYDATABASENAME,null,MYDATABASEVERSION);
sqlitedatabase=sqliteopenhelper.getWritableDatabase();
return this;
  }
 public void close(){
sqliteopenhelper.close();
 }  
  public Cursor retriveall(){
  System.out.println("RETRIEVE ALL OK!!!!!!!!!");
String[] columns={KEY_id,KEY_language,KEY_description};
Cursor cursor=sqlitedatabase.query(MYDATABASETABLE, columns,null,null,null,null,null);
return cursor;
  } 
  public Cursor retrivelanguages(){
String[] columns={KEY_language};
Cursor c=sqlitedatabase.query(MYDATABASETABLE, columns,null,null,null,null,null);
return c;
    }
  public Cursor retrieveselectedlanguagedecription(){
userselectedlang=listlang.selectedlanguage;
String query="select languagedescription from Mylanguagedb_table1 where languages 
      ='"+userselectedlang+"';";
Cursor c1=sqlitedatabase.rawQuery(query,null);
return c1;
   }
     public long insert(String language,String languagedescription){
System.out.println("DBINSERTTTTTTTTT!!!INSERT !!!!!!!!!1111");
ContentValues contentvalues=new ContentValues();
contentvalues.put(KEY_language,language);
contentvalues.put(KEY_description,languagedescription);
return sqlitedatabase.insert(MYDATABASETABLE, null,contentvalues);
    }
   public int deleteall(){

 return sqlitedatabase.delete(MYDATABASETABLE,null,null);
    }
   /*public int deleterow(){
String selectedrow=listlang.selectedlanguage;

return sqlitedatabase.delete(MYDATABASETABLE,selectedrow, null);
    }*/
     private static class datahelper extends SQLiteOpenHelper{

public datahelper(Context context, String name, CursorFactory factory,
        int version) {
    super(context, name, factory, version);
    // TODO Auto-generated constructor stub
}

@Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub
    db.execSQL(SCRIPT_CREATE_DATABASE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub
    //db.update(table, values, whereClause, whereArgs)
}

   }    
    }

2 个答案:

答案 0 :(得分:0)

当应用程序启动时,它将创建新的数据库和表,如果不存在,则它将继续使用退出数据库。

将此代码放入您应用的启动活动的onCreate()方法中,以检查数据库是否已存在。

//this is  the name of my database
public static final String DATABASE_NAME = "mydatabase.db";

//this is the complete path of my database stored. you can check in DDMS
public static final String DATABASE_PATH = "/data/data/com.rdc.mydatabase/databases/";

Context context = getBaseContext();

boolean databaseStatus = checkDataBase( DATABASE_PATH,DATABASE_NAME);
//this will check when app start
if (databaseStatus == false) {

    DBAdapter database = new DBAdapter(context);
    //here you can call your create table method 
    //database.createLoginTable();
    Log.v("Debug", "Login table created.");
}
else{
    Log.v("Debug", "Database already exist");
}

//method to check whether db is already exist or not and returns boolean
private boolean checkDataBase(String databasePath, String databaseName) {
        SQLiteDatabase checkDB = null;
        try {
            checkDB = SQLiteDatabase.openDatabase(databasePath + databaseName,
                    null, SQLiteDatabase.OPEN_READONLY);
            checkDB.close();
            Log.v("Debug", "Database exist");
            return true;
        } catch (SQLiteException e) {
            Log.v("Debug", "Database not exist");

        }
        return false;
    }

我希望它能帮到你!!

答案 1 :(得分:0)

您可以在SharedPreferences方法中使用onCreate()来解决此问题,只有在应用首次执行时才能限制数据的插入(如果它是固定数据)。这将解决重复。

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash);

        SharedPreferences pref = getSharedPreferences(PREFS_NAME1,MODE_PRIVATE);   
        boolean first1 = pref.getBoolean(PREF_FIRST1, false);

        if(first1!=true)
        {
            getSharedPreferences(PREFS_NAME1,MODE_PRIVATE)
            .edit()
            .putBoolean(PREF_FIRST1, true)
            .commit();

            // insert data here or use Background Task to do that 
        }

    }