How to disable auto update on scroll of a recyclerview? - android

I am building an Ecommerce app where I need to select the quanitity on the recycleview for each items. And scrolling down after selecting the upward items , the recyclerview refreshes and put the the value 0 again.
I need a very quick solution to that as I'm hanged in an ongoing project.
public void readOrders()
{
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReferenceFromUrl("https://kharkhowa-3b20d.firebaseio.com/items");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
list.clear();
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
ItemClass itemClass = dataSnapshot1.getValue(ItemClass.class);
assert itemClass != null;
assert firebaseUser != null;
list.add(itemClass);
}
Log.i("sizeeeeeeeeeeeee", String.valueOf(list));
itemAdapter = new ItemAdapter(getApplicationContext(), list);
recyclerView.setAdapter(itemAdapter);
recyclerView.addItemDecoration(new DividerItemDecoration(recyclerView.getContext(), DividerItemDecoration.VERTICAL));
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
Adapter Class
public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ViewHolder>{
HashMap<String, List<String>> hm = new HashMap();
Context context;
private List<ItemClass> list ;
int n, total = 0;
public ItemAdapter(Context context, List<ItemClass> list) {
this.context = context;
this.list = list;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.items,parent,false);
return new ItemAdapter.ViewHolder(view);
}
#SuppressLint("RestrictedApi")
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, int position) {
// int n = 0;
String s = "";
final ItemClass itemClass = list.get(position);
holder.itemName.setText(itemClass.getItemName());
final String price = itemClass.getItemPrice();
s = String.valueOf(n);
holder.noOfitem.setText(s);
holder.plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String n1 = (String) holder.noOfitem.getText();
int i = Integer.parseInt(n1);
i = i + 1;
String s1 = String.valueOf(i);
holder.noOfitem.setText(s1);
//n++;
String ab = (String) holder.noOfitem.getText();
int b = Integer.parseInt(ab);
List<String> list = new ArrayList();
list.add(price);
list.add(ab);
hm.put(itemClass.getItemName(), list);
Log.i("hashhhhhhhhhh", hm.toString());
if (b == 1) {
total = total + 1;
Intent intent = new Intent("custom-message");
intent.putExtra("total", String.valueOf(total));
intent.putExtra("hashmap", hm);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
}
});
holder.minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String n1 = (String) holder.noOfitem.getText();
int i = Integer.parseInt(n1);
if (i > 0) {
i = i - 1;
String s1 = String.valueOf(i);
holder.noOfitem.setText(s1);
String ab = (String) holder.noOfitem.getText();
int b = Integer.parseInt(ab);
List<String> list = new ArrayList();
list.add(price);
list.add(ab);
hm.put(itemClass.getItemName(), list);
Log.i("hashhhhhhhhhh", hm.toString());
if (b == 0) {
total = total - 1;
Intent intent = new Intent("custom-message");
intent.putExtra("total", String.valueOf(total));
intent.putExtra("hashmap", hm);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
// n--;
}
}
});
}
#Override
public int getItemCount() {
return list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder
{
public TextView itemName,noOfitem,cartnext;
public ImageView minus,plus;
public ViewHolder(View itemView) {
super(itemView);
itemName = (TextView)itemView.findViewById(R.id.itemname);
noOfitem = (TextView)itemView.findViewById(R.id.noOfitem);
minus = (ImageView)itemView.findViewById(R.id.minus);
plus = (ImageView)itemView.findViewById(R.id.plus);
}
}
}

get getItemCount() then it returns actual count
getItemCount()
keep size recycleview in variable in the bigining

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.

How to retrieve data from fire-base into a new activity On-click RecyclerView

It's an app that retrieves book data from firebase, I want to know how to retrieve specific data into a new activity. Like, retrieve specific book data on click RecyclerView. I am able to get the onclick position on the RecyclerView but I don't know how to use that with firebase
Here is my code:
public class SearchPage extends AppCompatActivity {
EditText searchbar;
RecyclerView recyclerView;
DatabaseReference reference;
ArrayList <String> BookNameList;
ArrayList <String> AuthorNameList;
ArrayList <String> PicList;
ArrayList <String> PublisherList;
ArrayList <String> Shelfnols;
ArrayList <String> Desc;
SearchAdapter searchAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_page);
searchbar = (EditText) findViewById(R.id.searchbar);
reference = FirebaseDatabase.getInstance().getReference();
reference.keepSynced(true);
recyclerView = (RecyclerView) findViewById(R.id.rv);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
BookNameList = new ArrayList <> ();
PublisherList = new ArrayList <> ();
AuthorNameList = new ArrayList <> ();
Shelfnols = new ArrayList <> ();
PicList = new ArrayList <> ();
Desc = new ArrayList <> ();
final ArrayList <String> uidlist = new ArrayList <String> ();
searchbar.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
if (!s.toString().isEmpty()) {
setAdapter(s.toString());
} else {
BookNameList.clear();
AuthorNameList.clear();
PicList.clear();
PublisherList.clear();
Shelfnols.clear();
Desc.clear();
uidlist.clear();
}
}
private void setAdapter(final String searchedString) {
reference.child("books").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
BookNameList.clear();
AuthorNameList.clear();
PicList.clear();
PublisherList.clear();
Shelfnols.clear();
Desc.clear();
uidlist.clear();
int counter = 0;
for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
String uid = snapshot.getKey();
String desc = snapshot.child("Desc").getValue(String.class);
String bookname = snapshot.child("bookname").getValue(String.class);
String author = snapshot.child("author").getValue(String.class);
String image = snapshot.child("image").getValue(String.class);
String publisher = snapshot.child("Publisher").getValue(String.class);
String shelfno = snapshot.child("Shelf_no").getValue(String.class);
try {
if (bookname.toLowerCase().contains(searchedString.toLowerCase())) {
BookNameList.add(bookname);
AuthorNameList.add(author);
PublisherList.add(publisher);
Shelfnols.add(shelfno);
PicList.add(image);
Desc.add(desc);
counter++;
} else if (author.toLowerCase().contains(searchedString.toLowerCase())) {
BookNameList.add(bookname);
AuthorNameList.add(author);
PublisherList.add(publisher);
Shelfnols.add(shelfno);
PicList.add(image);
Desc.add(desc);
counter++;
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "not found", Toast.LENGTH_LONG).show();
}
if (counter == 15) {
break;
}
SearchAdapter searchAdapter = new SearchAdapter(SearchPage.this, BookNameList, AuthorNameList, PicList, PublisherList, Shelfnols);
recyclerView.setAdapter(searchAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
});
}
This is my adapter class
public class SearchAdapter extends RecyclerView.Adapter<SearchAdapter.SearchViewHolder> {
public static final String id="key";
Context context;
ArrayList<String> BookNameList;
ArrayList<String> AuthorNameList;
ArrayList<String> PicList;
ArrayList<String> PublisherList;
ArrayList<String> Shelfnols;
LinearLayout booklayout;
class SearchViewHolder extends RecyclerView.ViewHolder{
ImageView bookimage;
TextView bookname, authorname,publisher,shelfno;
public SearchViewHolder(#NonNull View itemView) {
super(itemView);
bookimage = itemView.findViewById(R.id.Bookimg);
bookname = itemView.findViewById(R.id.BookName);
authorname = itemView.findViewById(R.id.AuthorName);
publisher = itemView.findViewById(R.id.Publications);
shelfno = itemView.findViewById(R.id.Shelfno);
booklayout=itemView.findViewById(R.id.LinLayout);
}
}
public SearchAdapter(Context context, ArrayList<String> bookNameList, ArrayList<String> authorNameList, ArrayList<String> picList,ArrayList<String> publisherList,ArrayList<String> shelfnols) {
this.context = context;
BookNameList = bookNameList;
AuthorNameList = authorNameList;
PicList = picList;
PublisherList=publisherList;
Shelfnols=shelfnols;
}
#NonNull
#Override
public SearchAdapter.SearchViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.activity_search_layout,parent,false);
return new SearchAdapter.SearchViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull SearchViewHolder holder, final int position) {
holder.bookname.setText(BookNameList.get(position));
holder.authorname.setText(AuthorNameList.get(position));
holder.publisher.setText(PublisherList.get(position));
holder.shelfno.setText(Shelfnols.get(position));
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String t=String.valueOf(position);
Toast.makeText(v.getContext(), "Item is clicked" + t, Toast.LENGTH_SHORT).show();
}
});
booklayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
this the new activity where i want the book details to be shown
public class Bookdetailslayout extends SearchPage {
DatabaseReference reference;
TextView bookname,author,publisher,desc,location;
ImageView image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bookdetailslayout);
bookname = (TextView)findViewById(R.id.bkname);
author = (TextView) findViewById(R.id.aname);
publisher = (TextView) findViewById(R.id.pname);
desc = (TextView) findViewById(R.id.bkdescription);
location = (TextView) findViewById(R.id.bklocation);
String s = getIntent().getStringExtra("key");
DatabaseReference databaseReference=FirebaseDatabase.getInstance().getReference().child("books");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Bookdeets bookdeets=dataSnapshot.getValue(Bookdeets.class);
bookname.setText(bookdeets.getBookname());
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
Glide.with(context).asBitmap().load(PicList.get(position)).placeholder(R.mipmap.ic_launcher_round).into(holder.bookimage);
}
#Override
public int getItemCount() {
return BookNameList.size();
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(context,BookdetailsActivity.class);
i.putExtra("bookname",bookname);
context.startActivity(i);
}
});
above code start new activity for showing details on new activity at the same time pass unique key for retrieving data from firebase.
inside BookDetailsActivity
get key value by using
String name = getIntent().getStringExtra("bookname");
then do your stuff for getting data from firebase.

My data of recyclerview loss in scroll down

I have a recyclerview and set text some textview in it. when I scroll down or my fragment goes to onPause state my data loss.
what can i do?
import static com.test.mohammaddvi.snappfood.Adapter.SectionListDataAdapter.decodeSampledBitmapFromResource;
public class RecyclerViewMenuFragmentAdapter extends RecyclerView.Adapter<RecyclerViewMenuFragmentAdapter.SingleItemInMenuFragment> {
private ArrayList<Food> foodList;
private Context mContext;
public RecyclerViewMenuFragmentAdapter(ArrayList<Food> foodList, Context mContext) {
this.foodList = foodList;
this.mContext = mContext;
}
#NonNull
#Override
public RecyclerViewMenuFragmentAdapter.SingleItemInMenuFragment onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.foodlist, null);
return new RecyclerViewMenuFragmentAdapter.SingleItemInMenuFragment(v);
}
#Override
public void onBindViewHolder(final RecyclerViewMenuFragmentAdapter.SingleItemInMenuFragment holder, int position) {
Food food = foodList.get(position);
holder.foodName.setText(food.getName());
holder.foodDetails.setText(food.getDetails());
holder.foodPrice.setText(food.getPrice() + " تومان ");
holder.foodOrderNumber.setVisibility(View.INVISIBLE);
holder.foodMinusButton.setVisibility(View.INVISIBLE);
holder.foodOrderNumber.setText(0 + "");
holder.foodImage.setImageBitmap(decodeSampledBitmapFromResource(mContext.getResources(), mContext.getResources().getIdentifier(food.getImage(),
"drawable", mContext.getPackageName()), 50, 50));
handleClick(holder, position);
}
private void handleClick(final SingleItemInMenuFragment holder, final int position) {
holder.foodPlusButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int orderNumber = Integer.parseInt(holder.foodOrderNumber.getText().toString());
holder.foodOrderNumber.setText(orderNumber + 1 + "");
holder.foodOrderNumber.setVisibility(View.VISIBLE);
holder.foodMinusButton.setVisibility(View.VISIBLE);
}
});
holder.foodMinusButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int orderNumber = Integer.parseInt(holder.foodOrderNumber.getText().toString());
if (orderNumber > 1) {
holder.foodOrderNumber.setText(orderNumber - 1 + "");
holder.foodOrderNumber.setVisibility(View.VISIBLE);
}
if (orderNumber == 1) {
holder.foodOrderNumber.setText(orderNumber - 1 + "");
holder.foodOrderNumber.setVisibility(View.INVISIBLE);
holder.foodMinusButton.setVisibility(View.INVISIBLE);
}
}
});
}
#Override
public int getItemCount() {
return (null != foodList ? foodList.size() : 0);
}
public class SingleItemInMenuFragment extends RecyclerView.ViewHolder {
TextView foodName;
TextView foodPrice;
Button foodPlusButton;
Button foodMinusButton;
TextView foodOrderNumber;
ImageView foodImage;
TextView foodDetails;
SingleItemInMenuFragment(View itemView) {
super(itemView);
this.foodName = itemView.findViewById(R.id.foodName);
this.foodImage = itemView.findViewById(R.id.imageFood);
this.foodPrice = itemView.findViewById(R.id.foodPrice);
this.foodDetails = itemView.findViewById(R.id.foodDetails);
this.foodPlusButton = itemView.findViewById(R.id.plusbutton);
this.foodMinusButton = itemView.findViewById(R.id.minusbutton);
this.foodOrderNumber = itemView.findViewById(R.id.ordernumber);
}
}
}
and this is my fragment that i use recyclerview in that:
public class MenuFragment extends Fragment{
private static final String TAG = "menufragment";
ArrayList<Food> allfoods = new ArrayList<>();
RecyclerView recyclerview;
private static Bundle bundle;
private final String KEY_RECYCLER_STATE= "recycler_state";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.menufragment, container, false);
}
#Override
public void onStart() {
super.onStart();
String jsonFilePath = "foods.json";
recyclerview = getActivity().findViewById(R.id.lstitems);
RecyclerViewMenuFragmentAdapter adapter = new RecyclerViewMenuFragmentAdapter(allfoods, getContext());
recyclerview.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
recyclerview.setHasFixedSize(true);
recyclerview.setAdapter(adapter);
parsJson(jsonFilePath);
}
//this method is for read a local json and return a string
public String readLocalJson(String jsonFile) {
String json;
try {
InputStream is = getActivity().getAssets().open(jsonFile);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
return null;
}
return json;
}
public void parsJson(String jsonFilePath) {
try {
JSONObject obj = new JSONObject(readLocalJson(jsonFilePath));
JSONArray jsonArray = obj.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String image = jsonObject.getString("image");
JSONArray jsonArrayFoot = jsonObject.getJSONArray("foots");
for (int j = 0; j < jsonArrayFoot.length(); j++) {
JSONObject jsonObjectFoot = jsonArrayFoot.getJSONObject(j);
String foodName = jsonObjectFoot.getString("name");
String fooddetails = jsonObjectFoot.getString("fooddetails");
String price = jsonObjectFoot.getString("price");
allfoods.add(new Food(foodName, price, fooddetails, image));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Basically, you just initialized the data on onStart which will eventually called when your activity/fragment is resumed, and because of that all data you've changed was overwritten to initial data.
Move your onStart initialization to onViewCreated:
#Override
public void onViewCreated() {
super.onViewCreated();
String jsonFilePath = "foods.json";
recyclerview = getActivity().findViewById(R.id.lstitems);
RecyclerViewMenuFragmentAdapter adapter = new RecyclerViewMenuFragmentAdapter(allfoods, getContext());
recyclerview.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
recyclerview.setHasFixedSize(true);
recyclerview.setAdapter(adapter);
parsJson(jsonFilePath);
}
And for scrolling, its normal because RecyclerView recycles the view from the list above but the data is not, so what you need to do is store values from the list source.
#Override
public void onBindViewHolder(final RecyclerViewMenuFragmentAdapter.SingleItemInMenuFragment holder, int position) {
Food food = foodList.get(position);
holder.foodName.setText(food.getName());
holder.foodDetails.setText(food.getDetails());
holder.foodPrice.setText(food.getPrice() + " تومان ");
holder.foodOrderNumber.setVisibility(View.INVISIBLE);
holder.foodMinusButton.setVisibility(View.INVISIBLE);
holder.foodOrderNumber.setText(food.getFoodOrderNumber());
holder.foodImage.setImageBitmap(decodeSampledBitmapFromResource(mContext.getResources(), mContext.getResources().getIdentifier(food.getImage(),
"drawable", mContext.getPackageName()), 50, 50));
handleClick(holder, position);
}
private void handleClick(final SingleItemInMenuFragment holder, final int position) {
holder.foodPlusButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int orderNumber = Integer.parseInt(holder.foodOrderNumber.getText().toString());
int newOrderNumber = orderNumber + 1;
Food food = foodList.get(position);
food.setFoodOrderNumber(newOrderNumber);
holder.foodOrderNumber.setText(newOrderNumber + "");
holder.foodOrderNumber.setVisibility(View.VISIBLE);
holder.foodMinusButton.setVisibility(View.VISIBLE);
}
});
holder.foodMinusButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Food food = foodList.get(position);
int orderNumber = food.getFoodOrderNumber();
if (orderNumber > 1) {
int newOrderNumber = orderNumber - 1;
food.setFoodOrderNumber(newOrderNumber);
holder.foodOrderNumber.setText(newOrderNumber + "");
holder.foodOrderNumber.setVisibility(View.VISIBLE);
}
if (orderNumber == 1) {
int newOrderNumber = orderNumber - 1;
food.setFoodOrderNumber(newOrderNumber);
holder.foodOrderNumber.setText(newOrderNumber + "");
holder.foodOrderNumber.setVisibility(View.INVISIBLE);
holder.foodMinusButton.setVisibility(View.INVISIBLE);
}
}
});
}
And on your Food object just add this field and functions:
public class Food {
int foodOrderNumber;
public int getFoodOrderNumber() {
return foodOrderNumber;
}
public void setFoodOrderNumber(int foodOrderNumber) {
this.foodOrderNumber = foodOrderNumber;
}
}
add this line to your onBindViewHolder method and check again if the problem still exits:
holder.setIsRecyclable(false);

RecyclerView Adapter notify data changed

There is my activity:
public class EventDetailsActivity extends AppCompatActivity {
private Event event;
private ArrayList<User> subscribedUsers;
private RecyclerView mRecyclerView;
private String eventId;
private SubscribedUsersAdapter adapter;
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_details);
context = this;
Bundle extras = getIntent().getExtras();
eventId = extras.getString("eventId");
setUpEvent();
}
private void setUpEvent() {
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
final DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference().child("events").child(eventId);
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String eventType = dataSnapshot.child("eventType").getValue().toString();
String description = dataSnapshot.child("description").getValue().toString();
Object object = dataSnapshot.child("startingDate").getValue();
HashMap result = (HashMap) object;
int year = Integer.parseInt(result.get("year").toString());
int month = Integer.parseInt(result.get("month").toString());
int day = Integer.parseInt(result.get("date").toString());
int hour = Integer.parseInt(result.get("hours").toString());
int minute = Integer.parseInt(result.get("minutes").toString());
Date startingDate = new Date(year,month,day,hour,minute,0);
object = dataSnapshot.child("location").getValue();
result = (HashMap) object;
double latitude = Double.parseDouble(result.get("latitude").toString());
double longitude = Double.parseDouble(result.get("longitude").toString());
LatLng location = new LatLng(latitude,longitude);
String userId = dataSnapshot.child("userId").getValue().toString();
String userName = dataSnapshot.child("userName").getValue().toString();
String userPicture = dataSnapshot.child("userPicture").getValue().toString();
subscribedUsers = new ArrayList<User>();
if (dataSnapshot.hasChild("subscribedUsers")) {
mDatabase.child("subscribedUsers").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
String userId = childSnapshot.child("userId").getValue().toString();
String name = childSnapshot.child("name").getValue().toString();
String picture = childSnapshot.child("picture").getValue().toString();
User subscribedUser = new User(userId, name, picture);
if (containsUser(subscribedUsers, subscribedUser) == -1) {
subscribedUsers.add(subscribedUser);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
event = new Event(eventId, eventType,description,startingDate,location,userId, userName, userPicture);
setText();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void setText()
{
ImageView mProfilePicture = (ImageView) findViewById(R.id.profilePicture);
if (!EventDetailsActivity.this.isFinishing()) {
Glide
.with(this)
.load(event.getUserPicture())
.into(mProfilePicture);
}
TextView mUserName = (TextView) findViewById(R.id.userName);
mUserName.setText(event.getUserName());
TextView mEventType = (TextView) findViewById(R.id.eventType);
mEventType.setText(event.getEventType());
TextView mDescription = (TextView) findViewById(R.id.description);
mDescription.setText(event.getDescription());
if (!EventDetailsActivity.this.isFinishing()) {
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.mapView);
mapFragment.getMapAsync(new OnMapReadyCallback()
{
#Override
public void onMapReady(GoogleMap googleMap) {
googleMap.clear();
googleMap.addMarker(new MarkerOptions().position(event.getLocation()));
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(event.getLocation(),12.0f));
}
});
}
TextView mStartingDate = (TextView) findViewById(R.id.startingDate);
Date startingDate = event.getStartingDate();
String displayText = String.valueOf(startingDate.getYear());
int month = startingDate.getMonth() + 1;
if (month/10 == 0)
{
displayText = displayText + ".0" + month;
}
else
{
displayText = displayText + "." + month;
}
if (startingDate.getDate()/10 == 0)
{
displayText = displayText + ".0" + startingDate.getDate();
}
else
{
displayText = displayText + "." + startingDate.getDate();
}
if (startingDate.getHours()/10 == 0)
{
displayText = displayText + ". 0" + startingDate.getHours();
}
else
{
displayText = displayText + ". " + startingDate.getHours();
}
if (startingDate.getMinutes()/10 == 0)
{
displayText = displayText + ":0" + startingDate.getMinutes();
}
else
{
displayText = displayText + ":" + startingDate.getMinutes();
}
mStartingDate.setText(displayText);
setUpRecyclerView();
subscribe();
}
private void setUpRecyclerView() {
adapter = new SubscribedUsersAdapter(this,subscribedUsers);
mRecyclerView.setAdapter(adapter);
}
private void subscribe()
{
FirebaseAuth mAuth = FirebaseAuth.getInstance();
if (mAuth.getCurrentUser() != null) {
final String userId = mAuth.getCurrentUser().getUid();
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference().child("users").child(userId);
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String userName = dataSnapshot.child("name").getValue().toString();
String userPicture = dataSnapshot.child("picture").getValue().toString();
User user = new User(userId, userName, userPicture);
userSubscribe(user);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
else
{
userSubscribe(null);
}
}
private void userSubscribe(final User user) {
Button mSubscribeButton = (Button) findViewById(R.id.subscribeButton);
if (user == null)
{
mSubscribeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(EventDetailsActivity.this, getResources().getString(R.string.logInToSubscribe), Toast.LENGTH_LONG).show();
Intent loginIntent = new Intent(EventDetailsActivity.this, LoginActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(loginIntent);
}
});
}
else if (containsUser(subscribedUsers,user) == -1)
{
mSubscribeButton.setText(getResources().getString(R.string.subscribe));
mSubscribeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference().child("events").child(event.getEventId());
subscribedUsers.add(user);
mDatabase.child("subscribedUsers").setValue(subscribedUsers);
}
});
}
else
{
mSubscribeButton.setText(getResources().getString(R.string.unsubscribe));
mSubscribeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference().child("events").child(event.getEventId());
int position = containsUser(subscribedUsers,user);
subscribedUsers.remove(position);
mDatabase.child("subscribedUsers").removeValue();
mDatabase.child("subscribedUsers").setValue(subscribedUsers);
}
});
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
this.finish();
}
private int containsUser(ArrayList<User> users, User user)
{
for (int i=0; i<users.size(); ++i)
{
if (users.get(i).getUserId().equals(user.getUserId()))
{
return i;
}
}
return -1;
}
}
And my adapter:
public class SubscribedUsersAdapter extends RecyclerView.Adapter<SubscribedUsersAdapter.ViewHolder>{
private Context context;
private ArrayList<User> items;
public SubscribedUsersAdapter(Context context, ArrayList<User> items) {
this.context = context;
this.items = items;
}
protected static class ViewHolder extends RecyclerView.ViewHolder {
public ImageView mProfilePictureView;
public TextView mUserName;
public ViewHolder(View itemView) {
super(itemView);
mProfilePictureView = (ImageView) itemView.findViewById(R.id.profilePictureView);
mUserName = (TextView) itemView.findViewById(R.id.userName);
}
}
#Override
public SubscribedUsersAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_user, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final User item = items.get(position);
Glide
.with(context)
.load(item.getPicture())
.into(holder.mProfilePictureView);
holder.mUserName.setText(item.getName());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent profileIntent = new Intent(context, ProfileActivity.class);
profileIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
profileIntent.putExtra("userId", item.getUserId());
context.startActivity(profileIntent);
}
});
}
#Override
public int getItemCount() {
return items.size();
}
}
When the activity starts firstly, the data is displayed well in RecyclerView, but if a user subscribes to the event or unsubscribe from it, the RecyclerView will be empty.
I tried with notifyDataSetChanged, notifyItemRangeInserted, notifyItemRangeRemoved, but none of them worked or I didn't use it well. I don't know.
Thanks for your help!
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
String userId = childSnapshot.child("userId").getValue().toString();
String name = childSnapshot.child("name").getValue().toString();
String picture = childSnapshot.child("picture").getValue().toString();
User subscribedUser = new User(userId, name, picture);
if (containsUser(subscribedUsers, subscribedUser) == -1) {
subscribedUsers.add(subscribedUser);
}
}
after that just add this line
adapter.notifyDataSetChanged();

Android - Firebase on data change refreshes the page

I'm kinda newbie to Android.
I have a recyclerview that I store in Firebase database.
My recyclerview are made of cardviews.
Inside each cardview I have a button that updates the node info in Firebase.
Each time the above is happening, my page refreshes (I guess to load the new data).
My mainactivity code relevant code(called on onCreate) :
private void loadRecyclerViewData() {
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (posts.size() > 0) {
posts.clear();
}
for (DataSnapshot ds : dataSnapshot.getChildren()) {
Post post = ds.getValue(Post.class);
//Getting a specific user's information (nickname purposes)
if (post.getSubGenreType().equals(SubGenreString)) {
posts.add(post);
Collections.reverse(posts);
}
}
adapter = new RecyclerAdapter(posts, getApplicationContext());
recyclerView.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
my adapter :
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
public static Boolean isAyed = false;
private FirebaseAuth firebaseAuth;
private List<Post> posts;
private Context context;
private String userTryToAyeEmail;
public RecyclerAdapter(List<Post> posts, Context context) {
this.posts = posts;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
firebaseAuth = FirebaseAuth.getInstance();
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.recycle_card, parent, false);
return new ViewHolder(v);
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final Post post = posts.get(position);
holder.imageButton.setVisibility(View.GONE);
holder.editText.setVisibility(View.GONE);
String colorString = post.getPostColor();
int color = Color.parseColor(colorString);
int newNumOfLikes = post.getPostLikes();
int currentNumOfLikes = post.getPostLikes();
// holder.cardView.setCardBackgroundColor(color);
holder.textViewHead.setText(post.getPostContent());
holder.textViewNickname.setText(post.getPostNickname());
holder.textViewTimeStamp.setText(post.getPostTimeStamp());
holder.ayeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Boolean userLiked = false;
if (firebaseAuth.getCurrentUser() != null) {
String currentUserEmail = firebaseAuth.getCurrentUser().getEmail();
List<String> currentLikedPost = post.getUserLikedList();
for (int i = 0; i < currentLikedPost.size(); i++) {
if (currentUserEmail.equals(currentLikedPost.get(i))) {
currentLikedPost.remove(i);
int newNumOfLikes = post.getPostLikes() - 1;
updateLikes(post.getId(), newNumOfLikes, post.getPostNickname(), post.getPostTimeStamp(), post.getPostContent(), post.getPostColor(), post.getSubGenreType(), post.getUserLikedList());
userLiked = true;
break;
}
}
if (!userLiked) {
currentLikedPost.add(currentUserEmail);
int newNumOfLikes = post.getPostLikes() + 1;
updateLikes(post.getId(), newNumOfLikes, post.getPostNickname(), post.getPostTimeStamp(), post.getPostContent(), post.getPostColor(), post.getSubGenreType(), post.getUserLikedList());
}
}
}
});
if (firebaseAuth.getCurrentUser() != null) {
String currentUserEmail = firebaseAuth.getCurrentUser().getEmail();
List<String> usersLikedPost = post.getUserLikedList();
for (int i = 0; i < usersLikedPost.size(); i++) {
if (currentUserEmail.equals(usersLikedPost.get(i))) {
holder.ayeButton.setTextColor(Color.parseColor("#FF0000"));
break;
}
}
}
holder.ayeTextView.setText(Integer.toString(newNumOfLikes));
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent myIntent = new Intent(context, SinglePostActivity.class);
myIntent.putExtra("postID", post.getId());
myIntent.putExtra("postNickname", post.getPostNickname());
myIntent.putExtra("postTimeStamp", post.getPostTimeStamp());
myIntent.putExtra("postContent", post.getPostContent());
myIntent.putExtra("postColor", post.getPostColor());
context.startActivity(myIntent);
}
});
}
private void updateLikes(String id, int newNumOfLikes, String postNickname, String postTimeStamp, String postContent, String postColor, String SubGenre, List<String> userLikedPostList) {
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("posts").child(id);
Post post = new Post(postColor, postContent, postNickname, postTimeStamp, id, newNumOfLikes, SubGenre, userLikedPostList);
databaseReference.setValue(post);
}
#Override
public int getItemCount() {
return posts.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView textViewHead;
public TextView textViewNickname;
public TextView textViewTimeStamp;
public TextView ayeButton;
public TextView ayeTextView;
public CardView cardView;
public LinearLayout linearLayout;
public EditText editText;
public ImageButton imageButton;
public ViewHolder(View itemView) {
super(itemView);
textViewHead = (TextView) itemView.findViewById(R.id.textViewHead);
textViewNickname = (TextView) itemView.findViewById(R.id.textViewNickname);
textViewTimeStamp = (TextView) itemView.findViewById(R.id.textViewTimeStamp);
ayeButton = (TextView) itemView.findViewById(R.id.ayeButton);
ayeTextView = (TextView) itemView.findViewById(R.id.ayeTextView);
cardView = (CardView) itemView.findViewById(R.id.cardViewID);
linearLayout = (LinearLayout) itemView.findViewById(R.id.cardLinearLayout);
editText = (EditText) itemView.findViewById(R.id.addCommentEditText);
imageButton = (ImageButton) itemView.findViewById(R.id.addCommentImageButton);
}
}
}
I wish the page to stay in place, how can I do that ??
Thank you all.
Set your adapter in onCreate and notify it from onDataChange
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
//initialize
.
.
//set adapter
adapter = new RecyclerAdapter(posts, getApplicationContext());
recyclerView.setAdapter(adapter);
}
private void loadRecyclerViewData() {
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (posts.size() > 0) {
posts.clear();
}
for (DataSnapshot ds : dataSnapshot.getChildren()) {
Post post = ds.getValue(Post.class);
//Getting a specific user's information (nickname purposes)
if (post.getSubGenreType().equals(SubGenreString)) {
posts.add(post);
Collections.reverse(posts);
}
}
adapter.notifyDataSetChanged(); //notify
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}

Categories

Resources