我将故事名称称为 _TodayDate ,但每当数据发生变化时,表示不存在此类表格。
这是我的DatabaseHandler
昨天工作正常,但每当日期发生变化时,应用程序都会崩溃。
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "entryManager";
private static String getTableName(){
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
String date = "_"+df.format(calendar.getTime());
return date;
}
// Contacts table name
private String TABLE_DATE = getTableName();
//String formattedDate = DateFormat.getDateFormat().format(new Date());
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_ROLL = "Roll";
private static final String KEY_DATE = "Date";
private static final String KEY_TIME = "Time";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_ENTRY_TABLE = "CREATE TABLE " +TABLE_DATE + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_ROLL + " TEXT,"
+ KEY_DATE + " TEXT," + KEY_TIME + " TEXT" + ")";
db.execSQL(CREATE_ENTRY_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_DATE);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new contact
void addEntry(EntryDetails entryDetails) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ROLL, entryDetails.getRoll()); // ROll
values.put(KEY_DATE, entryDetails.getDate()); // Date
values.put(KEY_TIME, entryDetails.getTime()); //Time
// Inserting Row
db.insert(TABLE_DATE, null, values);
db.close(); // Closing database connection
}
// Getting single contact
EntryDetails getEntryDetails(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_DATE, new String[] { KEY_ID,
KEY_ROLL, KEY_DATE, KEY_TIME }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
EntryDetails entryDetails = new EntryDetails(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2), cursor.getString(3));
// return contact
return entryDetails;
}
// Getting All Contacts
public List<EntryDetails> getAllEntries() {
List<EntryDetails> entryDetailses = new ArrayList<EntryDetails>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_DATE;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
EntryDetails entryDetails = new EntryDetails();
entryDetails.set_id(Integer.parseInt(cursor.getString(0)));
entryDetails.setRoll(cursor.getString(1));
entryDetails.setDate(cursor.getString(2));
entryDetails.setTime(cursor.getString(3));
// Adding contact to list
entryDetailses.add(entryDetails);
} while (cursor.moveToNext());
}
// return contact list
return entryDetailses;
}
// Updating single contact
public int updateEntry(EntryDetails entryDetails) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ROLL, entryDetails.getRoll());
values.put(KEY_DATE, entryDetails.getDate());
values.put(KEY_TIME, entryDetails.getTime());
// updating row
return db.update(TABLE_DATE, values, KEY_ID + " = ?",
new String[] { String.valueOf(entryDetails.get_id()) });
}
// Deleting single contact
public void deleteEntry(EntryDetails entryDetails) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_DATE, KEY_ID + " = ?",
new String[] { String.valueOf(entryDetails.get_id()) });
db.close();
}
// Getting contacts Count
public int getEntryCount() {
String countQuery = "SELECT * FROM " + TABLE_DATE;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
这是logcat。据说没有这样的表格。
E/SQLiteLog: (1) no such table: _20180121
01-21 00:31:32.078 7788-
7788/com.jagdishchoudhary.iitgandhinagarmesssystem E/AndroidRuntime:
FATAL EXCEPTION: main
Process: com.jagdishchoudhary.iitgandhinagarmesssystem, PID: 7788
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.jagdishchoudhary.iitgandhinagarmesssystem/com.jagdishchoudhary.iitgandhinagarmesssystem.MainActivity}: android.database.sqlite.SQLiteException: no such table: _20180121 (code 1): , while compiling: SELECT * FROM _20180121
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2659)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
Caused by: android.database.sqlite.SQLiteException: no such table: _20180121 (code 1): , while compiling: SELECT * FROM _20180121
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1318)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1257)
at com.jagdishchoudhary.iitgandhinagarmesssystem.DatabaseHandler.getAllEntries(DatabaseHandler.java:117)
at com.jagdishchoudhary.iitgandhinagarmesssystem.MainActivity.onCreate(MainActivity.java:135)
答案 0 :(得分:1)
根据您的经验,只要日期发生变化,表名就会发生变化。那是因为您将当前日期作为表名称。但是,不会创建这样的表,除非首次运行App,因为onCreate
方法只会在创建数据库(表的容器)时运行,即它只运行一次。 / p>
正确的解决方案是不使用动态表名而是使用固定的表名。如果日期是一个重要因素,您应该在表格中有一个列的日期(如您所示),然后使用此列来区分数据。
如果您真的想要每个日期的表,那么您可以修改表定义以在IF NOT EXISTS
方法中包含onCreate
,然后在构造DatabaseHandeler时调用它。
所以你可以这样做: -
1)修改DatabaseHandler的onCreate
方法,以便表定义包含IF NOT EXISTS
: -
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_ENTRY_TABLE = "CREATE TABLE IF NOT EXISTS " +TABLE_DATE + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_ROLL + " TEXT,"
+ KEY_DATE + " TEXT," + KEY_TIME + " TEXT" + ")";
db.execSQL(CREATE_ENTRY_TABLE);
}
2)修改DatabaseHandler的构造函数以始终调用onCreate
。 : -
public DatabaseHandlerDates(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
onCreate(this.getWritableDatabase()); //<<<< ADDED
}
<强>警告!关于使用多个/动态表格
onUpgrade
方法是不够的,因为它只会DROP并重新创建当前日期的表。所有其他表都不会升级。 (您可以通过从sqlite_master表中提取表列表来确定所有表。)您可以使用ALTER TABLE
sql语句来RENAME
表名。但是,您必须确定以前的表名才能重新命名(再次通过sqlite_master表进行拖网)。
处理表/数据将与建议的正确解决方案没有区别。除了在使用App时更改日期可能导致由于找不到表而导致崩溃(即任何新的DatabaseHandler实例,将使用新日期和ALTER表名,除非照顾(可能强制重启App))