display data of every child on a single page - java

recyclerView = findViewById(R.id.recyclerView);
database = FirebaseDatabase.getInstance();
reference_root = database.getReference("/image");
reference_grocery_and_staples = database.getReference("image/Grocery & Staples");
reference_beverages = database.getReference("image/Beverages");
reference_home_and_kitchen = database.getReference("image/Home & Kitchen");
reference_furnishing_and_home_needs = database.getReference("image/Furnishing & Home Needs");
reference_household_needs = database.getReference("image/Household Needs");
reference_personal_care = database.getReference("image/Personal Care");
reference_breakfast_and_dairy = database.getReference("image/Breakfast & Dairy");
reference_biscuits_snacks_and_chocolates = database.getReference("image/Biscuits, Snacks & Chocolates");
reference_noodles_sauces_and_instant_food = database.getReference("image/Noodles, Sauces & Instant Food");
reference_baby_and_kids = database.getReference("image/Baby & Kids");
reference_pet_care = database.getReference("image/Pet Care");
reference_frozen_food = database.getReference("image/Frozen Food");
reference_vegetables = database.getReference("image/Vegetables");
layoutManager = new GridLayoutManager(this, 2);
recyclerView.setLayoutManager(layoutManager);
final ArrayList<DatabaseReference> reference = new ArrayList<>();
reference.add(reference_grocery_and_staples);
reference.add(reference_beverages);
reference.add(reference_home_and_kitchen);
reference.add(reference_furnishing_and_home_needs);
reference.add(reference_household_needs);
reference.add(reference_personal_care);
reference.add(reference_breakfast_and_dairy);
reference.add(reference_biscuits_snacks_and_chocolates);
reference.add(reference_noodles_sauces_and_instant_food);
reference.add(reference_baby_and_kids);
reference.add(reference_pet_care);
reference.add(reference_frozen_food);
reference.add(reference_vegetables);
for(int i = 0; i < 13; i++) {
FirebaseRecyclerOptions<ImageModel> options = new FirebaseRecyclerOptions
.Builder<ImageModel>()
.setQuery(reference.get(i), ImageModel.class)
.build();
adapter = new FirebaseRecyclerAdapter<ImageModel, HomePage.ImageHolder>(options) {
#NonNull
#Override
public HomePage.ImageHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater
.from(HomePage.this)
.inflate(R.layout.row_layout, parent, false);
HomePage.ImageHolder holder = new HomePage.ImageHolder(view);
return holder;
}
#Override
protected void onBindViewHolder(#NonNull HomePage.ImageHolder holder, int position, #NonNull final e.shweta.authenticationdemo.ImageModel model) {
String url = model.getProductURL();
String name = model.getProductName();
String price = model.getProductPrice();
String descritpion = model.getProductDescription();
holder.textView1.setText(name);
holder.textView2.setText("Price: Rs. " + price);
Picasso.get()
.load(url)
.into(holder.imageView);
holder.linearLayoutRowLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(HomePage.this, e.shweta.authenticationdemo.ProductInfo.class);
intent.putExtra("productImage", model.getProductURL());
intent.putExtra("productName", model.getProductName());
intent.putExtra("productPrice", model.getProductPrice());
intent.putExtra("productDescription", model.getProductDescription());
startActivity(intent);
}
});
}
#Override
public void onDataChanged() {
super.onDataChanged();
adapter.notifyDataSetChanged();
}
};
}
recyclerView.setAdapter(adapter);
I want to show the data of all the children in my home page. I have tried to loop the references to the children. But what it is doing is putting the data of only the final loop to the page. I guess it is doing it because it is updating the view every time.
It is only showing me the data of the final loop, i.e the vegetables i want the data on my homepage of every child.

You need to structure your data differently. Add another field like productType which can be beverages, biscuits etc. If you are ready to do this then just create a class Product.java:
public class Product {
private String productName, productPrice;//etc
//add setters and getters
}
To get data and update recycler view
private List<Product> productList;
productList = new ArrayList<>();
mRef = database.getReference().child(); //path
mRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterable<DataSnapshot> productData = dataSnapshot.getChildren();
for(DataSnapshot d : productData){
Product product = d.getValue(Product.class);
if(product.getProductType() == "Beverages"){ //getProductType() is the getter from Product.java
productList.add(product);
recyclerAdapter.notifyDataSetChanged();
}
//Now only beverages are added to recycler view
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Pass the List item to the adapter
recyclerAdapter = new mRecyclerAdapter(getContext(), productList);
modify your adapter constructor to accept these values

Related

How to get total by adding all the recycler views rows

I have recycler view in my activity and below there is a total cost field which shows the total value comes after adding the values from each row. As shown in the screen below:
In a recycler view, there is a spinner that shows quantity on selecting a value from spinner it will be multiplied by the MRP like this every same row have some values. I want to add this value and want to show it in the Lower left corner.
So far I am sending MRP value from adapter class to activity using LocalBroadcatManager class.
But every time I selecting data from another row it does not add cost with the previous value
but it replaces the older value.
Below is my code:
ProductAdapter.java
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ViewHolder> {
private Context context;
private List<ProductsModel> productList;
public ProductAdapter(Context context, List<ProductsModel> productList) {
this.context = context;
this.productList = productList;
}
#NonNull
#Override
public ProductAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.selectpack_layout,parent,false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull final ProductAdapter.ViewHolder holder, int position) {
final ProductsModel model = productList.get(position);
holder.marketName.setText(model.getMarketName());
holder.productNo.setText(model.getProductNo());
holder.page.setText(model.getPage());
holder.mrp.setText(model.getMrp());
holder.innerPack.setText(model.getInnerPack());
holder.outerPack.setText(model.getOuterPack());
List<String> qty = new ArrayList<>();
qty.add("Select qty");
qty.add("1");
qty.add("2");
qty.add("3");
qty.add("4");
qty.add("5");
qty.add("6");
qty.add("7");
qty.add("8");
qty.add("9");
qty.add("10");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, qty);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.qtySpinner.setAdapter(dataAdapter);
holder.qtySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
int sum = 0;
String item = adapterView.getItemAtPosition(i).toString();
if (!item.equals("Select qty")) {
int qty = Integer.parseInt(item);
int cost = Integer.parseInt(model.getMrp());
int val = cost * qty;
holder.total.setText(String.valueOf(val));
Intent intent = new Intent("msg");
intent.putExtra("cost", String.valueOf(val));
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
#Override
public int getItemCount() {
return productList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView marketName,productNo,page,mrp,innerPack,outerPack,total;
Spinner qtySpinner;
Button order;
public ViewHolder(#NonNull View itemView) {
super(itemView);
order = itemView.findViewById(R.id.order);
qtySpinner = itemView.findViewById(R.id.qtySpinner);
marketName = itemView.findViewById(R.id.marketName);
productNo = itemView.findViewById(R.id.productNo);
page = itemView.findViewById(R.id.page);
mrp = itemView.findViewById(R.id.mrp);
innerPack = itemView.findViewById(R.id.innerPack);
outerPack = itemView.findViewById(R.id.outerPack);
total = itemView.findViewById(R.id.total);
}
}
}
SelectPack.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_pack);
fAuth = FirebaseAuth.getInstance();
ActionBar ab = getSupportActionBar();
assert ab!= null;
ab.setTitle("Select Pack");
ab.setDisplayHomeAsUpEnabled(true);
marketSpinner = findViewById(R.id.marketSpinner);
progress = findViewById(R.id.progress);
products = findViewById(R.id.products);
totalCost = findViewById(R.id.totalCost);
products.setHasFixedSize(true);
products.setLayoutManager(new LinearLayoutManager(this));
productList = new ArrayList<>();
List<String> categories = new ArrayList<String>();
categories.add("Select market");
categories.add("Crown");
categories.add("Long Book A4");
categories.add("Long Book");
categories.add("Crown Junior");
categories.add("Physics");
categories.add("Chemistry");
categories.add("Biology");
categories.add("Universal");
categories.add("Sketch Book");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
marketSpinner.setAdapter(dataAdapter);
marketSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String item = adapterView.getItemAtPosition(i).toString();
if(item.equals("Select market")){
progress.setVisibility(View.INVISIBLE);
}
else{
getData(item);
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
LocalBroadcastManager.getInstance(SelectPack.this).registerReceiver(message,new IntentFilter("msg"));
}
private void getData(String item){
progress.setVisibility(View.VISIBLE);
products.setVisibility(View.INVISIBLE);
productList.clear();
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(20, TimeUnit.SECONDS)
.readTimeout(20,TimeUnit.SECONDS)
.writeTimeout(20,TimeUnit.SECONDS)
.build();
RequestBody formBody = new FormBody.Builder()
.add("name",item)
.build();
Request request = new Request.Builder().post(formBody).url(URL).build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onResponse(#NotNull Call call, #NotNull final Response response) throws IOException {
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
JSONArray jsonArray = new JSONArray(response.body().string());
if(jsonArray.length() > 0){
products.setVisibility(View.VISIBLE);
progress.setVisibility(View.INVISIBLE);
}
for(int i=0;i<jsonArray.length();i++){
progress.setVisibility(View.INVISIBLE);
JSONObject object = jsonArray.getJSONObject(i);
String str1 = object.getString("market");
String str2 = object.getString("product_no");
String str3 = object.getString("page");
String str4 = object.getString("mrp");
String str5 = object.getString("inner_pack");
String str6 = object.getString("outer_pack");
Log.d("prod",str2);
ProductsModel model = new ProductsModel(str1,str2,str3,str4,str5,str6);
productList.add(model);
}
ProductAdapter adapter = new ProductAdapter(getApplicationContext(),productList);
products.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
#Override
public void onFailure(#NotNull Call call, #NotNull final IOException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
progress.setVisibility(View.INVISIBLE);
products.setVisibility(View.INVISIBLE);
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
});
}
public BroadcastReceiver message = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String nam = intent.getStringExtra("cost");
if(nam != null){
int val = Integer.parseInt(nam);
totalCost.setText("Total: "+val+".00");
}
}
};
Someone, please let me know what I am doing wrong or how should I implement it correctly. Any help would be appreciated.
THANKS
why you are using local broadcasts to communicate with activity. Instead, use interface to communicate it will be easy to use.
I found the problem when the item is getting selected you are passing the only current value not all the selected value that's why it is showing the latest value instead of all the value.
You should pass all the selected values from the list, let's say If I select one value, keep that in the separate list or you can manage with a flag in the current list object and when user selects any item then loop through that list and add all the price and pass it to activity.
Add one field in ProductsModel called Qty
Here is my updated adapter class I have added a comment as well please try this Hope it helps
public class ProductAdapter extends RecyclerView.Adapter {
private Context context;
private List<ProductsModel> productList;
// add this list
private List<ProductsModel> selectedProductList = new ArrayList();
public ProductAdapter(Context context, List<ProductsModel> productList) {
this.context = context;
this.productList = productList;
}
#NonNull
#Override
public ProductAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.selectpack_layout,parent,false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull final ProductAdapter.ViewHolder holder, int position) {
final ProductsModel model = productList.get(position);
holder.marketName.setText(model.getMarketName());
holder.productNo.setText(model.getProductNo());
holder.page.setText(model.getPage());
holder.mrp.setText(model.getMrp());
holder.innerPack.setText(model.getInnerPack());
holder.outerPack.setText(model.getOuterPack());
List<String> qty = new ArrayList<>();
qty.add("Select qty");
qty.add("1");
qty.add("2");
qty.add("3");
qty.add("4");
qty.add("5");
qty.add("6");
qty.add("7");
qty.add("8");
qty.add("9");
qty.add("10");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, qty);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.qtySpinner.setAdapter(dataAdapter);
holder.qtySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
int sum = 0;
String item = adapterView.getItemAtPosition(i).toString();
// add this line
adapterView.getItemAtPosition(i);
if (!item.equals("Select qty")) {
// add this line
model.setQty(Integer.parseInt(item));
selectedProductList.add(model);
}
int val = 0;
for(int j = 0; j < selectedProductList.size(); j++){
ProductsModel model = selectedProductList.get(i);
int mrp = model.getMrp();
int qty = model.getQty();
val = val + (mrp * qty);
}
holder.total.setText(String.valueOf(val));
Intent intent = new Intent("msg");
intent.putExtra("cost", String.valueOf(val));
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
#Override
public int getItemCount() {
return productList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView marketName,productNo,page,mrp,innerPack,outerPack,total;
Spinner qtySpinner;
Button order;
public ViewHolder(#NonNull View itemView) {
super(itemView);
order = itemView.findViewById(R.id.order);
qtySpinner = itemView.findViewById(R.id.qtySpinner);
marketName = itemView.findViewById(R.id.marketName);
productNo = itemView.findViewById(R.id.productNo);
page = itemView.findViewById(R.id.page);
mrp = itemView.findViewById(R.id.mrp);
innerPack = itemView.findViewById(R.id.innerPack);
outerPack = itemView.findViewById(R.id.outerPack);
total = itemView.findViewById(R.id.total);
}
}
}

RecyclerView is not populating items whereas Adapter and ArrayList already has data

recycerViewOrderNewItem and offlineOrderProductListProductList are two recyclerviews and those were initialized in onCreate() method.
recycerViewOrderNewItem = findViewById(R.id.recycerViewOrderNewItem);
recycerViewOrderNewItem.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
offlineOrderProductListProductList = findViewById(R.id.offlineOrderProductListProductList);
offlineOrderProductListProductList.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
The below is where I am retrieving my data as List<>
List<NewOrderEntryModel> allItemsOfOrder = new InitializeDatabase(OrderEntryActivity.this).myAppDatabaseInit.myDao().getAllNewOrderEntryModelByRefID(SalesID);
and I am setting adapter like this for both of them...
offlineOrderProductListProductList.setAdapter(new NewOrderEntryAdapter(OrderEntryActivity.this, (ArrayList<NewOrderEntryModel>) allItemsOfOrder));
recycerViewOrderNewItem.setAdapter(new NewOrderEntryAdapter(OrderEntryActivity.this, (ArrayList<NewOrderEntryModel>) allItemsOfOrder));
for offlineOrderProductListProductList recyclerview is working but for recycerViewOrderNewItem recyclerview is not working
I have debugged the code. ArrayList contains data.
Below is my adapter code...
public class NewOrderEntryAdapter extends RecyclerView.Adapter<NewOrderEntryAdapter.NewOrderEntryAdapterViewHolder>{
private Context context;
private ArrayList<NewOrderEntryModel> newOrderEntryModels;
public NewOrderEntryAdapter(Context context, ArrayList<NewOrderEntryModel> newOrderEntryModels) {
this.context = context;
this.newOrderEntryModels = newOrderEntryModels;
}
#NonNull
#Override
public NewOrderEntryAdapterViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.list_item_order_entry_detail,parent,false);
return new NewOrderEntryAdapterViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull NewOrderEntryAdapterViewHolder holder, final int position) {
NewOrderEntryModel orderEntryModel = newOrderEntryModels.get(position);
//Data
final String name = orderEntryModel.getProductName();
final String totalPrice = String.valueOf(orderEntryModel.getPBSalesTotal());
final String code = String.valueOf(orderEntryModel.getPCode());
final String quantity = String.valueOf(orderEntryModel.getPBInQty());
final String price = String.valueOf(orderEntryModel.getPBSalesPrice());
final String productID = String.valueOf(orderEntryModel.getPBProductID());
// Binding
holder.tvProductNameOrderEntry.setText(name);
holder.tvProductTotalPriceOrderEntry.setText(totalPrice);
holder.tvProductCodeOrderEntry.setText(code);
holder.tvProductQuantityOrderEntry.setText(quantity);
holder.tvProductPriceOrderEntry.setText(price);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(context, "Reference id: "+orderEntryModel.getPBRefID()+" Table ID: "+orderEntryModel.getID(), Toast.LENGTH_SHORT).show();
if(orderEntryModel.getPBRefID()==null){
//Toast.makeText(context, "Reference id: "+orderEntryModel.getPBRefID()+" Table ID: "+orderEntryModel.getID(), Toast.LENGTH_SHORT).show();
openDetailActivity(String.valueOf(position),"","",name,totalPrice,code,quantity,price,productID);
}else {
Toast.makeText(context, "Reference id: "+orderEntryModel.getPBRefID()+" Table ID: "+orderEntryModel.getID(), Toast.LENGTH_SHORT).show();
openDetailActivity(String.valueOf(position),Integer.toString(orderEntryModel.getID()),orderEntryModel.getPBRefID(),name,totalPrice,code,quantity,price,productID);
}
//Toast.makeText(context, context.toString(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return newOrderEntryModels.size();
}
public class NewOrderEntryAdapterViewHolder extends RecyclerView.ViewHolder{
public TextView tvProductNameOrderEntry
,tvProductTotalPriceOrderEntry
,tvProductCodeOrderEntry
,tvProductQuantityOrderEntry
,tvProductPriceOrderEntry;
public NewOrderEntryAdapterViewHolder(View itemView) {
super(itemView);
tvProductNameOrderEntry = itemView.findViewById(R.id.tvProductNameOrderEntry);
tvProductTotalPriceOrderEntry = itemView.findViewById(R.id.tvProductTotalPriceOrderEntry);
tvProductCodeOrderEntry = itemView.findViewById(R.id.tvProductCodeOrderEntry);
tvProductQuantityOrderEntry = itemView.findViewById(R.id.tvProductQuantityOrderEntry);
tvProductPriceOrderEntry = itemView.findViewById(R.id.tvProductPriceOrderEntry);
}
}
public void openDetailActivity(String position,
String id,
String pbRef,
String productName,
String totalPrice,
String productCode,
String quantity,
String productPrice,
String productID){
Intent intent = new Intent(context, NewItemDetailActivity.class);
intent.putExtra("position",position);
intent.putExtra("id",id);
intent.putExtra("pbRef",pbRef);
intent.putExtra("productName",productName);
intent.putExtra("totalPrice",totalPrice);
intent.putExtra("productCode",productCode);
intent.putExtra("quantity",quantity);
intent.putExtra("productPrice",productPrice);
intent.putExtra("productID",productID);
context.startActivity(intent);
}
}
please help me out with this problem...
I think you should initialize your adapter and recyclerview clearly.
allItemsOfOrder can be global like this
List<NewOrderEntryModel> allItemsOfOrder = new ArrayList<>();
Take the code below as an example:
recyclerView = (RecyclerView) findViewById(R.id.recycerViewOrderNewItem);
mAdapter = new NewOrderEntryAdapter(this,allItemsOfOrder);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
Then you should add orders to your list
allItemsOfOrder can be global like this
allItemsOfOrder.add(/*Something*/);
Then you should notify your adapter like below...
mAdapter.notifyDataSetChanged();
you can use this link as a reference.

Can't correctly pass data through Intent from ListView

I try to pass data item that I choose in ListView to the next Activity. But all that I can, is that second activity is empty or nullpoinexception error. I did it with RecycleView, but with ListView there some problems.
Main activity:
public class ListViewPlaces extends AppCompatActivity {
FirebaseFirestore mFirestore = FirebaseFirestore.getInstance();
CollectionReference placeRef = mFirestore.collection("Places");
Query query;
ListView mListView;
String name;
Places places;
ArrayList<Places> randomPlaceList;
PlaceAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view_places);
mListView = findViewById(R.id.place_list);
randomPlaceList = new ArrayList<>();
Boolean l_check1 = getIntent().getExtras().getBoolean("1");
Boolean l_check2 = getIntent().getExtras().getBoolean("2");
if (l_check2){
query = placeRef.whereEqualTo("colour", "red");
} else if (l_check1){
query = placeRef.whereEqualTo("size", "1");
} else {
query = placeRef.whereEqualTo("size", "2");
}
query.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
List<Places> placesList = new ArrayList<>();
for (DocumentSnapshot document : task.getResult()) {
Places place = document.toObject(Places.class);
placesList.add(place);
}
int placeCount = placesList.size();
Random randomGenerator = new Random();
ArrayList<Places> randomPlaceList = new ArrayList<>();
for (int i = 1; i <= 3; i++) {
randomPlaceList.add(placesList.get(randomGenerator.nextInt(placeCount)));
}
ListView mListView = (ListView) findViewById(R.id.place_list);
mAdapter = new PlaceAdapter(randomPlaceList, getBaseContext());
mListView.setAdapter(mAdapter);
}
}
});
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Places places = mAdapter.getItem(position);
Intent intent = new Intent(getApplicationContext(), Card_activity.class);
intent.putExtra("name", places.getName());
startActivity(intent);
}
});
}
}
My model class:
public class Places {
private String image, name;
public Places() {
}
public Places(String image, String name) {
this.image = image;
this.name = name;
}
public String getImage() { return image; }
public String getName() { return name; }
}
Custom Adapter:
class PlaceAdapter extends ArrayAdapter<Places> {
private ArrayList<Places> dataSet;
Context mContext;
private static class ViewHolder {
TextView name_text;
ImageView image_text;
}
public PlaceAdapter(ArrayList<Places> dataSet, Context context ) {
super(context, R.layout.item_list, dataSet);
this.dataSet = dataSet;
this.mContext = context;
}
#Override
public View getView(int position, View converView, ViewGroup parent) {
Places places = getItem(position);
ViewHolder viewHolder;
final View result;
if (converView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
converView = inflater.inflate(R.layout.item_list, parent, false);
viewHolder.name_text = (TextView) converView.findViewById(R.id.text_image_id);
viewHolder.image_text = (ImageView) converView.findViewById(R.id.image_id);
result = converView;
converView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) converView.getTag();
result = converView;
}
viewHolder.name_text.setText(places.getName());
Glide.with(getContext()).load(places.getImage()).into(viewHolder.image_text);
return converView;
And the second activity, where I pass data:
public class Card_activity extends AppCompatActivity implements View.OnClickListener{
TextView mTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.massive_places);
mTextView = findViewById(R.id.head_name);
String name = getIntent().getStringExtras("name")
mTextView.setText(name);
}
}
EDITED: Error
java.lang.NullPointerException: Attempt to invoke virtual method
'java.lang.Object java.util.ArrayList.get(int)' on a null object
reference
on this line:
Places places = randomPlaceList.get(position);
ERROR:
Process: com.example.eugene.lafinalproduction, PID: 8352
java.lang.IllegalArgumentException: n <= 0: 0
at java.util.Random.nextInt(Random.java:182)
at com.example.eugene.lafinalproduction.ListViewPlaces$1.onComplete(ListViewPlaces.java:63)
at com.google.android.gms.tasks.zzj.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5763)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
The problem in this line:
randomPlaceList.add(placesList.get(randomGenerator.nextInt(placeCount)));
The error means that your randomPlaceList is null.
Since I can't see the app or the logics you performed to get the error, I just go based on what I see.
The first stuff is that if you need to get the clicked item, it should be done by calling the getItem(position) method of your adapter; you can easily implement it like below:
#Override
public Places getItem(int position) {
if(dataSet != null && position < dataSet.size()){
return dataSet.get(position);
}
return null;
}
Now from your activity you can simply perform a call like:
Places places = mAdapter.getItem(position);
Remember to add a reference to the adapter when you initialize it by adding PlaceAdapter mAdapter; in activity variables and replacing initialization with
mAdapter = new PlaceAdapter(randomPlaceList, getBaseContext());
mListView.setAdapter(mAdapter);
reading the code quickly, I don't also find much sense to this:
this.randomPlaceList = randomPlaceList;
but maybe you cut out some code, but I prefer to report it to you, just in case :)
Note to specify the error
The error is here and it is about variable refer:
query.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
List<Places> placesList = new ArrayList<>();
for (DocumentSnapshot document : task.getResult()) {
Places place = document.toObject(Places.class);
placesList.add(place);
}
int placeCount = placesList.size();
Random randomGenerator = new Random();
// In the line below, you specify a new ArrayList that is LOCAL, you don't refer to the Activity's object
ArrayList<Places> randomPlaceList = new ArrayList<>();
for (int i = 1; i <= 3; i++) {
randomPlaceList.add(placesList.get(randomGenerator.nextInt(placeCount)));
}
ListView mListView = (ListView) findViewById(R.id.place_list);
PlaceAdapter placeAdapter = new PlaceAdapter(randomPlaceList, getBaseContext());
mListView.setAdapter(placeAdapter);
}
});
You should replace it with:
query.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
List<Places> placesList = new ArrayList<>();
for (DocumentSnapshot document : task.getResult()) {
Places place = document.toObject(Places.class);
placesList.add(place);
}
int placeCount = placesList.size();
Random randomGenerator = new Random();
randomPlaceList = new ArrayList<>(); //this is the activity's list
for (int i = 1; i <= 3; i++) {
randomPlaceList.add(placesList.get(randomGenerator.nextInt(placeCount)));
}
ListView mListView = (ListView) findViewById(R.id.place_list);
PlaceAdapter placeAdapter = new PlaceAdapter(randomPlaceList, getBaseContext());
mListView.setAdapter(placeAdapter);
}
});
Otherwise the activity's list will always be null, since you never init it
Hope this helps
Initialize you randomPlaceList in your onCreate method of ListViewPlaces.
randomPlaceList = new ArrayList<>();
Currently you are initializing your randomPlaceList in this way this.randomPlaceList = randomPlaceList; which is wrong because you are assigning same copy of randomPlaceList, its like a = a.
And delete your local variable ArrayList<Places> randomPlaceList = new ArrayList<>(); which is inside query.get().addOnCompleteListener();
getIntent().getExtras() returns a Bundle that has values in Key-Value pairs(You can add multiple value of Key-Value pair to a Bundle) but you are not passing a Bundle, you are passing simply one Key-Value pair. So it is preferred to call getStringExtra("name") in your Card_activity.
String name = getIntent().getStringExtra("name");
Instead of
String name = getIntent().getExtras().getString("name");
In your second activity, change this:
String name = getIntent().getExtras().getString("name");
To:
String name = getIntent().getStringExtra("name");
There are several issues in your code. But let's just focus on your question.
You should use
intent.getStringExtra
to get string data from previous activity, instead of using
intent.getExtras().getString("name");
getStringExtra and getExtras are different.

Removing some items in Gridlayout Recyclerview leaves Empty spaces

I am trying to remove some Items from my Json Response in my recyclerview but when I do that an empty item spaces is being created in place of the removed item. This is happening only when I use gridlayout manager with recyclerview , if I use Linearlayout manager there are no empty spaces.
Below is my code:
activityRecylerviewBinding.recyclerview1.setHasFixedSize(true);
//activityRecylerviewBinding.recyclerview1.setLayoutManager(new LinearLayoutManager(getActivity()));
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 2);
activityRecylerviewBinding.recyclerview1.setLayoutManager(mLayoutManager);
activityRecylerviewBinding.recyclerview1.addItemDecoration(new GridSpacingItemDecoration(2, dpToPx(5), true));
activityRecylerviewBinding.recyclerview1.setItemAnimator(new DefaultItemAnimator());
And for Removing items:
if (!user.emailId.equals(clickedemail)){
viewHolder.setIsRecyclable(false);
viewHolder.mAdapterItemChatsBinding.gooot.removeAllViews();
viewHolder.mAdapterItemChatsBinding.gooot.setPadding(0, 0, 0, 0);
//viewHolder.mAdapterItemChatsBinding.gooot.getLayoutParams().height = 0;
}else {
viewHolder.bindUser(user, RecycFragment.this);
}
When I use the blow code it's works fine.
activityRecylerviewBinding.recyclerview1.setLayoutManager(new LinearLayoutManager(getActivity()));
JsonParsing code:
private void initializeFirebase() {
final Query refUsers = FirebaseDatabase.getInstance()
.getReference(ConstantsFirebase.FIREBASE_LOCATION_GARMENTS);
refUsers.keepSynced(true);
final List<UploadImage> uploadImageList = new ArrayList<>();
refUsers.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot messageSnapshot : dataSnapshot.getChildren()) {
UploadImage uploadImage = messageSnapshot.getValue(UploadImage.class);
uploadImageList.add(uploadImage);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mAdapter = new FirebaseRecyclerAdapter<UploadImage, ChatsItemHolder>(UploadImage.class, R.layout.recycitemfirebase,
ChatsItemHolder.class, refUsers) {
#Override
public ChatsItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
adapterItemChatsBinding = DataBindingUtil.inflate(LayoutInflater
.from(parent.getContext()), viewType, parent, false);
//adapterItemChatsBinding.tvUserName.setTypeface(Typefaces.get(getActivity(), Constants.FONT_ROBOT_REGULAR));
return new ChatsItemHolder(adapterItemChatsBinding);
}
#Override
protected void populateViewHolder(ChatsItemHolder viewHolder, final UploadImage user, int position) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
clickedemail = prefs.getString(Constants.KEY_CLICKED_EMAIL, "");
if (!user.emailId.equals(clickedemail)){
viewHolder.setIsRecyclable(false);
viewHolder.mAdapterItemChatsBinding.gooot.removeAllViews();
viewHolder.mAdapterItemChatsBinding.gooot.setPadding(0, 0, 0, 0);
//viewHolder.mAdapterItemChatsBinding.gooot.getLayoutParams().height = 0;
}else {
viewHolder.bindUser(user, RecycFragment.this);
}
viewHolder.mAdapterItemChatsBinding.title.setText(user.getGarment_name());
viewHolder.mAdapterItemChatsBinding.count.setText(user.getGarment_color());
Glide.with(viewHolder.mAdapterItemChatsBinding.thumbnail.getContext())
.load(user.getImage())
.placeholder(R.drawable.ic_person)
.fitCenter()
.dontAnimate()
.into(viewHolder.mAdapterItemChatsBinding.thumbnail);
}
};
activityRecylerviewBinding.recyclerview1.setAdapter(mAdapter);
}
Can someone tell me what am I doing wrong?
Where are you removing your item from the dataset?
The action to remove the item should have the items index in the dataset should it not? If so something like this should work:
public void removeItem(final int index) {
list.remove(index);
adapter.notifyItemRemoved(index);
}
Seems, that adapter for recyclerview is built with the the firebase query as the source of the items.
You need to change your firebase query to only fetch the items you want to have in your list.

RecyclerView OutOfBoundsException When No Items in Array

I am trying to create a RecyclerView that populates CardViews based on data in Firebase. I am receiving an IndexOutOfBoundsException when there is no data in Firebase, however I would like for the RecyclerView to display (without any data) when there is no data in Firebase:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Firebase.setAndroidContext(this);
setContentView(R.layout.activity_discussion);
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
setTitle(R.string.discussion_title_text);
mDateFormat = new SimpleDateFormat("MM-dd-yyyy");
mDate = new Date();
mCurrentDateString = mDateFormat.format(mDate);
mBaseRef = new Firebase(FIREBASE_URL);
mPollsRef = mBaseRef.child(POLLS_LABEL);
mUpdateRef = mPollsRef.child(mCurrentDateString).child(String.valueOf(mPollIndex + 1));
mCommentsRef = mUpdateRef.child(COMMENTS_LABEL);
mPollImage = (ImageView) findViewById(R.id.comments_image);
mPollCommentQuestion = (TextView) findViewById(R.id.poll_comment_question);
mUserComment = (EditText) findViewById(R.id.user_comment);
mUserAvatar = (ImageView) findViewById(R.id.profile_image_avatar);
mCommentArrayList = new ArrayList<Comments>();
mCommentIDArrayList = new ArrayList<String>();
mPollCommentsList = (RecyclerView) findViewById(R.id.poll_comments_list);
LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.VERTICAL);
mPollCommentsList.setLayoutManager(llm);
mPollCommentsList.setHasFixedSize(true);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
mUpdateRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
setImage(dataSnapshot);
setQuestion(dataSnapshot);
createInitialCommentIDArray(dataSnapshot);
mNumberOfCommentsAtPoll = (int) dataSnapshot.child(COMMENTS_LABEL).getChildrenCount();
for (int i = 0; i < mNumberOfCommentsAtPoll; i++) {
String commentID = (String) dataSnapshot.child(COMMENTS_LABEL).child(mCommentIDArrayList.get(i)).child("COMMENT").getValue();
Log.v("COMMENT_ID", "The comment ID is " + commentID);
String userID = (String) dataSnapshot.child(COMMENTS_LABEL).child(mCommentIDArrayList.get(i)).child("USER_ID").getValue();
Log.v("USER_ID", "The user ID is " + userID);
mCommentArrayList.add(0, new Comments(mUserAvatar, userID, commentID));
mCommentAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
mCommentAdapter = new MyAdapter(mCommentArrayList);
mPollCommentsList.setAdapter(mCommentAdapter);
Intent intent = getIntent();
String pollID = intent.getStringExtra("POLL_ID");
mPollIndex = intent.getIntExtra("POLL_INDEX", 0);
//TODO: Store unique comment ID's in an array
//TODO: Figure out how to programmatically add images to AWS and then store URL in Firebase
ImageView fab = (ImageView) findViewById(R.id.add_comment);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
HashMap<String, Object> commentMap = new HashMap<String, Object>();
commentMap.put("USER_ID", mBaseRef.getAuth().getUid());
commentMap.put("COMMENT", mUserComment.getText().toString());
mUpdateRef.child(COMMENTS_LABEL).push().updateChildren(commentMap);
hideKeyboard(view);
mUserComment.setText("");
Toast.makeText(getApplicationContext(), R.string.comment_added, Toast.LENGTH_LONG).show();
}
});
}
My Array Adapter, I note where the error is occurring:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private ArrayList<Comments> mDataSet;
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
protected ImageView userAvatar;
protected TextView userID;
protected TextView userComment;
public ViewHolder(View v) {
super(v);
userAvatar = (ImageView) findViewById(R.id.profile_image_avatar);
userID = (TextView) findViewById(R.id.user_ID);
userComment = (TextView) findViewById(R.id.user_comment);
}
}
// Provide a suitable constructor (depends on the kind of dataset)
public MyAdapter(ArrayList<Comments> myDataset) {
mDataSet = myDataset;
}
// Create new views (invoked by the layout manager)
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.individual_comment, parent, false);
// set the view's size, margins, paddings and layout parameters
ViewHolder x = new ViewHolder(v);
return x;
}
// Replace the contents of a view (invoked by the layout manager)
//The OutOfBoundsException is pointing here
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.userComment.setText(mCommentArrayList.get(position).getUserComment());
String x = mCommentArrayList.get(position).getUserComment();
Log.v("ON_BIND_VIEW", "THE STRING IS " + x);
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return mNumberOfCommentsAtPoll;
}
}
Result:
You should try to return mDataset.size() in the getItemCount() method instead of mNumberOfCommentsAtPoll.
#Override
public int getItemCount() {
return mDataSet.size();
}

Categories