I have implemented a FirebaseRecyclerAdapter to populate cities from the database in to the RecyclerView. After several fails to implement a search feature I am seeking for help. I would like to let users search for a particular city by typing the city's name (postName). The idea is to populate all of the available cities at the beginning and the desired city after its name is typed in the search field.
My code to populate the view is:
searchField = view.findViewById(R.id.search_field);
searchButton = view.findViewById(R.id.imageButton);
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String search_field = searchField.getText().toString().trim();
initialiseScreen(view, search_field);
Toast.makeText(getContext(), search_field, Toast.LENGTH_SHORT).show();
}
});
String search_field = null;
initialiseScreen(view, search_field);
return view;
}
private void initialiseScreen(final View view, String searchText) {
Query postQuery = mDataRef.orderByChild("postName").startAt(searchText).endAt(searchText + "\uf8ff");
mDataRef.keepSynced(true);
recyclerView = view.findViewById(R.id.post_RV);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(mPostViewAdapter);
FirebaseRecyclerOptions postOptions = new FirebaseRecyclerOptions.Builder<Post>()
.setQuery(postQuery, Post.class).build();
mPostViewAdapter = new FirebaseRecyclerAdapter<Post, PostViewHolder>(postOptions) {
#Override
protected void onBindViewHolder(PostViewHolder holder, int position, final Post model) {
final String post_key = getRef(position).getKey();
holder.setPostCityImage(model.getImageURL());
holder.setPostCityName(model.getPostName());
holder.setLikeBtn(post_key);
//When is clicked once go to city fragment
holder.cityImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Add code here
Intent singlePostIntent = new Intent(getActivity(), CitiesActivity.class);
singlePostIntent.putExtra("blog_id", post_key);
startActivity(singlePostIntent);
}
});
//Likes button
holder.likes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mProccessLike = true;
String postId = model.getmUid();
mDatabaseLikesRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(mProccessLike) {
if (dataSnapshot.child(post_key).hasChild(current_user_id)) {
mDatabaseLikesRef.child(post_key).child(current_user_id).removeValue();
mProccessLike = false;
} else {
mDatabaseLikesRef.child(post_key).child(current_user_id).setValue("RandomValue");
mProccessLike = false;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
//
}
Btw it populates only one city if instead of String search_field = null; I write something like String search_field = "Calp, Spain";
Related
The node that I want to update is "txt98"
editText=findViewById(R.id.editBalagh);
button=findViewById(R.id.update);
databaseReference44 = FirebaseDatabase.getInstance().getReference().child("Registration Data2");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String txt98 = editText.getText().toString();
HashMap hashMap = new HashMap();
hashMap.put("txt98",txt98);
databaseReference44.child("ss3").updateChildren(hashMap).addOnSuccessListener(new OnSuccessListener() {
#Override
public void onSuccess(Object o) {
Toast.makeText(update.this, "done", Toast.LENGTH_SHORT).show();
}
});
}
});
You missed to add a a node: the key which starts with (KAsr..) complete it in below script.
editText=findViewById(R.id.editBalagh);
button=findViewById(R.id.update);
databaseReference44 = FirebaseDatabase.getInstance().getReference().child("Registration Data2");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String txt98 = editText.getText().toString();
HashMap hashMap = new HashMap();
hashMap.put("txt98",txt98);
databaseReference44.child("KAsr.....").child("ss3").updateChildren(hashMap).addOnSuccessListener(new OnSuccessListener() {
#Override
public void onSuccess(Object o) {
Toast.makeText(update.this, "done", Toast.LENGTH_SHORT).show();
}
});
}
});
I use Firebase Storage to store an image file and when I tried to send it to the Realtime Database the data rewrote the whole data so my existing data is gone and replaced by just the image URL data. How do I send it without deleting my existing data?
This is my code:
public class Utama extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
DrawerLayout drawerLayout;
private Button uploadBTN;
private ImageView imageView;
private ProgressBar progressBar;
private TextView namapengguna, emailpengguna;
private View headerView;
private FirebaseUser user;
private DatabaseReference root;
private StorageReference reference;
private Uri imageUri;
private String userID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_utama);
drawerLayout = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
headerView = navigationView.getHeaderView(0);
uploadBTN = findViewById(R.id.upload_btn);
progressBar = findViewById(R.id.progressBar);
imageView = findViewById(R.id.imageview);
namapengguna = (TextView) headerView.findViewById(R.id.namalengkap);
emailpengguna = (TextView) headerView.findViewById(R.id.emailpengguna);
progressBar.setVisibility(View.INVISIBLE);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, 2);
}
});
uploadBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (imageUri != null) {
uploadToFirebase(imageUri);
} else {
Toast.makeText(Utama.this, "Please Select Image", Toast.LENGTH_SHORT).show();
}
}
});
user = FirebaseAuth.getInstance().getCurrentUser();
root = FirebaseDatabase.getInstance().getReference("Users");
reference = FirebaseStorage.getInstance().getReference();
userID = user.getUid();
final TextView fullNameTextView = (TextView) findViewById(R.id.fullName);
final TextView emailTextView = (TextView) findViewById(R.id.emailaddress);
root.child(userID).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
User userProfile = snapshot.getValue(User.class);
if (userProfile != null) {
String fullName = userProfile.fullname;
String email = userProfile.email;
fullNameTextView.setText(fullName);
namapengguna.setText(fullName);
emailTextView.setText(email);
emailpengguna.setText(email);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(Utama.this, "Terjadi Kesalahan Pada Database", Toast.LENGTH_LONG).show();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 2 && resultCode == RESULT_OK && data != null) {
imageUri = data.getData();
imageView.setImageURI(imageUri);
}
}
private void uploadToFirebase(Uri uri) {
StorageReference fileRef = reference.child(System.currentTimeMillis() + "." + getFileExtension(uri));
fileRef.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl();
while (!uriTask.isSuccessful());
final Uri downloadUri = uriTask.getResult();
if (uriTask.isSuccessful()){
HashMap<String,Object> result = new HashMap<>();
result.put(userID,downloadUri.toString());
root.child(userID).updateChildren(result).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
progressBar.setVisibility((View.INVISIBLE));
Toast.makeText(Utama.this, "Your Profile succesfully changed", Toast.LENGTH_SHORT).show();
imageView.setImageResource(R.drawable.ic_add_photo);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(Utama.this, "", Toast.LENGTH_SHORT).show();
}
});
}
// fileRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
// #Override
// public void onSuccess(Uri uri) {
// Model model = new Model(uri.toString());
// String modelId = root.push().getKey();
//// root.child(userID).child(modelId).setValue(model);
// root.child(userID).child(modelId).setValue(model);
// progressBar.setVisibility(View.INVISIBLE);
// Toast.makeText(Utama.this, "Upload Succesfully", Toast.LENGTH_SHORT).show();
// imageView.setImageResource(R.drawable.ic_add_photo);
// }
// });
}
})
// .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
// #Override
// public void onProgress(#NonNull UploadTask.TaskSnapshot snapshot) {
// progressBar.setVisibility(View.VISIBLE);
// }
// })
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(Utama.this,e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private String getFileExtension(Uri mUri) {
ContentResolver cr = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cr.getType(mUri));
}
public void ClickMenu(View view) {
Dashboard.openDrawer(drawerLayout);
}
public void ClickLogo(View view) {
Dashboard.closeDrawer(drawerLayout);
}
public void ClickHome(View view) {
Dashboard.redirectActivity(this, Dashboard.class);
}
public void ClickUtama(View view) {
recreate();
}
public void ClickAboutUs(View view) {
Dashboard.redirectActivity(this, AboutUs.class);
}
public void ClickLogout(View view) {
logout (this);
}
private void redirectActivity(Activity activity, Class aClass) {
Intent intent = new Intent(activity, aClass);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(intent);
}
public static void logout(Activity activity) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle("Logout");
builder.setMessage("Are you sure want to logout?");
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
activity.finishAffinity();
System.exit(0);
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
}
#Override
protected void onPause() {
super.onPause();
Dashboard.closeDrawer(drawerLayout);
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
return false;
}
}
This is for Model:
public class Model {
private String imageUrl;
public String fullname, email;
public Model (){
}
public Model(String imageUrl){
this.imageUrl = imageUrl;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
}
here is the problem how can I rename the image
here is the problem how can I rename the image
There is no need to rename the image. You can update it correctly even from the beginning. When you add data to Firebase, your structure looks like this:
Firebase-root
|
--- Users
|
--- Pp3Cc... smV2
|
--- email: "test#gmail.com"
|
--- fullname: "Test"
Now, to add a new property within the UID's node called "imageUrl", that can hold the actual URL of the photo, please change the following line of code:
result.put(userID,downloadUri.toString());
To:
result.put("imageUrl",downloadUri.toString());
In this way, your first child won't be added as:
Firebase-root
|
--- Users
|
--- Pp3Cc... smV2
|
--- Pp3Cc... smV2: "https://" //Incorrect
|
--- email: "test#gmail.com"
|
--- fullname: "Test"
But as:
Firebase-root
|
--- Users
|
--- Pp3Cc... smV2
|
--- imageUrl: "https://" //Correct
|
--- email: "test#gmail.com"
|
--- fullname: "Test"
You must use setValue to set the value to your realtime database.
The current method which you are using replace the completed data under userId, but if you wish to update a specific field, you should
root.child("users").child(userId).setValue(user)
use something like this.
I am currently programin a test QuizApp. The gameplay is pretty easy I just want an online database of questions and a user can answer them.
This is what the database looks like:
That collection questions contains an unique ID and a custom Object (questionObject) named 'content'. The number is only something easy I can query/search for.
This is my questionAdder and query UI. It's only a small test App.
public class questionAdder extends AppCompatActivity {
EditText pQuestion, pAnwerA, pAnswerB, pAnswerC, pAnswerD, number;
Button pAdd, query;
private DatabaseReference databaseReference;
private FirebaseFirestore firebaseFirestore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addquestion);
firebaseFirestore = FirebaseFirestore.getInstance();
pQuestion = (EditText) findViewById(R.id.question);
pAnwerA = (EditText) findViewById(R.id.answerA);
pAnswerB = (EditText) findViewById(R.id.answerB);
pAnswerC = (EditText) findViewById(R.id.answerC);
pAnswerD = (EditText) findViewById(R.id.answerD);
number = (EditText) findViewById(R.id.number);
pAdd = (Button) findViewById(R.id.addQuestion);
pAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
readQuestionStore();
}
});
query = (Button) findViewById(R.id.query);
query.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CollectionReference questionRef = firebaseFirestore.collection("questions");
questionRef.whereEqualTo("content.number", "20").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
questionObject pContent = queryDocumentSnapshots.toObjects(questionObject.class);
}
});
}
});
}
public void readQuestionStore(){
Map<String, Object> pContent = new HashMap<>();
pContent.put("question", pQuestion.getText().toString());
pContent.put("Corr Answer", pAnwerA.getText().toString());
pContent.put("AnswerB", pAnswerB.getText().toString());
pContent.put("AnswerC", pAnswerC.getText().toString());
pContent.put("AnswerD", pAnswerD.getText().toString());
questionObject content = new questionObject(pContent, number.getText().toString()); //document("Essen").collection("Katalog")
firebaseFirestore.collection("questions").add(content).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
Toast.makeText(questionAdder.this, "Klappt", Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(questionAdder.this, "Klappt nicht", Toast.LENGTH_LONG).show();
}
});
}
}
And this is how my questionObject looks like:
public class questionObject{
private Map<String, Object> content;
private String number;
public questionObject(){
}
public questionObject(Map<String, Object> pContent, String pNumber) {
this.content = pContent;
this.number = pNumber;
}
public Map<String, Object> getContent() {
return content;
}
public void setContent(Map<String, Object> content) {
this.content = content;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
}
Problem In that questionAdder class in the onClickListener I receive an "incompatible types" Error (Found: java.utils.list Required: questionObject).
query.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CollectionReference questionRef = firebaseFirestore.collection("questions");
questionRef.whereEqualTo("content.number", "20").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
questionObject pContent = queryDocumentSnapshots.toObjects(questionObject.class);
}
});
}
});
If if I change that to a List it is empty. So the actual question is, how do I get the CustomObject into my code using the Database. Thanks!
The reason you are getting this error in because the QuerySnapshot is a type which "contains" multiple documents. Firestore won't decide for you whether there are a bunch of objects to return as a result, or just one.
This is why you can take two different approaches:
Put the data in a custom object's list:
List<questionObject> questionsList=new ArrayList<>();
if (!documentSnapshots.isEmpty()){
for (DocumentSnapshot snapshot:queryDocumentSnapshots)
questionsList.add(snapshot.toObject(questionObject.class));
}
If you're sure that your gonna get only one queried object, you can just get the first object from the returned queryDocumentSnapshots:
questionObject object=queryDocumentSnapshots.getDocuments().get(0).toObject(questionObject.class);
A few more things you should be aware of:
Why do you write content.number instead of just number?
It seems like number is a separated field in your question document, so your code should be as follows:
CollectionReference questionRef = firebaseFirestore.collection("questions");
questionRef.whereEqualTo("number", "20").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
questionObject pContent = queryDocumentSnapshots.toObjects(questionObject.class);
}
});
In addition, try to change your number field to int, because it's not a String but a just a number.
By the way, it is more acceptable to write classes' names with a capital letter at a beginning, for example: QuestionObject question=new QuestionObject();
I've got input city form, where it has 2 element, EditText for city name and Spinner a that has been populate Province Data from Firebase database. I want to make nodes structure in Firebase like this:
database{
provinces{
provinceId_1{
provinceId_1 : value
provinceName_1 : value
}
provinceId_2{
provinceId_2 : value
provinceName_2 : value
}
}
cities{
provinceId_1{
cityId_1{
cityId_1 : value
cityName_1 : value
}
cityId_2{
cityId_2 : value
cityName_2 : value
}
}
provinceId_2{
cityId_3{
cityId_3 : value
cityName_3 : value
}
}
}
}
But i do not know how to acquire provinces id and store it to cities table in firebase database, here's my code :
public class AddCityActivity extends AppCompatActivity {
private EditText inputCity;
private Button btnAddCity, btnClearText;
private MaterialSpinner spinnerProvinces;
private DatabaseReference databaseCities, databaseProvinces;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_city);
inputCity = (EditText) findViewById(R.id.add_city_edit_text);
btnAddCity = (Button) findViewById(R.id.action_add_city_button);
btnClearText = (Button) findViewById(R.id.action_clear_text_button);
spinnerProvinces = (MaterialSpinner) findViewById(R.id.provinceSpinner);
databaseProvinces = FirebaseDatabase.getInstance().getReference().child("provinces");
databaseProvinces.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final List<String> provinces = new ArrayList<String>();
for (DataSnapshot provinceSnapshot : dataSnapshot.getChildren()) {
String provinceName = provinceSnapshot.child("provinceName").getValue(String.class);
provinces.add(provinceName);
}
MaterialSpinner provincesSpinner = (MaterialSpinner) findViewById(R.id.provinceSpinner);
ArrayAdapter<String> provincesAdapter = new ArrayAdapter<String>(AddCityActivity.this, android.R.layout.simple_spinner_item, provinces); provincesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
provincesSpinner.setAdapter(provincesAdapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
btnClearText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
inputCity.setText("");
}
});
btnAddCity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addCity();
}
});
}
private void addCity() {
String name = inputCity.getText().toString().trim();
databaseCities = FirebaseDatabase.getInstance().getReference("cities");
if (!TextUtils.isEmpty(name)) {
String id = databaseCities.push().getKey();
City city = new City(id, name);
databaseCities.child(id).setValue(city);
Toast.makeText(this, "City Added", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Enter City Name", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onBackPressed() {
startActivity(new Intent(AddCityActivity.this, LandingActivity.class));
finish();
}
}
So basically I'm collecting data from a json url in my listview. It's a chatroom type of app and in the lists I want to sync the chatroom contact lists with latest message and timestamps.
When the json gets updated I'm calling the fuction.
public void addGroupAdapter() {
Firebase jsonurl = new Firebase("firebase url");
jsonurl.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
ContactListAdapter adapter = new ContactListAdapter(getContext(),dataSnapshot);
try {
Log.i("Response Array fire",new JSONArray(dataSnapshot.getValue(String.class)).toString());
if (!adapted){
chatLists.setAdapter(adapter);
adapted = true;
}else {
Log.i("update",dataSnapshot.getValue(String.class));
adapter.setContactList(dataSnapshot);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
That Json data is stored in the firebase database .
chatLists.setAdapter(adapter) works well.
But when I try to update. notifyDataSetChanged(); doesn't work.
new ContactListAdapter(getContext(),dataSnapshot).notifyDataSetChanged();
I also tried invalidateviews method and same result. So where am I doing wrong?
After reading answers I tried this. SO now this my adapter class,
class ContactListAdapter extends BaseAdapter {
Context c;
List lists;
Type type = new TypeToken<List<ChatroomLists>>(){}.getType();
JsonParser parser = new JsonParser();
ArrayList<ChatroomLists> ob1 = new ArrayList<ChatroomLists>();
public void setContactList(DataSnapshot dataSnapshot) {
Type listType = new TypeToken<ArrayList<ChatroomLists>>() {
}.getType();
ob1 = new Gson().fromJson((JsonArray)parser.parse(dataSnapshot.getValue(String.class)),listType);
Log.i("setContactList",dataSnapshot.getValue(String.class));
notifyDataSetChanged();
}
ContactListAdapter(Context c, DataSnapshot group_name) {
this.c = c;
this.groupids = group_name;
Type listType = new TypeToken<ArrayList<ChatroomLists>>() {
}.getType();
ob1 = new Gson().fromJson((JsonArray)parser.parse(group_name.getValue(String.class)),listType);
}
#Override
public int getCount() {
return ob1.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
GroupChat.viewHolder holder = null;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) c.getSystemService (Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate (R.layout.chat_list_style, parent, false);
holder = new GroupChat.viewHolder(row);
row.setTag (holder);
} else {
holder = (GroupChat.viewHolder) row.getTag ();
}
ChatroomLists chatroomLists = ob1.get(position);
Iterator<ChatroomLists> iter = ob1.iterator();
String id = chatroomLists.getId();
String time = chatroomLists.getTimestamp();
Log.i("updated data",id + time);
viewHolder finalHolder = holder;
Firebase chatlink = new Firebase ("firebase link");
chatlink.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot d: dataSnapshot.getChildren()){
finalHolder.user_message.setText (dataSnapshot.child(d.getKey()).child("message").getValue(String.class));
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
Firebase imageurl = new Firebase("firebase link");
imageurl.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Glide.with (getActivity ())
.load (dataSnapshot.getValue(String.class))
.error (R.drawable.man)
.into (finalHolder.user_img);
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
holder.user_name.setText (id);
row.setOnClickListener (new View.OnClickListener () {
#Override
public void onClick(View v) {
Intent intent = new Intent (getActivity (), ChatRoom.class);
intent.putExtra ("group_name", id);
startActivity (intent);
}
});
registerForContextMenu (row);
return row;
}
}
But it's still not updating.. :(
UPDATE: Listview was so buggy in this case. And I changed to Recyclerview. Now everything is working smoothly.
This is because you are creating new adapter instance instead of updating data on existing adapter which is set on list/recyclerview.
private ContactListAdapter mAdatper;
public void addGroupAdapter() {
Firebase jsonurl = new Firebase("firebase url");
jsonurl.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
try {
Log.i("Response Array fire",new JSONArray(dataSnapshot.getValue(String.class)).toString());
if (!adapted){
mAdatper = new ContactListAdapter(getContext(),dataSnapshot);
chatLists.setAdapter(mAdapter);
adapted = true;
}else {
Log.i("update",dataSnapshot.getValue(String.class));
mAdatper.setContactList(dataSnapshot);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
}
In your adapter, add setter method.
public void setContactList(DataSnapshot dataSnapshot) {
// set contactList here
notifyDataSetChanged();
}
Hope it might be helpful for you.
You are calling notifyDataSetChanged() on a new instance of the adapter everytime. You should call it on the same adapter that you set on the list. And you should update the data in that particular instance of the adapter
In your else case you are creating a new ContactListAdapter but you are not attaching that adapter to your chatLists. Anyway, you do not need to create a new CustomAdapter instance, just create a update method within your CustomAdapter and call it passing new dataSnapshot data.
You can Try something as the following inside your CustomAdapter.java:
public void updateData(Data data) {
this.dataList = data;
notifyDataSetChanged();
}
Then back into your addGroupAdapter method just call that method