SQLiteOpenHelper的onCreate方法没有获取并向sqlite db插入数据

时间:2017-08-22 20:14:31

标签: android sqlite retrofit2

我想从网络服务中获取数据,并在应用程序的生命周期内将其插入sqlite DB一次,并且可能会更新时间,我试图以这种方式完成工作

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 = "currencyManager";

    // Contacts table name
    public static final String TABLE_CURRENCY = "currency";

    // Contacts Table Columns names
    public static final String KEY_ID = "id";
    public static final String KEY_CURRENCY_POSTFIX = "currencyPostfix";
    public static final String KEY_CURRENCY_RATE = "currencyRate";

    private RestManager mRestManager;
    private Call<List<Currency>> mCurrencyCall;

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

    @Override
    public void onCreate(final SQLiteDatabase sqLiteDatabase) {
        String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CURRENCY + "("
                + KEY_ID + " INTEGER PRIMARY KEY," + KEY_CURRENCY_POSTFIX + " TEXT,"
                + KEY_CURRENCY_RATE + " REAL" + ")";
        sqLiteDatabase.execSQL(CREATE_CONTACTS_TABLE);

        //Get data from API service and insert once for the life time of the App
        mRestManager = new RestManager();
        mCurrencyCall = mRestManager.getApiService().getRates();
        mCurrencyCall.enqueue(new Callback<List<Currency>>() {
            @Override
            public void onResponse(Call<List<Currency>> call, retrofit2.Response<List<Currency>> response) {
                try{
                    if (null != response.body()){
                        for (Currency currency : response.body()){
                            insertOnceAtStartUp(sqLiteDatabase, new Rate(currency.getAbbr(), currency.getRate()));
                        }

                        Log.e("CURRENCY_COUNT", "is " + DatabaseHandler.this.getRatesCount());

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

            @Override
            public void onFailure(Call<List<Currency>> call, Throwable t) {

            }
        });


    }

    private int getRatesCount() {
        int rowCount = 0;
        SQLiteDatabase db = DatabaseHandler.this.getReadableDatabase();
        String countQuery = "SELECT  * FROM " + DatabaseHandler.TABLE_CURRENCY;
        Cursor cursor = db.rawQuery(countQuery, null);
        if(cursor != null && !cursor.isClosed()){
            rowCount = cursor.getCount();
            cursor.close();
        }

        // return count
        return rowCount;

    }

    private void insertOnceAtStartUp(SQLiteDatabase db, Rate rate){
        db = DatabaseHandler.this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(DatabaseHandler.KEY_CURRENCY_POSTFIX, rate.getCurrencyPostfix());
        values.put(DatabaseHandler.KEY_CURRENCY_RATE, rate.getCurrencyRate());

        // Inserting Row
        db.insert(DatabaseHandler.TABLE_CURRENCY, null, values);
        db.close(); // Closing database connection
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        // Drop older table if existed
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_CURRENCY);

        // Create tables again
        onCreate(sqLiteDatabase);
    }
}

上述类在Activity中调用为

public class MainActivity extends AppCompatActivity {

    private DatabaseHandler mDatabaseHandler;

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

        mDatabaseHandler = new DatabaseHandler(MainActivity.this);        
    }
}

但未创建数据库,也未从Web服务获取数据。 请问这个问题的任何解决方案吗?

1 个答案:

答案 0 :(得分:1)

关于您的具体问题,您的Retrofit调用是异步的,并且在onCreate()返回时不会完成。不要这样做。将Retrofit调用移到SQLiteOpenHelper之外的某个位置。

除此之外:

  • 请勿在{{1​​}}中致电getWritableDatabase(),因为您已经通过了数据库

  • 请勿在{{1​​}}中调用数据库中的insertOnceAtStartUp(),因为最好让您的应用程序性能更差,最糟糕的情况下会导致崩溃