Update listView after updating dataBase? - android

I have a listView of books ,I update listview by clicking on item and its work , but i have duplicate item , the old one and the new one.in my database i have just the new data. How can i also modify my listview? I'm using FireBase Database.
Update with source of my activity:
public class ListOfMyBookActivity extends AppCompatActivity {
//The elements are initialized here
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_of_my_book);
listView = (ListView) findViewById(R.id.list_book);
feedItems = new ArrayList<Book>();
dataBD= FirebaseDatabase.getInstance();
dataBaseD=FirebaseDatabase.getInstance();
updateDB=FirebaseDatabase.getInstance();
ref = dataBD.getReference("books");
refdelete=dataBaseD.getReference("books");
refUpdate=updateDB.getReference("books");
auth = FirebaseAuth.getInstance();
mDatabase = FirebaseDatabase.getInstance().getReference("books");
ref.orderByChild("date_creation").limitToLast(10).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> list = new ArrayList<String>();
for (DataSnapshot dataSnap : dataSnapshot.getChildren()) {
Book valueBook = dataSnap.getValue(Book.class);
keyId = dataSnap.getKey();
String userBd = valueBook.getId_user();
if (userBd.equalsIgnoreCase(id_user)) {
String titreLivreToDisplay = valueBook.getNom_livre();
String descLivreToDisplay = valueBook.getDesc_livre();
String prixLivreToDisplay = valueBook.getPrix_livre();
String timeToDisplay = valueBook.getDate_creation();
String filePathToDiplay = valueBook.getChemin_image();
String villeToDisplay = valueBook.getVille_livre();
String typeAnnToDisplat = valueBook.getType_annonce_selected();
String bookid = valueBook.getId_book();
item = new Book();
item.setNom_livre(titreLivreToDisplay);
item.setDesc_livre(descLivreToDisplay);
item.setPrix_livre(prixLivreToDisplay);
item.setDate_creation(timeToDisplay);
item.setChemin_image(filePathToDiplay);
item.setVille_livre(villeToDisplay);
item.setType_annonce_selected(typeAnnToDisplat);
item.setId_book(bookid);
item.setKeyIdNode(keyId);
feedItems.add(item);
}
Collections.reverse(feedItems);
listAdapter = new MyBookListAdapter(ListOfMyBookActivity.this, feedItems);
listView.setAdapter(listAdapter);
listView.setOnItemClickListener(myClickListener);
listAdapter.notifyDataSetChanged();
}}
});
}
public AdapterView.OnItemClickListener myClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
final int position, long arg3) {
deleteItem = position;
// The AlertDialog is created programmatically
AlertDialog.Builder alert = new AlertDialog.Builder(arg1.getContext());
nameBookEdtDlg.setText(nom);
descBookEdtDlg.setText(desc);
prixBookEdtDlg.setText(prix);
alert.setPositiveButton("Update ",
new DialogInterface.OnClickListener()
{
public void onClick (DialogInterface dialog,
int whichButton){
Query query = refUpdate.orderByChild("id_book").equalTo(bookID);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
prixSt=prixBookEdtDlg.getText().toString();
descSt=descBookEdtDlg.getText().toString();
namSt=nameBookEdtDlg.getText().toString();
Map<String, Object> result = new HashMap<String, Object>();
result.put("nom_livre", namSt);
result.put("desc_livre", descSt);
result.put("prix_livre", prixSt);
result.put("date_creation", currentDateandTimeUpdate);
refUpdate.child(keyId).updateChildren(result);
listAdapter.notifyDataSetChanged();
} });
AlertDialog alertDialog = alert.create();
try{alertDialog.show();} } };}
}
}
The Adapter :
public class MyBookListAdapter extends BaseAdapter {
public MyBookListAdapter( ListOfMyBookActivity listMyBooks, List<Book> feedItemsBooks) {
this.activity = listMyBooks;
this.feedItemsBooks = feedItemsBooks;
}
#Override
public int getCount() {
return feedItemsBooks.size();
}
#Override
public Object getItem(int location) {
return feedItemsBooks.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, final ViewGroup parent) {
final int pos = position;
if (inflater == null) {
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (convertView == null) {
convertView = inflater.inflate(R.layout.feed_list_item, null);
}
storageDisplayImg = FirebaseStorage.getInstance();
auth = FirebaseAuth.getInstance();
FirebaseUser userConnect = auth.getCurrentUser();
String id_user = userConnect.getUid();
mFirebaseInstance = FirebaseDatabase.getInstance();
mFirebaseDatabase = mFirebaseInstance.getReference("books");
final ImageView profilePic = (ImageView) convertView.findViewById(R.id.book_picture_display_myBook);
name = (TextView) convertView.findViewById(R.id.name_book_display_myBook);
TextView timestamp = (TextView) convertView.findViewById(R.id.timestamp_myBook);
statusMsg = (TextView) convertView.findViewById(R.id.desc_display_myBook);
prix = (TextView) convertView.findViewById(R.id.prix_display_myBook);
TextView ville = (TextView) convertView.findViewById(R.id.ville_display_myBook);
TextView typeCat = (TextView) convertView.findViewById(R.id.type_ann_to_display_myBook);
Book item = feedItemsBooks.get(position);
idLivreListAdapter=item.getId_book();
name.setText(item.getNom_livre());
if (!TextUtils.isEmpty(item.getDate_creation())) {
timestamp.setText(item.getDate_creation());
timestamp.setVisibility(View.VISIBLE);
} else {
timestamp.setVisibility(View.GONE);
}
if (!TextUtils.isEmpty(item.getDesc_livre())) {
statusMsg.setText(item.getDesc_livre());
statusMsg.setVisibility(View.VISIBLE);
} else {
statusMsg.setVisibility(View.GONE);
}
if (!TextUtils.isEmpty(item.getType_annonce_selected())) {
typeCat.setText(item.getType_annonce_selected());
typeCat.setVisibility(View.VISIBLE);
} else {
typeCat.setVisibility(View.GONE);
}
if (item.getPrix_livre() != null) {
prix.setText(item.getPrix_livre() + " DH");
prix.setVisibility(View.VISIBLE);
} else {
prix.setVisibility(View.GONE);
}
if (item.getVille_livre() != null) {
ville.setText(item.getVille_livre());
ville.setVisibility(View.VISIBLE);
} else {
ville.setVisibility(View.GONE);
}
storageRef = storageDisplayImg.getReferenceFromUrl(item.getChemin_image());
Log.e(" ", " storageRef " + storageRef.toString());
if (item.getChemin_image() != null && id_user != null) {
Glide.with(convertView.getContext())
.using(new FirebaseImageLoader())
.load(storageRef)
.into(profilePic);
profilePic.setVisibility(View.VISIBLE);
} else {
profilePic.setVisibility(View.GONE);
}
return convertView;
}
}
My question is not duplicated I tried the proposed solutions but it does not work.

Not sure if this if your problem, but most of that firebase code isn't all necessary...
Notice you call getNom_livre (and others) and then call setNom_livre (and others) with the exact same value?
You also make a new Book when you already have one.
Book valueBook = dataSnap.getValue(Book.class); // This is a Book
keyId = dataSnap.getKey();
String userBd = valueBook.getId_user();
if (userBd.equalsIgnoreCase(id_user)) {
String titreLivreToDisplay = valueBook.getNom_livre();
...
item = new Book(); // Why do you need a new one?
item.setNom_livre(titreLivreToDisplay);
...
feedItems.add(item);
}
First, you should move this before the firebase method. There is no need to recreate the adapter every data update.
listAdapter = new MyBookListAdapter(ListOfMyBookActivity.this, feedItems);
listView.setAdapter(listAdapter);
listView.setOnItemClickListener(myClickListener);
ref.orderByChild("date_creation")...
but i have duplicate item , the old one and the new one
You simply need to clear the adapter to remove old data and add the new stuff
ref.orderByChild("date_creation")
.limitToLast(10)
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Remove old data
feedItems.clear();
// Add new data
for (DataSnapshot dataSnap : dataSnapshot.getChildren()) {
Book valueBook = dataSnap.getValue(Book.class);
keyId = dataSnap.getKey();
String userBd = valueBook.getId_user();
if (userBd.equalsIgnoreCase(id_user)) {
valueBook.setKeyIdNode(keyId);
feedItems.add(valueBook);
}
}
Collections.reverse(feedItems);
listAdapter.notifyDataSetChanged(); // Tell adapter of new data

Use feedItems.clear() before getting updated data from firebase.
Try this:
ref.orderByChild("date_creation").limitToLast(10).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
feedItems.clear();
.............
..................
}
});

try
feedItems.remove(position);
// listView.invalidateViews();
arrayAdapter.notifyDataSetChanged();

use this in your adapter
public void dataSetChanged(ArrayList<Movie>list)
{
this.list=list;
this.notifyDataSetChanged();
}
and use it like this
upadte your list data and after that use below line
customListViewAdapter.dataSetChanged(movieList);

use this for update your list
notifyDataSetChanged()

Related

Import an firebase image when i click it in the recyclerView?

What I've done alone so far is to bring up a activity (recyclerView of the products) when I click ImageView 1.
When I click on the image of recyclerView, my goal is to load the image I clicked on ImageView 1 and save it in DB.
How can I get an image?
this is my product's adapter
#NonNull
#Override
public HolderProductCody onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
//inflate layout
View view = LayoutInflater.from(context).inflate(R.layout.row_product_seller,parent,false);
return new HolderProductCody(view);
}
#Override
public void onBindViewHolder(#NonNull HolderProductCody holder, int position) {
//get data
final ModelProduct modelProduct = productList.get(position);
String id = modelProduct.getProductId();
String uid = modelProduct.getUid();
String detailAvailable = modelProduct.getDetailAvailable();
String productColor = modelProduct.getProductColor();
String productTpo = modelProduct.getProductTpo();
String productDescription = modelProduct.getProductDescription();
String productCategory = modelProduct.getProductCategory();
String icon = modelProduct.getProductIcon();
String SeasonCategory = modelProduct.getProductSeasonCategory();
String productSeasonCategory = modelProduct.getProductSeasonCategory();
String title = modelProduct.getProductTitle();
String timestamp = modelProduct.getTimestamp();
String originalPrice = modelProduct.getOriginalPrice();
//set data
holder.titleTv.setText(title);
holder.SeasonCategoryTv.setText(SeasonCategory);
holder.tpoTv.setText(productTpo);
holder.colorTv.setText(productColor);
holder.originalPriceTv.setText("$"+originalPrice);
if(detailAvailable.equals("true")){
//product is on discount
holder.tpoTv.setVisibility(View.VISIBLE);
holder.colorTv.setVisibility(View.VISIBLE);
}
else{
//product is not on discount
holder.tpoTv.setVisibility(View.GONE);
holder.colorTv.setVisibility(View.GONE);
}
try{
Picasso.get().load(icon).placeholder(R.drawable.ic_tshirt_black).into(holder.productIconIv);
}
catch(Exception e){
holder.productIconIv.setImageResource(R.drawable.ic_tshirt_black);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//handle item clicks, show item details
Toast.makeText(context, "클릭됨", Toast.LENGTH_SHORT).show();
//addcodylayout(modelProduct);
}
});
}
private void addcodylayout(ModelProduct modelProduct) {
Dialog dialog = new Dialog(context);
View view = LayoutInflater.from(context).inflate(R.layout.activity_cody_product,null);
dialog.setContentView(view);
dialog.show();
//get data
final String id = modelProduct.getProductId();
String uid = modelProduct.getUid();
String detailAvailable = modelProduct.getDetailAvailable();
String productTpo = modelProduct.getProductTpo();
String productColor = modelProduct.getProductColor();
String productDescription = modelProduct.getProductDescription();
String productCategory = modelProduct.getProductCategory();
String icon = modelProduct.getProductIcon();
String productSeasonCategory = modelProduct.getProductSeasonCategory();
final String title = modelProduct.getProductTitle();
String timestamp = modelProduct.getTimestamp();
String originalPrice = modelProduct.getOriginalPrice();
try{
Picasso.get().load(icon).placeholder(R.drawable.ic_tshirt_black).into(productIconIv);
}
catch(Exception e){
productIconIv.setImageResource(R.drawable.ic_tshirt_black);
}
dialog.show();
}
#Override
public int getItemCount() {
return productList.size();
}
#Override
public Filter getFilter() {
if(filter==null){
filter = new FilterProduct(this,filterList);
}
return filter;
}
class HolderProductCody extends RecyclerView.ViewHolder{
/*holds views of recyclerview*/
private ImageView productIconIv;
private TextView tpoTv, titleTv, SeasonCategoryTv,colorTv,originalPriceTv;
public HolderProductCody(#NonNull View itemView) {
super(itemView);
productIconIv = itemView.findViewById(R.id.productIconIv);
tpoTv = itemView.findViewById(R.id.tpoTv);
titleTv = itemView.findViewById(R.id.titleTv);
SeasonCategoryTv = itemView.findViewById(R.id.categorySeasonTv);
colorTv = itemView.findViewById(R.id.colorTv);
originalPriceTv = itemView.findViewById(R.id.originalPriceTv);
}
}
}
this is my product's activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cody_product);
filterProductBtn = findViewById(R.id.filterProductBtn);
productsRv = findViewById(R.id.productsRv);
filteredProductsTv = findViewById(R.id.filteredProductsTv);
getSupportActionBar().hide();
firebaseAuth = FirebaseAuth.getInstance();
filterProductBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(CodyProductActivity.this);
builder.setTitle("카테고리 선택").setItems(Constants.productCategories1, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//get selected item
String selected = Constants.productCategories1[which];
filteredProductsTv.setText(selected);
if (selected.equals("모든 옷")) {
//load all
loadAllProducts();
} else {
//load filtered
loadFilteredProducts(selected);
}
}
}).show();
}
});
}
private void loadFilteredProducts(String selected) {
productList = new ArrayList<>();
//get all products
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
reference.child(firebaseAuth.getUid()).child("Products").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//before getting reset List
productList.clear();
for(DataSnapshot ds: dataSnapshot.getChildren()){
String productCategory = ""+ds.child("productCategory").getValue();
//if selected category matches product category then add in list
if(selected.equals(productCategory)){
ModelProduct modelProduct = ds.getValue(ModelProduct.class);
productList.add(modelProduct);
}
}
//setup adapter
adapterProductCody = new AdapterProductCody(CodyProductActivity.this,productList);
//set adapter
GridLayoutManager layoutManager = new GridLayoutManager(CodyProductActivity.this,3);
productsRv.setLayoutManager(layoutManager);
productsRv.setAdapter(adapterProductCody);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseerror) {
}
});
}
private void loadAllProducts() {
productList = new ArrayList<>();
//get all products
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
reference.child(firebaseAuth.getUid()).child("Products").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//before getting reset List
productList.clear();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
ModelProduct modelProduct = ds.getValue(ModelProduct.class);
productList.add(modelProduct);
}
//setup adapter
adapterProductCody = new AdapterProductCody(CodyProductActivity.this, productList);
//set adapter
GridLayoutManager layoutManager = new GridLayoutManager(CodyProductActivity.this, 3);
productsRv.setLayoutManager(layoutManager);
productsRv.setAdapter(adapterProductCody);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
The ID value of ImageView1 is topImages.

Firebase ListView is not updating in real time

When I make changes to the data which is displayed using ListView and DataSnapshot the data is not refreshed in real time until I restart the Activity. The ListView loads and displays all the data without any problem. Why is this happening and how to solve this ?
MainMenuRequest.java
public class MainMenuRequest extends AppCompatActivity {
String UserNameString;
DatabaseReference db;
ListView lv;
ArrayList<RequestItem> list = new ArrayList<>();
RequestItemAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu_request);
makeItem();
}
public void makeItem ()
{
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReferenceFromUrl("https://vsem-inventory.firebaseio.com/ItemRequest");
ValueEventListener valueEventListener = new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
list = new ArrayList<RequestItem>();
for(DataSnapshot dSnapshot : dataSnapshot.getChildren()) {
for(DataSnapshot ds : dSnapshot.getChildren()) {
RequestItem Ri = ds.getValue(RequestItem.class);
Ri.setRefID(ds.getKey());
Log.d("myTag",ds.getKey());
list.add(Ri);
}
}
lv = findViewById(R.id.listViewRequest);
adapter = new RequestItemAdapter(MainMenuRequest.this,list);
lv.setAdapter(adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("DatabaseError", databaseError.getMessage()); //Don't ignore errors!
}
};
rootRef.addListenerForSingleValueEvent(valueEventListener);
}
}
RequestItemAdapter.java
public class RequestItemAdapter extends ArrayAdapter<RequestItem> {
private Context ctx;
private ArrayList<RequestItem> list;
ImageView statusimg;
Drawable lateIcon;
Drawable paidIcon;
public RequestItemAdapter(Context context, ArrayList<RequestItem> list)
{
super(context,0,list);
this.ctx = context;
this.list = list;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listItem = convertView;
if(listItem == null)
listItem = LayoutInflater.from(ctx).inflate(R.layout.content_main_menu_request_list,parent,false);
final RequestItem rq = list.get(position);
final TextView tvAmount = listItem.findViewById(R.id.amountReq);
final TextView tvName = listItem.findViewById(R.id.nameReq);
final TextView tvSerial = listItem.findViewById(R.id.serialNoReq);
final TextView tvSupplier = listItem.findViewById(R.id.supplierNameReq);
final ImageView more = listItem.findViewById(R.id.moreReq);
statusimg = listItem.findViewById(R.id.statusReq);
lateIcon = listItem.getResources().getDrawable(R.drawable.late);
Drawable pendingIcon = listItem.getResources().getDrawable(R.drawable.pending);
String userName = rq.getRequestBy();
userName = userName.replace("#vsemtech.com","");
tvAmount.setText(userName);
tvName.setText(rq.getProductName());
tvSerial.setText(rq.getSerialNo());
tvSupplier.setText(rq.getCategory());
String status = rq.getStatus();
if(status.equals("REJECT"))
statusimg.setImageDrawable(lateIcon);
else if (status.equals("APPROVED"))
statusimg.setImageDrawable(paidIcon);
else if (status.equals("PENDING"))
statusimg.setImageDrawable(pendingIcon);
more.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
String RequestBy = rq.getRequestBy();
String Status = rq.getStatus();
String ProductName = rq.getProductName();
String SerialNo = rq.getSerialNo();
String Model = rq.getModel();
String Category = rq.getCategory();
String Quantity = rq.getQuantity();
String Remarks = rq.getRemarks();
showMenu(rq,more);
}
});
return listItem;
}
public void showMenu (RequestItem reqItem,ImageView More)
{
final RequestItem finalItem = reqItem;
final ImageView more = More;
final String shortRequestby = reqItem.getRequestBy().replace("#vsemtech.com","");
final DatabaseReference DeleteRef = FirebaseDatabase.getInstance().getReference().child("ItemRequest").child(shortRequestby);
final DatabaseReference DbRef = FirebaseDatabase.getInstance().getReference().child("ItemRequest").child(shortRequestby).child(finalItem.getRefID());
//Creating the instance of PopupMenu
PopupMenu popup = new PopupMenu(ctx, more);
//Inflating the Popup using xml file
popup.getMenuInflater().inflate(R.menu.menu_options_req, popup.getMenu());
//registering popup with OnMenuItemClickListener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.item_approve)
{
DeleteRef.child(finalItem.getRefID()).removeValue();
writeNewPost(new RequestItem(finalItem,"APPROVED"));
Toast.makeText(ctx,"Successfully approved request made by " + shortRequestby ,Toast.LENGTH_SHORT).show();
}
else if (itemId == R.id.item_reject)
{
DeleteRef.child(finalItem.getRefID()).removeValue();
writeNewPost(new RequestItem(finalItem,"REJECTED"));
Toast.makeText(ctx,"Successfully rejected request made by " + shortRequestby ,Toast.LENGTH_SHORT).show();
}
return true;
}
});
popup.show();//showing popup menu
}
public void writeNewPost(RequestItem item)
{
DatabaseReference dbReq = FirebaseDatabase.getInstance().getReference().child("ItemHistory").child(item.getRequestBy().replace("#vsemtech.com",""));
String key = dbReq.push().getKey();
Map<String, Object> postValues = toMap(item);
Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put(key, postValues);
dbReq.updateChildren(childUpdates);
}
public Map<String, Object> toMap(RequestItem item)
{
HashMap<String, Object> result = new HashMap<>();
result.put("ProductName", item.getProductName());
result.put("SerialNo", item.getSerialNo());
result.put("Quantity", item.getQuantity());
result.put("Category",item.getCategory());
result.put("Model", item.getModel());
result.put("RequestBy", item.getRequestBy());
result.put("Status",item.getStatus());
result.put("Remarks",item.getRemarks());
return result;
}
}
You are using addListenerForSingleValueEvent() which will only listen for single value and then stop. You need to use addValueEventListener().
one way of doing this is you need to add elements in this ArrayList<RequestItem> list by making this as static in adapter class instead of the list in activity which you are passing to the adapter then you notifyDataSetChanged() function will work if you want to show changes in the list in real time
I suggest you to use the already built in library to make the list automatically updated when new data is pushed in firebase: check out this
If you want to stick with a custom implementation, define the adapter first in OnCreate callback and call adapter.notifyDataSetChanged() every time you updated your data.
If you want to insert/update/delete only one item inside your list call adapter.notifyItemChanged(position) from your adapter.
I strongly suggest you to switch to RecyclerView instead of ListView in Android (interesting comparison between them)

How to retrieve values from FireBase to JSONArray?

I got a source code of a food delivery app from git. he is parsing a website and displaying the menu items, I guess to see the
instead of this I have created a fire-base database and stored one food item for testing
I want to display my item from the fire-base to the app menu I will show the code of all food item fragment,
package com.example.guanzhuli.foody.HomePage.fragment;
public class AllTabFragment extends Fragment {
private String baseUrl = "http://rjtmobile.com/ansari/fos/fosapp/fos_food_loc.php?city=";
private String TAG = "ALLFOOD";
private StorageReference mStorageRef;
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference("menu");
ArrayList<Food> foods = new ArrayList<>();
private RecyclerView mRecyclerView;
private AllFoodAdapter adapter;
private RecyclerView.LayoutManager layoutManager;
String foodName;
public AllTabFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_all_tab, container, false);
mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
foodName = snapshot.child("name").getValue().toString();
String foodPrice = snapshot.child("prize").getValue().toString();
Toast.makeText(getActivity(), foodName, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
// Request Data From Web Service
if (foods.size() == 0) {
objRequestMethod();
}
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerview_all);
mRecyclerView.setHasFixedSize(false);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
adapter = new AllFoodAdapter(getActivity(), foods);
adapter.setOnItemClickListener(new AllFoodAdapter.OnRecyclerViewItemClickListener() {
#Override
public void onItemClick(View view, String data) {
Bundle itemInfo = new Bundle();
for (int i = 0; i < foods.size(); i++) {
if (foods.get(i).getId() == Integer.valueOf(data)) {
itemInfo.putInt("foodId", foods.get(i).getId());
itemInfo.putString("foodName", foods.get(i).getName());
// itemInfo.putString("foodName", foodName);
itemInfo.putString("foodCat", foods.get(i).getCategory());
itemInfo.putString("foodRec", foods.get(i).getRecepiee());
itemInfo.putDouble("foodPrice", foods.get(i).getPrice());
itemInfo.putString("foodImage", foods.get(i).getImageUrl());
break;
}
}
FoodDetailFragment foodDetailFragment = new FoodDetailFragment();
foodDetailFragment.setArguments(itemInfo);
getActivity().getSupportFragmentManager()
.beginTransaction()
.setCustomAnimations(R.anim.fade_in, R.anim.fade_out, R.anim.fade_in, R.anim.fade_out)
.replace(R.id.main_fragment_container, foodDetailFragment)
.addToBackStack(AllTabFragment.class.getName())
.commit();
}
});
mRecyclerView.setAdapter(adapter);
return view;
}
private void objRequestMethod() {
HomePageActivity.showPDialog();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET, buildUrl(), null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
Log.d(TAG, jsonObject.toString());
try {
JSONArray foodsJsonArr = jsonObject.getJSONArray("Food");
for (int i = 0; i < foodsJsonArr.length(); i++) {
JSONObject c = foodsJsonArr.getJSONObject(i);
String id = c.getString("FoodId");
String name = c.getString("FoodName");
String recepiee = c.getString("FoodRecepiee");
String price = c.getString("FoodPrice");
String category = c.getString("FoodCategory");
String thumb = c.getString("FoodThumb");
final Food curFood = new Food();
curFood.setCategory(category);
curFood.setName(name);
curFood.setRecepiee(recepiee);
curFood.setPrice(Double.valueOf(price));
curFood.setId(Integer.valueOf(id));
curFood.setImageUrl(thumb);
foods.add(curFood);
// Log.e("Current Food", curFood.getName());
ImageLoader imageLoader = VolleyController.getInstance().getImageLoader();
imageLoader.get(thumb, new ImageLoader.ImageListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Image Load Error: " + error.getMessage());
}
#Override
public void onResponse(ImageLoader.ImageContainer response, boolean arg1) {
if (response.getBitmap() != null) {
curFood.setImage(response.getBitmap());
// Log.e("SET IMAGE", curFood.getName());
adapter.notifyData(foods);
}
}
});
foods.get(i).setImage(curFood.getImage());
}
} catch (Exception e) {
System.out.println(e);
}
HomePageActivity.disPDialog();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
VolleyLog.d(TAG, "ERROR" + volleyError.getMessage());
Toast.makeText(getActivity(), volleyError.getMessage(),
Toast.LENGTH_SHORT).show();
HomePageActivity.disPDialog();
}
});
VolleyController.getInstance().addToRequestQueue(jsonObjReq);
}
private String buildUrl() {
return baseUrl + HomePageActivity.City;
}
}
I got food name from fire-base and stored in the string called "foodname" Now I want to display it in the menu, how can I do it?
if my question is wrong please forgive me, please help me
package com.example.guanzhuli.foody.HomePage.adapter;
public class AllFoodAdapter extends RecyclerView.Adapter<AllHolder> implements
View.OnClickListener {
private Context mContext;
ArrayList<Food> foods;
public String TAG = "ALLFOOD";
//
// public AllFoodAdapter(Context context) {
// mContext = context;
// }
public AllFoodAdapter(Context context, ArrayList<Food> foods) {
mContext = context;
this.foods = foods;
}
#Override
public AllHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.cardview_food, parent, false);
AllHolder allHolder = new AllHolder(v);
v.setOnClickListener(this);
return allHolder;
}
#Override
public void onBindViewHolder(AllHolder holder, int position) {
holder.mTextId.setText(String.valueOf(foods.get(position).getId()));
holder.mTextName.setText(foods.get(position).getName());
holder.mTextPrice.setText(String.valueOf(foods.get(position).getPrice()));
holder.mTextCategory.setText(foods.get(position).getCategory());
holder.mImageView.setImageBitmap(foods.get(position).getImage());
holder.itemView.setTag(foods.get(position).getId());
}
#Override
public int getItemCount() {
return foods.size();
}
public void notifyData(ArrayList<Food> foods) {
// Log.d("notifyData ", foods.size() + "");
this.foods = foods;
notifyDataSetChanged();
}
public static interface OnRecyclerViewItemClickListener {
void onItemClick(View view, String data);
}
private OnRecyclerViewItemClickListener mOnItemClickListener = null;
public void setOnItemClickListener(OnRecyclerViewItemClickListener listener) {
this.mOnItemClickListener = listener;
}
#Override
public void onClick(View view) {
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(view, String.valueOf(view.getTag()));
} else {
Log.e("CLICK", "ERROR");
}
}
}
class AllHolder extends RecyclerView.ViewHolder {
NetworkImageView mImage;
ImageView mImageView;
TextView mTextId, mTextName, mTextCategory, mTextPrice;
public AllHolder(View itemView) {
super(itemView);
// mImage = (NetworkImageView) itemView.findViewById(R.id.food_img);
mImageView = (ImageView) itemView.findViewById(R.id.food_img);
mTextId = (TextView) itemView.findViewById(R.id.food_id);
mTextName = (TextView) itemView.findViewById(R.id.food_name);
mTextPrice = (TextView) itemView.findViewById(R.id.food_price);
mTextId = (TextView) itemView.findViewById(R.id.food_id);
mTextCategory = (TextView) itemView.findViewById(R.id.food_category);
}
}
Please help me, because it is an important project for me
If you want to display the strings you have received from firebase in a new activity as a list, you can declare an ArrayList and then add those strings to it and then with an adapter set it to display.
In code it looks something like this:
private ArrayList array;
private ListView listView;
private FirebaseAuth mAuth = FirebaseAuth.getInstance();
private String curName;
//set them
listView = findViewById(R.id.list1);
array = new ArrayList<String>();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("menu");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
array.add(ds.child("name").getValue(String.class));
}
ArrayAdapter adapter = new ArrayAdapter(Main6Activity.this, android.R.layout.simple_list_item_1, array);
listView.setAdapter(adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
stackoverflow was not conceived to get complete code solutions. We can only help you on some point. Other than that, you need to think to use the Food class for read and write values on your db. When you retrive the values, get it as a Food object casting it by method dataSnapshot.getValue("object class");...
In your case you need a code like this:
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Food food = snapshot.getValue(Food.class);
//here you need to add the food object to a list and after the for diplay it with adapter.
//for example foodsList.add(food);
}
foodsList.setAdapter(myAdepter); //ecc
}
If you need help, please tell us more
You seem to be loading the food items from the database, and reading the values from them. All that's left to do, is add each item to the foods array, and tell the adapter that its data has changed:
mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
String foodName = snapshot.child("name").getValue(String.class);
String foodPrice = snapshot.child("prize").getValue(String.class);
Food food = new Food();
food.setName(name);
food.setPrice(Double.valueOf(price));
foods.add(food);
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});

Unable to display all images from firebase database and I want to show all images from one id into grid view

This is my firebase storage image and I want to display all images from url into gridview by taking the current user id
This is my main activity onstart() that leads to adapter class.
I want to show all the images under current user id like grid view.
How to display all user image posts in grid view from firebase above image.
#Override
protected void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
uploads = new ArrayList<Blog>();
if (currentUser != null && !currentUser.isAnonymous()) {
mUserf.child("online").setValue("true");
mProgressbar.setMessage("Welcome.....");
mProgressbar.show();
mProgressbar.dismiss();
ConnectivityManager check = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo info = check.getActiveNetworkInfo(); //for checking whether app is connected to a network or not..
if(info!=null && info.isConnected()) {
//Toast.makeText(MainActivity.this, "network available", Toast.LENGTH_SHORT).show();
firebaseAuth.addAuthStateListener(authStateListener);
mProgressbar.setMessage("Fetching Blogs.....");
mProgressbar.show();
mProgressbar.dismiss();
list = new ArrayList<>();
adapter = new MyCustomAdapter(this,list,firebaseAuth,mdatabaseReference,likesdatabaseReference);
recyclerView = (RecyclerView) findViewById(R.id.blog_list);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
alpha = FirebaseDatabase.getInstance().getReference().child("Blog").child(mAuth.getCurrentUser().getUid());
mchildEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
mProgressbar.dismiss();
String j = dataSnapshot.getKey();
Log.v("GETKEYZZZ", j);
Blog friendlyMessage = dataSnapshot.getValue(Blog.class);
friendlyMessage.setPostkey(j);
list.add(friendlyMessage);
adapter.notifyDataSetChanged();
}
public void onChildChanged(DataSnapshot dataSnapshot, String s) {}
public void onChildRemoved(DataSnapshot dataSnapshot){}
public void onChildMoved(DataSnapshot dataSnapshot, String s) {}
public void onCancelled(DatabaseError databaseError) {}
};
mquery.addChildEventListener(mchildEventListener);
} else {
//Toast.makeText(MainActivity.this, "No network available", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),"Please Check Your Internet Connection", Toast.LENGTH_LONG).show();
}
// mDatabseUsers.child("online").setValue("true");
} else {
Intent user1 = new Intent(MainActivity.this, LoginActivity.class);
startActivity(user1);
}
}
This is my adapter class where
public class MyCustomAdapter extends RecyclerView.Adapter<MyCustomAdapter.myviewholder> {
Context context;
ArrayList<Blog> list;
List <String> imageUrls;
//List<String> imageUrls ;
LayoutInflater inflator;
int lastPosition = 1;
boolean mprogressLike = true,mprogressview = true;
DatabaseReference likeDatabaseReference;
FirebaseAuth firebaseAuth;
DatabaseReference blogDatabaseReference;
public MyCustomAdapter(Context context, ArrayList<Blog> list,FirebaseAuth firebaseAuth,DatabaseReference blogDatabaseReference, DatabaseReference likeDatabaseReference) {
this.context=context;
this.list=list;
inflator=LayoutInflater.from(context);
this.likeDatabaseReference=likeDatabaseReference;
this.firebaseAuth=firebaseAuth;
this.blogDatabaseReference=blogDatabaseReference;
}
#Override
public myviewholder onCreateViewHolder(ViewGroup parent, int position) {
View v=inflator.inflate(R.layout.posts,parent,false);//this view will contain appearance of each layout i.e each row..
myviewholder holder=new myviewholder(v);// we are passing the view of each row to the myviewholder class
return holder;
}
#Override
public void onBindViewHolder(final myviewholder holder, int position) {//here we will inflate datas in the widgets i.e image and title..
//It is called for each row..so every row is inflated here..
final Blog p=list.get(position);
holder.title.setText(p.getTitle());
holder.username.setText(p.getUsername());
holder.viewno.setText(p.getTimestamp());
/*int count = 0;
for(HospitalModel.Images images: hospitalModelList.get(position).getImagesList()) {
count += images.size();
}*/
for(Blog model : list) {
imageUrls = new ArrayList<>();;
imageUrls.addAll(model.getUrl());
Log.v("IMURLSSS", String.valueOf(imageUrls));
Picasso.with(context).load(imageUrls.get(position)).into(holder.imageview);
Log.v("IMGGPOS", imageUrls.get(position));
}
Picasso.with(context).load(p.getImage()).into(holder.userdp);
}
#Override
public int getItemCount() {
return list.size();
}
public class myviewholder extends RecyclerView.ViewHolder implements View.OnClickListener {
// It contains the elements in each row that we will inflate in the recyclerView..
TextView title,desc,username,likeno,viewno;
ImageView imageview,userdp, over, comments, likes;
ImageButton likebtn,viewbtn;
public myviewholder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.blog_desc);//here we link with the elements of each view i.e each row and
// desc = (TextView) itemView.findViewById(R.id.postdesc);//here we link with the elements of each view i.e each row and
username = (TextView) itemView.findViewById(R.id.blog_user_name);
viewno = (TextView) itemView.findViewById(R.id.blog_date);
likeno = (TextView) itemView.findViewById(R.id.blog_like_count);
userdp = (ImageView) itemView.findViewById(R.id.blog_user_image);
imageview = (ImageView) itemView.findViewById(R.id.blog_image);
comments = (ImageView) itemView.findViewById(R.id.blog_comment_icon);
//here we link with the elements of each view i.e each row and
// likebtn = (ImageButton)itemView.findViewById(R.id.likebtn);
// viewbtn = (ImageButton)itemView.findViewById(R.id.viewbtn);
comments.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mprogressview = true;
int pos = getAdapterPosition();
Blog b = list.get(pos);
Intent intent = new Intent(context,CommentBox.class);
Bundle bundle = new Bundle();
bundle.putString("post_key",b.getUid().toString());
intent.putExtras(bundle);
context.startActivity(intent);
}
});
over = (ImageView) itemView.findViewById(R.id.overflow);
over.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showFilterPopup(v);
}
});
});
itemView.setOnClickListener(this);
}
}
To display all those url's, please use the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference urlRef = rootRef.child("Blog").child(uid).child("url");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String url = ds.getValue(String.class);
Log.d("TAG", url);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
urlRef.addListenerForSingleValueEvent(valueEventListener);
And here is a recommended way in which you can retrieve data from a Firebase Realtime database and display it in a RecyclerView using FirebaseRecyclerAdapter.
Edit:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("Blog").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String uid = dataSnapshot.child("uid").getValue(String.class);
String title = dataSnapshot.child("title").getValue(String.class);
String timestamp = dataSnapshot.child("timestamp").getValue(String.class);
Log.d("TAG", uid + " / " + title + " / " + timestamp);
for(DataSnapshot ds : dataSnapshot.child("url").getChildren()) {
String url = ds.getValue(String.class);
Log.d("TAG", url);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);

Sorting FirebaseRecyclerAdapter on Client Side

I want to sort FirebaseRecyclerAdapter on the TIME BASIS. I'm working on That Application so whenever new Message comes then That Dialog goes on The Top of the Layout, it also contain time of Sending the Message so The message which is new Then that should be in The Top of the Recyclerview. So So How Can i sort The FirebaseRecyclerAdapter on the Time Basis
Here is me Code
madapter = new FirebaseRecyclerAdapter<user, contact.UserViewHolder>(user.class, R.layout.activity_dialogs_list, contact.UserViewHolder.class, muserref) {
#Override
protected void populateViewHolder(final UserViewHolder viewHolder, user model, final int position) {
final String ais = model.getName();
viewHolder.setName(model.getName());
final String b = model.groupId;
//Toast.makeText(contact.this,viewHolder.getLayoutPosition(),LENGTH_SHORT).show();
mref = FirebaseDatabase.getInstance().getReference().child("LastMessage").child(b);
mref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapShot : dataSnapshot.getChildren()) {
val=lmlm;
HashMap<String, Object> hashmap = (HashMap) dataSnapshot.getValue();
val = (String) hashmap.get("lastm");
Long role = (Long) hashmap.get("timestampCreated");
String lastsender = (String) hashmap.get("LastmessageSender");
getTimeago getTimeAgo = new getTimeago();
String lastSeenTime = getTimeAgo.getTimeAgo(role);
//SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy HH:mm:ss");
//String dateAsString = sdf.format (role);
//change(position);
// swape(viewHolder.getAdapterPosition());
if (val.length() > 40) {
String nawa = val.substring(0, 40);
viewHolder.setLastmessage((nawa + "..."));
viewHolder.setLastTime(lastSeenTime);
} else {
viewHolder.setLastmessage(val);
viewHolder.setLastTime(lastSeenTime);
}
//viewHolder.setLastmessage(val);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mimage = FirebaseDatabase.getInstance().getReference().child("Image").child(b);
mimage.keepSynced(true);
mimage.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapShot : dataSnapshot.getChildren()) {
HashMap<String, Object> hashmap = (HashMap) dataSnapshot.getValue();
final String vala = (String) hashmap.get("image");
viewHolder.setImage(vala, getApplicationContext());
/// //viewHolder.setImage(val,getApplicationContext());
//viewHolder.setImage(vala);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(contact.this,"Something Went wrong",LENGTH_SHORT).show();
}
});
}
});
}
};
mUserlist.setAdapter(madapter);
madapter.notifyDataSetChanged();
And Here is My Holder
`
public static class UserViewHolder extends RecyclerView.ViewHolder {
View mview;
ImageLoader imageLoader;
public UserViewHolder(View itemView) {
super(itemView);
mview = itemView;
}
public void setName(String name) {
TextView username = (TextView) mview.findViewById(R.id.dialogName);
username.setText(name);
}
public void setLastmessage(String lastmessage) {
TextView set = (TextView) mview.findViewById(R.id.dialogLastMessage);
set.setText(lastmessage);
}
public void setLastTime(String lastTime) {
TextView time = (TextView) mview.findViewById(R.id.dialogDate);
time.setText(lastTime);
}
public void setImage(final String vala, final Context applicationContext) {
final CircleImageView cm = (CircleImageView) mview.findViewById(R.id.dialogAvatar);
Picasso.with(applicationContext).load(vala).networkPolicy(NetworkPolicy.OFFLINE).into(cm, new Callback() {
#Override
public void onSuccess() {
Picasso.with(applicationContext).load(vala).into(cm);
}
#Override
public void onError() {
Picasso.with(applicationContext).load(vala).into(cm);
}
});
}
`
So if new Message comes in SE Comps then that Dialog Show goes on The Top of RecyclerViewSo How can i get that please Help
Did you try orderByChild function to sort firebase list data?
ref.orderByChild('< time_key >')
OrderByChild will work with ChildEventListner
check this link

Categories

Resources