【问题标题】:Android SQLite Table not created未创建 Android SQLite 表
【发布时间】:2017-08-15 15:56:14
【问题描述】:

我正在尝试创建一个统计表,但由于某种原因,直到我第一次调用 StatisticsAdapter.insertEntry() 时它才会创建。之后,我可以删除该代码,重新加载新版本,然后一切正常。由于这在现实生活中行不通,我想知道如何创建一个空表?

目前if(StatisticsAdapter.getCount(isbn) < 1) 有一个错误,因为它说没有这样的表。为什么会这样?

主代码

StatisticsAdapter=new StatisticsAdapter(this);
    StatisticsAdapter=StatisticsAdapter.open();
    Calendar curDate = Calendar.getInstance();
    if(StatisticsAdapter.getCount(isbn) < 1)
        StatisticsAdapter.insertEntry(isbn, curDate.get(Calendar.YEAR), (curDate.get(Calendar.MONTH)+1), 1);
    else
        StatisticsAdapter.increaseCount(isbn);

StatisticsAdapter

public class StatisticsAdapter {
public static final int NAME_COLUMN = 1;
static final String tableName="STATISTICS";
// TODO: Create public field for each column in your table.
// SQL Statement to create a new database.
public static final String STATISTICS_TABLE_CREATE = "create table "+"STATISTICS"
        + "( " +"ID"+" integer primary key autoincrement,"
        + "ISBN text,"
        + "YEAR text,"
        + "MONTH text,"
        + "COUNT integer); ";
// Variable to hold the database instance
public  SQLiteDatabase db;
// Context of the application using the database.
private final Context context;
// Database open/upgrade helper
private DataBaseHelper dbHelper;
public  StatisticsAdapter(Context _context) 
{
    context = _context;
    dbHelper = new DataBaseHelper(context);
}
public  StatisticsAdapter open() throws SQLException 
{
    db = dbHelper.getWritableDatabase();
    return this;
}
public void close() 
{
    db.close();
}

public  SQLiteDatabase getDatabaseInstance()
{
    return db;
}

public void insertEntry(String ISBN, int year, int month, int count)
{
   ContentValues newValues = new ContentValues();
    // Assign values for each row.
    newValues.put("ISBN", ISBN);
    newValues.put("YEAR", ((Integer)year).toString());
    if(month>=10)
        newValues.put("MONTH", ((Integer)month).toString());
    else
        newValues.put("MONTH", "0"+((Integer)month).toString());
    newValues.put("COUNT", count);

    // Insert the row into your table
    db.insert("STATISTICS", null, newValues);
    ///Toast.makeText(context, "Reminder Is Successfully Saved", Toast.LENGTH_LONG).show();
}
public int getCount(String ISBN)
    {
        //Query
        String query = "select COUNT from STATISTICS where ISBN = ?";
        Cursor cursor = db.rawQuery(query, new String[] {ISBN});
        if(cursor.getCount()<1) // title Not Exist
        {
            cursor.close();
            return 0;
        }
        cursor.moveToFirst();
        int count = cursor.getInt(cursor.getColumnIndex("COUNT"));
        cursor.close();
        return count;               
    }

DataBaseHelper

public class DataBaseHelper extends SQLiteOpenHelper
{   
    // Database Version
        private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "database.db";

    // ============================ End Variables ===========================

    public DataBaseHelper(Context context, String name, CursorFactory factory, int version) 
    {
               super(context, name, factory, version);
    }

    public DataBaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Called when no database exists in disk and the helper class needs
    // to create a new one.
    @Override
    public void onCreate(SQLiteDatabase _db) 
    {
            _db.execSQL(LoginDataBaseAdapter.USER_TABLE_CREATE);
            _db.execSQL(CheckOutDataBaseAdapter.CHECKOUT_TABLE_CREATE);
            _db.execSQL(InventoryAdapter.INVENTORY_TABLE_CREATE);
            _db.execSQL(StatisticsAdapter.STATISTICS_TABLE_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");


            // Upgrade the existing database to conform to the new version. Multiple
            // previous versions can be handled by comparing _oldVersion and _newVersion
            // values.
            // on upgrade drop older tables
            _db.execSQL("DROP TABLE IF EXISTS " + LoginDataBaseAdapter.USER_TABLE_CREATE);
            _db.execSQL("DROP TABLE IF EXISTS " + CheckOutDataBaseAdapter.CHECKOUT_TABLE_CREATE);
            _db.execSQL("DROP TABLE IF EXISTS " + InventoryAdapter.INVENTORY_TABLE_CREATE);
            _db.execSQL("DROP TABLE IF EXISTS " + StatisticsAdapter.STATISTICS_TABLE_CREATE);

            // Create a new one.
            onCreate(_db);
    }

}

【问题讨论】:

    标签: android sqlite


    【解决方案1】:

    尝试扩展SQLiteOpenHelper

    覆盖

    @Override
      public void onCreate(SQLiteDatabase database) {
        database.execSQL(DATABASE_CREATE);
      }
    

    在调用getWritableDatabase()getReadableDatabase() 之一之前,不会实际创建或打开数据库。

    【讨论】:

    • 你能详细说明你的意思吗?我以为我已经在 DataBaseHelper 中进行了覆盖。我将如何以及在哪里打电话给getWritableDatabase()getReadableDatabase()
    • 正如我上面提到的,您缺少 DataBaseHelper 类中的 onCreate 方法。 STATISTICS_TABLE_CREATE 也需要移到 DataBaseHelper 类中。
    【解决方案2】:

    您是否尝试过在运行代码之前卸载应用程序?如果您之前的代码版本创建的 db 没有统计表,您必须增加数据库版本 (DatabaseHelper.DATABASE_VERSION) 以触发 onUpgrade 调用,这将创建表。

    您可以尝试的第二件事是将表名提取为常量并使用它来代替硬编码字符串。也许你在某个地方有错字?

    我还建议从设备中提取数据库并使用命令行 sqlite 客户端检查其架构:

    adb shell
    busybox cp data/data/com.your.package/databases/database.db /sdcard
    exit
    adb pull /sdcard/database.db
    sqlite3 database.db
    .schema
    

    【讨论】:

      【解决方案3】:

      创建类DatabaseHandler extends SQLiteOpenHelper

      并像下面这样覆盖:

      // Creating Tables
      @Override
      public void onCreate(SQLiteDatabase db) {
          String CREATE_CONTACTS_TABLE = Crate table query;
          db.execSQL(CREATE_CONTACTS_TABLE);
      }
      

      现在,您想从您的Activity 调用SQLiteDatabase db = cintext.getWritableDatabase(); 来访问数据库表。

      【讨论】:

      • 我这样做了,但我仍然遇到同样的问题。
      • @erad 你的查询在这里也是错误的。 “ID 整数主键自动增量”。无需声明自动增量。声明为 INTEGER PRIMARY KEY 的列将在 SQLite 中自动递增。
      【解决方案4】:

      当设备上的应用程序版本较低并且您更改数据库(添加表,创建新数据库,...)并安装新版本时,会发生此问题,现在应用程序尝试创建新数据库但不能在数据库上创建和更改修改。

      解决办法是:

      只需更改DATABASE_VERSION

      应用强制创建新数据库

      祝你好运

      【讨论】:

        【解决方案5】:

        只需更新 dbHelper 类中的 DATABASE_VERSION。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-07-12
          • 2018-10-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多