Retrieving Data from Firebase real time Database to ListView - java

I've problem storing data into ListView from database on Firebase, I'm using the method below it runs when I click on button,
here is the method I use
private void retrieveMyDataMethod(){
databaseReference = FirebaseDatabase.getInstance().getReference();
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String name = dataSnapshot.child(uid).child("name").getValue(String.class);
String address = dataSnapshot.child(uid).child("address").getValue(String.class);
String[] data = new String[]{
name, address
};
List<String> data_list = new ArrayList<String>(Arrays.asList(data));
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data_list);
listViewRe.setAdapter(arrayAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}

To solve this, please use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.orderByChild("name");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
ArrayList<String> list = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String name = ds.child("name").getValue(String.class);
list.add(name);
}
ListView listView = (ListView) findViewById(R.id.list_view);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, list);
listView.setAdapter(arrayAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
query.addListenerForSingleValueEvent(valueEventListener);
The output in your ListView will be:
cmon
here

Related

How do i fix recyclerview shows database entrys twice after new entry?

My Code
FloatingActionButton button;
button = findViewById(R.id.floatbtn);
if (button != null) {
button.setOnClickListener(new android.view.View.OnClickListener() {
#Override
public void onClick(android.view.View v) {
startActivity(new Intent(Userlist.this, AddTextActivity.class));
recyclerView.removeAllViews();
recyclerView.removeAllViewsInLayout();
}
});
}
recyclerView = findViewById(R.id.userList);
database = FirebaseDatabase.getInstance().getReference("Messages");
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
list = new ArrayList<>();
myAdapter = new MyAdapter(this, list);
recyclerView.setAdapter(myAdapter);
database.addValueEventListener(new ValueEventListener() {
#SuppressLint("NotifyDataSetChanged")
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
Text text = dataSnapshot.getValue(Text.class);
list.add(text);
}
myAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
How do i fix recyclerview shows database entrys twice after new entry
I try to delete to remove all Views when Activity is closing. This didnt work.
Can you help me with this problem?
Why is this happening at all?

I want to fetch Product ID from Firebase

I am retrieving Product Information from Firebase, but the issue is that I can't select any specific ID that is stored in Firebase.
I tried different solutions for the problem including get(position) but it's getting the position of the product in the RecyclerView
This the ProductsAdapter onBindViewHolder function.
Changes are added using *'s
#Override
public void onBindViewHolder(#NonNull ProductViewHolder holder, int position) {
Product productCurrent = mProducts.get(position);
holder.product_title.setText(toCapitalize(productCurrent.getpTitle()));
holder.product_pice.setText("$: " + productCurrent.getpPrice());
Picasso.with(mContext)
.load(productCurrent.getpImageUrl())
.placeholder(R.mipmap.ic_launcher)
.fit()
.centerCrop()
.into(holder.product_image);
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, ProductPreview.class);
intent.putExtra("pImageUrl", productCurrent.getpImageUrl());
intent.putExtra("pTitle", toCapitalize(productCurrent.getpTitle()));
intent.putExtra("pPrice", productCurrent.getpPrice());
intent.putExtra("pDescription", toCapitalize(productCurrent.getpDescription()));
Toast.makeText(mContext, " " + position, Toast.LENGTH_SHORT).show();
mContext.startActivity(intent);
}
});
}
This Code is from the ProductsActivity having the RecyclerView
private ProductsAdapter mAdapter;
private ProgressBar mProgressBar;
DatabaseReference mDatabaseReference;
private ArrayList<Product> mProducts;
***ArrayList<ProductKeys> mProductKeys;***
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_products);
mRecyclerView = findViewById(R.id.products_recycler_view);
mRecyclerView.setHasFixedSize(true);
GridLayoutManager gridLayoutManager = new GridLayoutManager(getApplicationContext(),2);
mRecyclerView.setLayoutManager(gridLayoutManager);
mProgressBar = (ProgressBar) findViewById(R.id.progress_bar);
mProducts = new ArrayList<>();
***mProductKeys = new ArrayList<>();***
mDatabaseReference = FirebaseDatabase.getInstance().getReference("products");
mDatabaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapShot : dataSnapshot.getChildren())
{
Product product = postSnapShot.getValue(Product.class);
mProducts.add(product);
***mProductKeys.add(postSnapShot.getKey());***
}
mAdapter = new ProductsAdapter(ProductsActivity.this, mProducts);
mRecyclerView.setAdapter(mAdapter);
mProgressBar.setVisibility(View.INVISIBLE);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(ProductsActivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
mProgressBar.setVisibility(View.INVISIBLE);
}
});
Getting Error:
(com.*)
in ArrayList cannot be applied
to
(java.lang.String)
Please help me out of this... Thanks in Advance
If you're trying to determine the Firebase Database ID of the item at position in the onBindViewHolder method, you will have to maintain that mapping yourself. You can easily do this by extracting both the getKey() as well as the getValue() from the snapshot in onDataChange and keeping lists of both of them.
Something like this:
mProductKeys = new ArrayList<String>();
mDatabaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapShot : dataSnapshot.getChildren())
{
Product product = postSnapShot.getValue(Product.class);
mProducts.add(product);
mProductKeys.add(postSnapShot.getKey());
}
mAdapter = new ProductsAdapter(ProductsActivity.this, mProducts);
mRecyclerView.setAdapter(mAdapter);
mProgressBar.setVisibility(View.INVISIBLE);
}
And then in the onBindViewHolder you can look up the key for the item that was clicked on in mProductKeys.
Ok, I tried different things and #Frank's answer gave me some idea to do this. Just added one Line and its done. :) No Need to add ArrayList<String>.
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapShot : dataSnapshot.getChildren())
{
Product product = postSnapShot.getValue(Product.class);
product.setpKey(postSnapShot.getKey());
mProducts.add(product);
}
mAdapter = new ProductsAdapter(ProductsActivity.this, mProducts);
mRecyclerView.setAdapter(mAdapter);
mProgressBar.setVisibility(View.INVISIBLE);
}
And Added the String pKey to my Product.class with Setter and Getter.

OnItemClicklistener returning somthing else

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("Users");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> al = new ArrayList<>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String rId = ds.child("Phone_Number").getValue(String.class);
String name = ds.child("Name").getValue(String.class);
al.add(name);
al.add(rId);
}
ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, android.R.id.text1, al);
ListView listView = rootView.findViewById(R.id.usersList);
listView.setAdapter(adapter);
mProgressDialogue.dismiss();
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(getActivity(), "Please Check Your Internet Connection", Toast.LENGTH_SHORT).show();
}
};
usersRef.addListenerForSingleValueEvent(eventListener);
usersList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//This cannot be done in this way
Intent intent = new Intent(getActivity(), Chat.class);
String rId = (String)parent.getItemAtPosition(position);
String name = (String)parent.getItemAtPosition(position);
intent.putExtra("Recievers_Id", rId);
intent.putExtra("Recievers_Name", name);
startActivity(intent);
}
});
return rootView;
It's like. In the listview... Of the same user userid and name is shown... Ik y that is shown. Its because I hav added al.add (name) and also id... That's becuase... In onclicklistener I want to fetch id of the user but the listview should contain names... I'm not able to do that... Like if I click on the name of the user it fetches name and if I click on id of the user it fetches id... I want it to work like... IF I CLICK ON NAME OF THE USER IT SHOULD FETCH ID

Make listView clickable in android [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I have code that ought to make my ListView clickable and bring my user to another activity. But I'm getting an error saying
Attempt to invoke virtual method 'void android.widget.ListView.setClickable(boolean)' on a null object reference
But I've no idea how it's a null object reference if the ListView is working. Here is my feed code:
public void populateList() {
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference allBooksRef = rootRef.child("All_Books");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<Book> bookModelList = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
Book book = ds.getValue(Book.class);
bookModelList.add(book);
}
ListView list = (ListView) findViewById(R.id.listView);
CustomListAdapter adapter = new CustomListAdapter(AdminFeed.this, bookModelList);
list.setAdapter(adapter);
list.setClickable(true);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
allBooksRef.addListenerForSingleValueEvent(valueEventListener);
list.setClickable(true);
list.setOnItemClickListener((AdapterView.OnItemClickListener) this);
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(AdminFeed.this, BookIndexed.class);
i.putExtra("ValueKey", modelList.get(position).getTitle());
i.putExtra("ValueKey2", modelList.get(position).getAuthor());
startActivity(i);
title = bookModelList.get(position).getTitle();
}
Why is this throwing up such an error?
Move findViewById outside ValueEventListener() like below code
Try this
public void populateList() {
ListView list = (ListView) findViewById(R.id.listView);
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference allBooksRef = rootRef.child("All_Books");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<Book> bookModelList = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
Book book = ds.getValue(Book.class);
bookModelList.add(book);
}
CustomListAdapter adapter = new CustomListAdapter(AdminFeed.this, bookModelList);
list.setAdapter(adapter);
list.setClickable(true);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
allBooksRef.addListenerForSingleValueEvent(valueEventListener);
list.setClickable(true);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent i = new Intent(AdminFeed.this, BookIndexed.class);
i.putExtra("ValueKey", modelList.get(position).getTitle());
i.putExtra("ValueKey2", modelList.get(position).getAuthor());
startActivity(i);
title = bookModelList.get(position).getTitle();
}
});
}

selected item on spinner won't work (ANDROID)

My data comes from Firebase database. I successfully populated the busNumto the spinner. But my problem is whenever I got to select the busnum, nothing shows up on my spinner. Here are some of codes.
List<String> busnum = new ArrayList<String>();
busRef = new Firebase(Config.FIREBASE_URL_BUSNUMBER);
busRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
busnum.add(postSnapshot.child("busNum").getValue().toString());
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Toast.makeText(AddDriverActivity.this, "Failed to read data.... " +firebaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, busnum);
mSpinBusNum.setPrompt("Select bus number");
mSpinBusNum.setAdapter(adapter);
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
busNum = parent.getItemAtPosition(position).toString();
}
You must set Adapter after on datachange like this:
//after onDataChange
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, busnum);
mSpinBusNum.setPrompt("Select bus number");
// Apply the adapter to the spinner
mSpinBusNum.setAdapter(adapter);
ArrayList<String> issueCategoryArrayList = new ArrayList<String>();
FirebaseDatabase.getInstance().getReference("issue_categories").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
issueCategoryArrayList.add(dataSnapshot1.getValue(IssueCategory.class).getTitle());
}
spinner = findViewById(R.id.post_category);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(PostActivity.this,
android.R.layout.simple_spinner_item, issueCategoryArrayList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);;
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Categories

Resources