【问题标题】:SQLite item not being added to databaseSQLite 项目未添加到数据库
【发布时间】:2019-02-04 03:24:58
【问题描述】:

我正在为我的 Android 应用设置 SQLite 数据库,并希望支持添加和删除 RecyclerView 项目。如何修复我的代码以便添加项目?

当我添加项目时,它们出现在 RecyclerView 但不在 SQLite 数据库中。我知道会发生这种情况,因为当我重新启动应用程序或导航到另一个片段时,RecyclerView 变为空。我还检查了 SQLite 数据库文件,它是空的。

我在 YouTube 上遵循了一些关于在 SQLite 中添加和删除项目的教程,但它们似乎都使用“ID”系统,而我的课程没有。

我尝试通过您可以在COLUMN_NAME 中看到的“名称”属性来引用 SQLite 数据库中的每个项目。这将包含一个城市名称,它是一个字符串。

我添加到我的 RecyclerView 的项目是从 JSON 生成的 POJO。

DatabaseHelper.java

public class DatabaseHelper extends SQLiteOpenHelper {

public static final String DATABASE_NAME = "stations.db";
private static final int DATABASE_VERSION = 3;
public static final String TABLE_NAME = "Station";
public static final String COLUMN_NAME = "_name";
public static final String COLUMN_JSON = "json";


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

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(" CREATE TABLE " + TABLE_NAME + " (" +
            COLUMN_NAME + " BLOB NOT NULL, " +
            COLUMN_JSON + " BLOB NOT NULL);"
    );
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // you can implement here migration process
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
    this.onCreate(db);
}

/**
 * Returns all the data from database
 * @return
 */
public Cursor getData(){
    SQLiteDatabase db = this.getWritableDatabase();
    String query = "SELECT * FROM " + TABLE_NAME;
    Cursor data = db.rawQuery(query, null);
    return data;
}

/**
 * create record
 **/
public void saveStationRecord(String stationJSON) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(COLUMN_JSON, stationJSON);
    db.insert(TABLE_NAME, null, values);
    db.close();
}

/**
 * delete record
 **/
public void deleteStationRecord(String name, Context context) {
    SQLiteDatabase db = this.getWritableDatabase();
    db.execSQL("DELETE FROM " + TABLE_NAME + " WHERE _name='" + name + "'");
}

ListAdapter.java(RecyclerView 适配器)

public void removeItem(int position) {
    Station station = stationList.get(position);
    DatabaseHelper dbHelper = new DatabaseHelper(context);
    dbHelper.deleteStationRecord(station.getData().getCity(), context);
    stationList.remove(position);
    // notify item added by position
    notifyItemRemoved(position);
    //notifyItemRangeChanged(position, stationList.size());
}

ListFragment.java(显示 RecyclerView 的地方)

@Override
public void onStart() {
    super.onStart();
    //loadDataFromFirebase();
    loadDataFromSQLiteDatabase();
}

public void addData(String data) {
    databaseHelper = new DatabaseHelper(getActivity());
    databaseHelper.saveStationRecord(data);
}

private void loadDataFromSQLiteDatabase() {
    //Get the JSON data with the DatabaseHelper class
    Cursor data = databaseHelper.getData();
    //Using Gson to turn JSON to Java object of Station
    //Create new GsonBuilder and Gson objects
    GsonBuilder gsonBuilder = new GsonBuilder();
    Gson gson = gsonBuilder.create();
    while (data.moveToNext()) {
        //Get the next JSON from the database
        String jsonResponse = data.getString(1);
        //Create a new Station object and use Gson to deserialize JSON data
        //into the Station object
        Station station = gson.fromJson(jsonResponse, Station.class);
        //Add the new Station object to the ArrayList of Station objects
        //This is to create another entry in the RecyclerView
        //Tell the RecyclerView listAdapter that our data is updated
        //because Station was just to the ArrayList
        stationList.add(station);
    }
}

private void loadSelectedDataToRecyclerView(String selectedStation) {
    RequestQueue requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
    StringRequest stringRequest = new StringRequest(Request.Method.GET, generateRequestURL(selectedStation),
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    GsonBuilder gsonBuilder = new GsonBuilder();
                    Gson gson = gsonBuilder.create();
                    Station station = gson.fromJson(response, Station.class);
                    stationList.add(station);
                    listAdapter.notifyDataSetChanged();
                    //Add the new Station object to SQLite database
                    addData(response);
                    Log.d("API RESPONSE", response);
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d("VOLLEY ERROR", error.toString());
        }
    });
    requestQueue.add(stringRequest);
}

我希望添加到 RecyclerView 的项目也将添加到 SQLite 数据库中,这样当我重新启动应用程序或导航到另一个 Fragment 时,该项目将保留在 RecyclerView 中。

【问题讨论】:

  • 嗨,谁反对这个,为什么?我能够解决我自己的问题。

标签: android sqlite android-recyclerview android-sqlite crud


【解决方案1】:

我已经解决了我的问题。

再次查看我的代码后,在saveStationRecord 中我未能指定COLUMN_NAME

这是更新后的代码。

public void saveStationRecord(String stationJSON) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    GsonBuilder gsonBuilder = new GsonBuilder();
    Gson gson = gsonBuilder.create();
    //Create a new Station object and use Gson to deserialize JSON data
    //into the Station object
    Station station = gson.fromJson(stationJSON, Station.class);
    values.put(COLUMN_NAME, station.getData().getCity());
    values.put(COLUMN_JSON, stationJSON);
    db.insert(TABLE_NAME, null, values);
    db.close();
}

我使用 Gson 将 JSON 转换回 POJO,然后将城市名称放入 COLUMN_NAME

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-30
    • 1970-01-01
    • 1970-01-01
    • 2020-02-24
    • 1970-01-01
    • 2016-11-24
    • 1970-01-01
    相关资源
    最近更新 更多