Search code examples
androidsqliteandroid-recyclerviewandroid-sqlitecrud

SQLite item not being added to database


I'm setting up a SQLite database for my Android app, and want to support adding and deleting RecyclerView items. How can I fix my code so that adding the items work?

When I add items, they appear in the RecyclerView but not in the SQLite database. I know this happens because when I relaunch the app or navigate to another Fragment the RecyclerView becomes empty. I also checked the SQLite database file and it is empty.

I followed a few tutorials on YouTube on adding and deleting items in SQLite but they all seem to use an "ID" system, which my classes do not have.

I tried to reference each item in the SQLite database through a "name" property which you can see in COLUMN_NAME. This will contain a city name, which is a String.

The items I am adding to my RecyclerView are POJO generated from JSON.

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 adapter)

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 (Where the RecyclerView is shown)

@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);
}

I expect the item that was added to the RecyclerView to be also added to the SQLite database so that when I relaunch the app or navigate to another Fragment the item will remain in the RecyclerView.


Solution

  • I've fixed my issue.

    After looking through my code again, in saveStationRecord I failed to specify the COLUMN_NAME.

    Here is the updated code.

    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();
    }
    

    I turned the JSON back into POJO with Gson then I put the city name into COLUMN_NAME.