Answer the question
In order to leave comments, you need to log in
How to sync ListView and Firebase Database?
Good afternoon,
There is a project that is tied to the Firebase Realtime Database. The data is loaded into the SharedPreference, then into the array of objects, and finally into the ListView. The task is not to connect to the Database every time, but to show the user data from the SharedPreference, but if there have been changes in the database (adding, changing, deleting), connect to the database, update the SharedPreference and show the user updated information. And if the user, say, has the Internet turned off, then he will have information, but not relevant.
My idea is to check the size of the SharedPreference at the start of the activity and compare it with the size of the Firebase Database, if different, then run the OnDataChanged method and update the SharedPreference.
Is the idea correct or should it be implemented differently. I would be grateful for any idea to solve the problem.
This is how it is currently implemented:
public class Dictionary extends AppCompatActivity {
// Firebase db
private DatabaseReference mDictionaryDatabase;
// Android layout
private ListView listViewDictionary;
private List<DictionaryModel> arrayListDictionary;
private DictionaryAdapter dictionaryAdapter;
private SharedPreferences sPrefDictionary;
String prefWord = "firebaseKey";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dictionary);
mDictionaryDatabase = FirebaseDatabase.getInstance().getReference("dictionary");
listViewDictionary = findViewById(R.id.listViewDictionary);
arrayListDictionary = new ArrayList<>();
sPrefDictionary = getSharedPreferences(prefWord, MODE_PRIVATE);
mDictionaryDatabase.orderByChild("word").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dictionarySnapshot : dataSnapshot.getChildren()){
DictionaryModel word = dictionarySnapshot.getValue(DictionaryModel.class);
SharedPreferences.Editor editor = sPrefDictionary.edit();
editor.putString(word.getWord(), word.getDescription()).apply();
dictionaryAdapter.notifyDataSetChanged();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
Map<String,?> keys = sPrefDictionary.getAll();
for(Map.Entry<String,?> entry : keys.entrySet()){
DictionaryModel dm = new DictionaryModel(entry.getKey(), entry.getValue().toString());
arrayListDictionary.add(dm);
}
dictionaryAdapter = new DictionaryAdapter(Dictionary.this, arrayListDictionary);
listViewDictionary.setAdapter(dictionaryAdapter);
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question