0

I am trying to show data in a recycler view from SQLite database class "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 = "NewPersonManager";

// New Person table name
private static final String TABLE_NEW_PERSON = "newPerson";

// New Person Table Columns names
private static final String KEY_NAME = "name";
private static final String KEY_ID = "id";
private static final String KEY_FACEBOOK_ID = "facebook_id";
private static final String KEY_TWITTER_ID = "twitter_id";

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

}

// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_NEW_PERSON_TABLE = "CREATE TABLE " + TABLE_NEW_PERSON +
            "("+KEY_ID + " INTEGER PRIMARY KEY,"+ KEY_NAME + " TEXT, "  + KEY_FACEBOOK_ID + " TEXT," + KEY_TWITTER_ID + " TEXT " + ")";
    db.execSQL(CREATE_NEW_PERSON_TABLE);
}

// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older table if existed
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NEW_PERSON);

    // Create tables again
    onCreate(db);
}
// Adding new contact
public void addNewPerson(New_Person_data newPerson) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_NAME, newPerson.getmUserName()); // Person Name
    values.put(KEY_FACEBOOK_ID, newPerson.getmFacebookId()); // Person Facebook ID
    values.put(KEY_TWITTER_ID, newPerson.getmTwitterId()); //Person Twitter ID
    // Inserting Row
    db.insert(TABLE_NEW_PERSON, null, values);
    db.close(); // Closing database connection

}

// Getting single Person
public New_Person_data getPerson(int id) {
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.query(TABLE_NEW_PERSON, new String[] {KEY_ID,KEY_NAME, KEY_FACEBOOK_ID,
                    KEY_TWITTER_ID }, KEY_ID + "=?",
            new String[] { String.valueOf(id) }, null, null, null, null);
    if (cursor != null)
        cursor.moveToFirst();

    New_Person_data newPerson = new New_Person_data
            ( Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2));
    // return New Person
    return newPerson;
}

// Getting All Persons
    public List<New_Person_data> getAllPeople() {
        List<New_Person_data> PeopleList = new ArrayList<New_Person_data>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_NEW_PERSON;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                New_Person_data newPerson = new New_Person_data();
                newPerson.setID(Integer.parseInt(cursor.getString(0)));
                newPerson.setmUserName(cursor.getString(1));
                newPerson.setmFacebookId(cursor.getString(2));
                newPerson.setmTwitterId(cursor.getString(2));
                // Adding person to list
                PeopleList.add(newPerson);
            } while (cursor.moveToNext());
        }

        // return people list
        return PeopleList;
}



// Getting PEOPLE Count
public int getPeopleCount() {
    String countQuery = "SELECT  * FROM " + TABLE_NEW_PERSON;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    cursor.close();

    // return count
    return cursor.getCount();

}

// Updating single person
public int updatePerson(New_Person_data new_person_data) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_NAME, new_person_data.getmUserName());
    values.put(KEY_FACEBOOK_ID, new_person_data.getmFacebookId());
    values.put(KEY_FACEBOOK_ID, new_person_data.getmTwitterId());

    // updating row
    return db.update(TABLE_NEW_PERSON, values, KEY_ID + " = ?",
            new String[] { String.valueOf(new_person_data.getID()) });
}

// Deleting single person
public void deletePerson(New_Person_data newPerson) {
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(TABLE_NEW_PERSON, KEY_ID + " = ?",
            new String[] { String.valueOf(newPerson.getID()) });
    db.close();
}

}

and save the data when user clicked on DONE icon from Add_New_Person fragment

 @Override
public boolean onOptionsItemSelected(MenuItem item) {
    int itemId =item.getItemId();
    New_Person_data  new_person_data;
    if(itemId == R.id.new_person_done)

        userName = mUserName.getText().toString();
        facebookId = mFacebookId.getText().toString();
        twitterId = mTwitterId.getText().toString();

    // after user click done image , add new person row
        new_person_data= new New_Person_data(userName,facebookId,twitterId);
        databaseHandler.addNewPerson(new_person_data);
        getActivity().finish();

    return true;
}

In another fragment, I made a method to get an array of "People" class that has a constractur with one String parameter "userName which I get it from New_Person_Class...

`private void preparePeopleData() {

    DatabaseHandler databaseHandler = new DatabaseHandler(this.getContext());


    // List to get all people from database
    List<New_Person_data> peopleArrayList = databaseHandler.getAllPeople();
    //get people's user name and add to people class to show in recycler view
    for (New_Person_data newPerson:peopleArrayList) {
        People People = new People(newPerson.getmUserName());
        PeopleList.add(People);
    }


    Log.d("Peple Array size ", String.valueOf(peopleArrayList.size()));

    // sort user name from A-Z
    Collections.sort(PeopleList, new Comparator<People>() {
        @Override
        public int compare(People lhs, People rhs) {
            return lhs.getPerson().compareTo(rhs.getPerson());
        }
    });

    // set the new changes of data
    mAdapter.notifyDataSetChanged();

}`

At the end after running app and insert date an three edit Text in the Add New Person activity and click done it shows blank recycler view.

Edit* I found that the data does appear only after running the app again, so every time I need to show the added item I need to run the app again .. why it's not updated immediately?

LCTS
  • 286
  • 2
  • 10
  • r u sure data is getting inserted into DB . Use stetho to check if data is inserted or not. Check this to know how to use Stetho https://github.com/facebook/stetho – suja Jan 28 '18 at 14:41
  • @suja I found that the data does appear only after running the app again, so every time I need to show the added item I need to run the app again .. why it's not updated immediately? – LCTS Jan 28 '18 at 14:55
  • try adding loadercallback in your fragments/activity. so that your recycler will update when ever a data is inserted successfully into DB. – suja Jan 30 '18 at 09:27

1 Answers1

0

Problem solved by Override onStart method and invoke the method that gives data to the recycler view.

  @Override
public void onStart() {
    super.onStart();
    preparePeopleData();
}
LCTS
  • 286
  • 2
  • 10