如何在SPLASH SCREEN中创建数据库?
Reason的:
我创建了一个代码,用于验证我的表和数据库是否存在,但是当我尝试读取不存在的数据库(然后,应用程序已关闭)时,此代码会崩溃,因为我没有创建方法。
我需要创建一个数据库和表“Users”(如果不存在)(就是这种情况)。
当数据库存在且表存在时,这个应用程序非常好用......
public class SplashScreenActivity extends Activity {
// Set the duration of the splash screen
private static final long SPLASH_SCREEN_DELAY = 2000;
final Context context = this;
UsersDataBaseAdapter loginDataBaseAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
loginDataBaseAdapter=new UsersDataBaseAdapter(this);
loginDataBaseAdapter=loginDataBaseAdapter.open();
// Set portrait orientation
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// Hide title bar
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.splash_screen);
TimerTask task = new TimerTask() {
@Override
public void run() {
loginDataBaseAdapter=loginDataBaseAdapter.open();
File dbtest =new File("/data/data/my.example.com/databases/database.db");
if(dbtest.exists())
{
boolean dbtest1 = UsersDataBaseAdapter.databaseExist();
if (dbtest1==true){
Integer dbtest2= UsersDataBaseAdapter.ExisteTabla();
if (dbtest2==0 ){
Intent mainIntent = new Intent().setClass(SplashScreenActivity.this, HomeActivity.class);
startActivity(mainIntent);
}else{
Intent mainIntent = new Intent().setClass(SplashScreenActivity.this, HomeActivity.class);
startActivity(mainIntent);
}
}else{
Intent mainIntent = new Intent().setClass(SplashScreenActivity.this, HomeActivity.class);
startActivity(mainIntent);
}
}else{
Intent mainIntent = new Intent().setClass(SplashScreenActivity.this, HomeActivity.class);
startActivity(mainIntent);
}
// Close the activity so the user won't able to go back this
// activity pressing Back button
finish();
}
};
// Simulate a long loading process on application startup.
Timer timer = new Timer();
timer.schedule(task, SPLASH_SCREEN_DELAY);
}
}
日志
中的错误消息03-11 00:22:09.971: E/Trace(4411): error opening trace file: No such file or directory (2)
03-11 00:22:27.839: D/AndroidRuntime(4411): Shutting down VM
03-11 00:22:28.069: W/dalvikvm(4411): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
03-11 00:22:28.281: E/AndroidRuntime(4411): FATAL EXCEPTION: main
03-11 00:22:28.281: E/AndroidRuntime(4411): java.lang.RuntimeException: Unable to start activity ComponentInfo{br.exemplozxingintegration/com.example.skysoft.qr.SplashScreenActivity}: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
03-11 00:22:28.281: E/AndroidRuntime(4411): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
03-11 00:22:28.281: E/AndroidRuntime(4411): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
03-11 00:22:28.281: E/AndroidRuntime(4411): at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-11 00:22:28.281: E/AndroidRuntime(4411): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
03-11 00:22:28.281: E/AndroidRuntime(4411): at android.os.Handler.dispatchMessage(Handler.java:99)
03-11 00:22:28.281: E/AndroidRuntime(4411): at android.os.Looper.loop(Looper.java:137)
03-11 00:22:28.281: E/AndroidRuntime(4411): at android.app.ActivityThread.main(ActivityThread.java:5041)
03-11 00:22:28.281: E/AndroidRuntime(4411): at java.lang.reflect.Method.invokeNative(Native Method)
03-11 00:22:28.281: E/AndroidRuntime(4411): at java.lang.reflect.Method.invoke(Method.java:511)
03-11 00:22:28.281: E/AndroidRuntime(4411): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
03-11 00:22:28.281: E/AndroidRuntime(4411): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-11 00:22:28.281: E/AndroidRuntime(4411): at dalvik.system.NativeStart.main(Native Method)
03-11 00:22:28.281: E/AndroidRuntime(4411): Caused by: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
03-11 00:22:28.281: E/AndroidRuntime(4411): at android.database.AbstractCursor.checkPosition(AbstractCursor.java:424)
03-11 00:22:28.281: E/AndroidRuntime(4411): at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
03-11 00:22:28.281: E/AndroidRuntime(4411): at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
03-11 00:22:28.281: E/AndroidRuntime(4411): at com.example.skysoft.qr.UsersDataBaseAdapter.<init>(UsersDataBaseAdapter.java:56)
03-11 00:22:28.281: E/AndroidRuntime(4411): at com.example.skysoft.qr.SplashScreenActivity.onCreate(SplashScreenActivity.java:28)
03-11 00:22:28.281: E/AndroidRuntime(4411): at android.app.Activity.performCreate(Activity.java:5104)
03-11 00:22:28.281: E/AndroidRuntime(4411): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
03-11 00:22:28.281: E/AndroidRuntime(4411): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
03-11 00:22:28.281: E/AndroidRuntime(4411): ... 11 more
我的想法是,只需在启动画面中创建数据库
UsersDataBaseAdapter.java
public class UsersDataBaseAdapter
{
static final String DATABASE_NAME = "database.db";
static final String LOGIN = "Users";
String ID = "IdUser";
String USERNAME = "UserName";
String PASSWORD = "PASSWORD";
String ETIQUETA = "Etiqueta";
Integer COUNT = 0;
static String PATH = "/data/data/my.example.com/databases/database.db";
static final int DATABASE_VERSION = 1;
public static final int NAME_COLUMN = 1;
static final String DATABASE_CREATE = "CREATE TABLE IF NOT exists Users( IdUser INTEGER PRIMARY KEY, UserName VARCHAR, PASSWORD VARCHAR, Etiqueta VARCHAR); ";
public static SQLiteDatabase db;
// Context of the application using the database.
private final Context context;
// Database open/upgrade helper
private static DataBaseHelper dbHelper;
public UsersDataBaseAdapter(Context _context)
{
context = _context;
dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
if(db == null) db = dbHelper.getWritableDatabase();
String Query = "Select IdUser, UserName, Etiqueta, PASSWORD From Users LIMIT 1";
Cursor D = db.rawQuery(Query, null);
D.moveToFirst();
ID = D.getString(0);
USERNAME = D.getString(1);
ETIQUETA = D.getString(2);
PASSWORD = D.getString(3);
String QueryCheck= "select DISTINCT tbl_name from sqlite_master where tbl_name = '"+"Users"+"'";
Cursor A = db.rawQuery(QueryCheck, null);
A.getCount();
if(A!=null) COUNT = A.getCount();
}
public UsersDataBaseAdapter open() throws SQLException
{
db = dbHelper.getWritableDatabase();
return this;
}
public UsersDataBaseAdapter read() throws SQLException
{
db = dbHelper.getReadableDatabase();
return this;
}
public void close()
{
db.close();
}
public SQLiteDatabase getDatabaseInstance()
{
return db;
}
public void insertRecords(String userName,String password, Integer uid)
{
ContentValues newValues = new ContentValues();
// Asigna los valores para cada "row" (la fila).
newValues.put(USERNAME, userName);
newValues.put(PASSWORD, password);
newValues.put(ID, uid);
// Inserta el "row" (la fila) en la tabla
db.insert(LOGIN, null, newValues);
///Toast.makeText(context, "Reminder Is Successfully Saved", Toast.LENGTH_LONG).show();
}
public void updateEti(String userName, String etiqueta)
{
// Define la actualización del contenido del "row" (fila).
ContentValues updatedValues = new ContentValues();
// Asigna los valores de cada "row" (fila).
updatedValues.put(USERNAME, userName);
updatedValues.put(ETIQUETA, etiqueta);
String where=USERNAME+" = ?";
db.update(LOGIN,updatedValues, where, new String[]{userName});
}
//
public static Boolean CheckTable() {
SQLiteDatabase helppo = db;
Cursor cursor = helppo.rawQuery("select DISTINCT tbl_name from sqlite_master where tbl_name = '"+LOGIN+"'", null);
if(cursor!=null) {
if(cursor.getCount()>0) {
cursor.close();
return true;
}
cursor.close();
}
return false;
}
public String CheckEtiqueta(String LOGIN2) {
String Query = "Select * Form Users LIMIT 1";
Cursor c = db.rawQuery(Query, null);
while (c.moveToNext()) {
//Sample operation with the Database
if (c.getString(c.getColumnIndex("IdUser"))!=null) {
return c.getString(c.getColumnIndex("IdUser"));
}
}
return c.getString(c.getColumnIndex("IdUser"));
}
public static String getIDUsuario(){
String Query = "Select * From Users LIMIT 1";
Cursor D = db.rawQuery(Query, null);
D.moveToFirst();
String Var1 = D.getString(0);
return Var1;
}
public static String getUsuario(){
String Query = "Select * From Users LIMIT 1";
Cursor D = db.rawQuery(Query, null);
D.moveToFirst();
String Var1 = D.getString(1);
return Var1;
}
public static String getPassword(){
String Query = "Select * From Users LIMIT 1";
Cursor D = db.rawQuery(Query, null);
D.moveToFirst();
String Var1 = D.getString(2);
return Var1;
}
public static String getEtiqueta(){
String Query = "Select * From Users LIMIT 1";
Cursor D = db.rawQuery(Query, null);
D.moveToFirst();
String Var1 = D.getString(3);
return Var1;
}
public static boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
checkDB = SQLiteDatabase.openDatabase("/data/data/my.example.com/databases/database.db", null,
SQLiteDatabase.OPEN_READONLY);
checkDB.close();
} catch (SQLiteException e) {
// database doesn't exist yet.
}
return checkDB != null ? true : false;
}
public static SQLiteDatabase getReadableDatabase() {
db = dbHelper.getReadableDatabase();
return db;
}
public static boolean databaseExist()
{
String DB_PATH=PATH;
SQLiteDatabase checkDB = null;
try {
checkDB = SQLiteDatabase.openDatabase(DB_PATH, null, SQLiteDatabase.OPEN_READONLY);
checkDB.close();
return true;
}
catch(SQLiteException e) {
// Log an info message stating database doesn't exist.
}
return false;
}
boolean isTableExists(SQLiteDatabase db, String tableName)
{
if (tableName == null || db == null || !db.isOpen()) {
return false;
}
Cursor cursor = db.rawQuery("SELECT COUNT(*) FROM sqlite_master WHERE type = ? AND name = ?",
new String[] {"table", tableName});
if (!cursor.moveToFirst())
{
return false;
}
int count = cursor.getInt(0);
cursor.close();
return count > 0;
}
public static int ExisteTabla(){
String Query = "Select * From Users LIMIT 1";
Cursor D = db.rawQuery(Query, null);
D.moveToFirst();
int Var1 = D.getCount();
return Var1;
}
DataBaseHelper.java
public class DataBaseHelper extends SQLiteOpenHelper
{
public DataBaseHelper(Context context, String name,CursorFactory factory, int version)
{
super(context, name, factory, version);
}
// Manda llamar cuando la base de datos NO existe en disco y el "helper class" (La clase auxiliar) requiere
// crear uno nuevo.
@Override
public void onCreate(SQLiteDatabase _db)
{
_db.execSQL(UsersDataBaseAdapter.DATABASE_CREATE);
}
// Called when there is a database version mismatch meaning that the version
// of the database on disk needs to be upgraded to the current version.
@Override
public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion)
{
// Log the version upgrade.
Log.w("TaskDBAdapter", "Upgrading from version " +_oldVersion + " to " +_newVersion + ", which will destroy all old data");
// Actualiza la base de datos existente para conformar la nueva version. Multiple
// Puede realizar por comparacion de los valores entre los _oldVersion y _newVersion
// The simplest case is to drop the old table and create a new one.
_db.execSQL("DROP TABLE IF EXISTS " + "TEMPLATE");
// Create a new one.
onCreate(_db);
}
}
答案 0 :(得分:1)
错误可能是数据库中没有任何数据导致D.moveToFirst();导致错误
将其更改为
if (D.moveToFirst()){
ID = D.getString(0);
USERNAME = D.getString(1);
ETIQUETA = D.getString(2);
PASSWORD = D.getString(3);
}