-1

im making simple notes app width Sqlite Mysql sync. The problem is that when i save my data in edit_note_fragment and then go back to fragment width my recyclerView my list don't load new data. It's because String request take a while to perform and saves data after my list is already refreshed in my recyclerView. I already tried to delay the refresh but the ansfer from server sometimes takes longer and the same thing happen. Any idea how execute refresh after the data was saved? Here is my code

edit note fragment

    buttonBack.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (StringId != null) {
                UpdateNote();
                    }else { CreateNote(); }

            Fragment fragment = new NotesFragment();
            FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.frameLayoutHome, fragment);
            fragmentTransaction.addToBackStack(null);
            fragmentTransaction.commit();
        }
    });

}


 private void CreateNote() {
   final String name = EtTitle.getText().toString().trim();
    final  String des =  EtDes.getText().toString().trim();
    StringRequest stringRequest = new StringRequest(Request.Method.POST, Api.URL_CREATE_IVDATA,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject obj = new JSONObject(response);
                        if (!obj.getBoolean("error")) {
                            //if there is a success
                            Log.d(TAG, "Created");
                            //storing the name to sqlite with status synced
                            JSONArray ivdata = (obj.getJSONArray("ivdata"));
                            for (int i = 0; i < ivdata.length(); i++) {
                                JSONObject json = ivdata.getJSONObject(i);

                                int serverId = json.getInt("sid");
                                String StringSid = String.valueOf(serverId);

                                saveNameToLocalStorage(name, des,  NAME_SYNCED_WITH_SERVER, StringSid);


                            }
                        } else {
                            //if there is some error
                            //saving the name to sqlite with status unsynced
                            saveNameToLocalStorage(name, des, NAME_NOT_SYNCED_WITH_SERVER, null);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                    saveNameToLocalStorage(name, des,  NAME_NOT_SYNCED_WITH_SERVER, null);
                    Log.d(TAG, "saving to local storage");

                }
            }) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> params = new HashMap<>();
            params.put("t1", myToken);
            params.put("t2", "notes");
            params.put("c1", name);
            params.put("c2", des);
            return params;
        }
    };

    VolleySingleton.getInstance(context).addToRequestQueue(stringRequest);
}
 private void saveNameToLocalStorage(String name,String des, int status, String sid) {
        mDatabase.addNote(name, des, status, sid);
        Note n = new Note(name,des, status, sid);
        noteList.add(n);

    }

fragment width my recyclerview(refresh is in executed in onViewCreated)

private void refresh()
    {
        noteList.clear();
        mDatabase = new SqliteDatabase(context);
        noteList = mDatabase.listContacts();
        Log.d(TAG, "refreshing");

        if(!(noteList.size()<1))
        {
            notesAdapter = new NotesAdapter(noteList, context, this);
            recyclerView.setAdapter(notesAdapter);
        } else {
            recyclerView.setVisibility(View.GONE);
            Toast.makeText(context, "There is no Notes in the database. Start adding now", Toast.LENGTH_LONG).show();
        }

    }

SqliteDatabaseHelper

public ArrayList<Note> listContacts() {
        String sql = "select * from " + TABLE_NAME;
        SQLiteDatabase db = this.getReadableDatabase();
        ArrayList<Note> noteList= new ArrayList<>();
        Cursor cursor = db.rawQuery(sql, null);
        if (cursor.moveToFirst()) {
            do {
                int id = Integer.parseInt(cursor.getString(0));
                String c1 = cursor.getString(1);
                String c2 = cursor.getString(2);
                int status = Integer.parseInt(cursor.getString(3));
                String sid = cursor.getString(4);
                noteList.add(new Note(id, c1, c2, status, sid));
            }
            while (cursor.moveToNext());
        }
        cursor.close();
        return noteList;
    }

  public boolean addNote(String name,String des, int status, String sid) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();

        contentValues.put(COLUMN_NAME, name);
        contentValues.put(COLUMN_DESC, des);
        contentValues.put(COLUMN_STATUS, status);
      contentValues.put(COLUMN_SID, sid);


        db.insert(TABLE_NAME, null, contentValues);
        db.close();
        return true;
    }
Homie
  • 1

1 Answers1

0

you can set a listener on the update of the DB. When the callback get called you refresh the list. (If I understood the problem correctly lol)

SQLITE DB UPDATE CALLBACKS

Davide
  • 73
  • 6
  • Im not sure how to do this, i didnt find any good example. The problem is : when i click on recycler item, edit fragment is diplayed, after im finished with editing note, i click on back button that display note list fragment and invoke UpdateNote method that save note to MySql database if im online. Saving to mysql take some time so meanwhile in note list fragment my recycler is already refreshed and old data is displayed so i want to perform refresh after note is saved to database. Can you provide some code example or procedure what i should do exacly. Thanks – Homie Jul 30 '22 at 18:49
  • It's strange it takes so much time to save to your SQLite database :/ Anyway you can use another solution like Realm or Room to save your data (I Think they are better). I think you just need to use the function "sqlite3_update_hook" on your "db" instance and set a callback to be called when the db is updated. Here you can find an example but in python (if I'm right): https://stackoverflow.com/questions/16872700/sqlite-data-change-notification-callbacks-in-python-or-bash-or-cli/16920926#16920926 – Davide Aug 01 '22 at 14:30