BaseAdapter - how to use notifyItemRemoved - java

I have a BaseAdapter which is responsible for my SwipeCardView. Now I need to add something like this notifyItemRemoved to remove one specific item and show the new list. I need to remove the item at the bottom of my code at the AlertDialog part. Everything is working, its just I don't know how to remove it. Unfortunately, I can't find the right syntax for it. FYI I removed method like the constructor etc. to keep the post small:
public class FeedAdapter extends BaseCardAdapter {
private List<EventObject> ideen;
private Activity context;
#Override
public void onBindData(final int position, View cardview) {
if (ideen.size() ==0 || ideen == null){
return;
}
ImageView bild = cardview.findViewById(R.id.imageView);
TextView name = cardview.findViewById(R.id.name);
final EventObject eo = ideen.get(position);
name.setText(eo.getName());
TextView adress = cardview.findViewById(R.id.address);
Geocoder geocoder;
List<Address> addresses = null;
geocoder = new Geocoder(context, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(Double.parseDouble(eo.getLat()), Double.parseDouble(eo.getLng()), 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
} catch (IOException e) {
e.printStackTrace();
}
String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
String city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName();
String[] separatedadress = address.split(",");
adress.setText(separatedadress[0]+" , "+city);
TextView date = cardview.findViewById(R.id.date);
date.setText(eo.getDate());
Button teilnehmen = cardview.findViewById(R.id.teilnehmen);
teilnehmen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String userid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users").child(userid).child("acceptedEvents").child(eo.getId());
ref.setValue(true);
getPLZ(eo.getId(), eo, position);
}
});
bild.setImageResource(R.drawable.blau);
}
private void getPLZ(final String id, final EventObject eo, final int position) {
String userid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users").child(userid).child("plz");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String plz = dataSnapshot.getValue().toString();
setParticipantInEvent(plz, id, eo, position);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void setParticipantInEvent(String plz, String id, EventObject eo, int position){
String userid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Events").child(plz).child(id);
ref.child("participants").child(userid).setValue(true);
askForCalendar(eo, position);
}
private void askForCalendar(final EventObject eventObject, final int position) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("Event in deinem Kalender speichern?")
.setCancelable(false)
.setPositiveButton("Ja", new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra("beginTime", Long.parseLong(eventObject.getTs()));
intent.putExtra("allDay", true);
intent.putExtra("endTime", Long.parseLong(eventObject.getTs())+60*60*1000);
intent.putExtra("title", eventObject.getName());
context.startActivity(intent);
}
})
.setNegativeButton("Nein", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//Here i have to remove one item:
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}

Related

bottom Sheet Dialog Crashing

holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//handle item clicks show item details (in bottom sheet)
detailBottomProduct(productModel);
}
});
private void detailBottomProduct(ProductModel productModel) {
final BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(context);
View view = LayoutInflater.from(context).inflate(R.layout.bs_product_details_seller,null);
//init View
ImageView productIconIv = view.findViewById(R.id.productIconIv);
TextView discountNoteTv = view.findViewById(R.id.discountNoteTv);
TextView titleTv = view.findViewById(R.id.titleTv);
TextView descriptionTv = view.findViewById(R.id.descriptionTv);
TextView categoryTv = view.findViewById(R.id.categoryTv);
TextView quantityTv = view.findViewById(R.id.quantityTv);
TextView discountPriceTv = view.findViewById(R.id.discountPriceTv);
TextView priceTv = view.findViewById(R.id.priceTv);
//get Data
final String id = productModel.getProductId();
String uid = productModel.getUid();
String discountAvailable = productModel.getDiscountAvailable();
String discountNote = productModel.getDiscountNote();
String discountPrice = productModel.getDiscountPrice();
String productCategory = productModel.getProductCategory();
String productIcon = productModel.getProductIcon();
final String title = productModel.getProductTitle();
String description = productModel.getProductDescription();
String productQuantity = productModel.getProductQuantity();
String timestamp = productModel.getTimestamp();
String actualPrice = productModel.getProductPrice();
//setData
titleTv.setText(title);
descriptionTv.setText(description);
categoryTv.setText(productCategory);
priceTv.setText("₹ "+ actualPrice);
quantityTv.setText(productQuantity);
discountPriceTv.setText("₹ "+discountPrice);
discountNoteTv.setText(discountNote);
if (discountAvailable.equals("true")){
//product is on discount
discountPriceTv.setVisibility(View.VISIBLE);
discountNoteTv.setVisibility(View.VISIBLE);
priceTv.setPaintFlags(priceTv.getPaintFlags()| Paint.STRIKE_THRU_TEXT_FLAG);
}
else {
//product is not on discount
discountPriceTv.setVisibility(View.GONE);
discountNoteTv.setVisibility(View.GONE);
}
try {
Glide.with(context).load(productIcon).into(productIconIv);
}
catch (Exception e){
productIconIv.setImageResource(R.drawable.ic_add_shopping_primary);
}
//set view
bottomSheetDialog.setContentView(view);
//show dialog
bottomSheetDialog.show(); // app crashed point (Line 173 )
}
Complete Adapter Code:
public class AdapterProductSeller extends
RecyclerView.Adapter<AdapterProductSeller.HolderProductSeller>
implements Filterable {
private Context context;
public ArrayList<ProductModel> productList,filterList;
private FilterProduct filter;
public AdapterProductSeller(Context context, ArrayList<ProductModel> productList) {
this.context = context;
this.productList = productList;
this.filterList = productList;
}
#NonNull
#Override
public HolderProductSeller onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
//inflate layout
View view = LayoutInflater.from(context).inflate(R.layout.row_product_seller,parent,false);
return new HolderProductSeller(view);
}
#Override
public void onBindViewHolder(#NonNull HolderProductSeller holder, int position) {
//getData
ProductModel productModel = productList.get(position);
String id = productModel.getProductId();
String uid = productModel.getUid();
String discountAvailable = productModel.getDiscountAvailable();
String discountNote = productModel.getDiscountNote();
String discountPrice = productModel.getDiscountPrice();
String productCategory = productModel.getProductCategory();
String productIcon = productModel.getProductIcon();
String title = productModel.getProductTitle();
String description = productModel.getProductDescription();
String productQuantity = productModel.getProductQuantity();
String timestamp = productModel.getTimestamp();
String actualPrice = productModel.getProductPrice();
//setData
holder.discountNoteTv.setText(discountNote);
holder.titleTv.setText(title);
holder.quantityTv.setText(productQuantity);
holder.discountPriceTv.setText("₹"+discountPrice);
if (discountAvailable.equals("true")){
//product is on discount
holder.discountPriceTv.setVisibility(View.VISIBLE);
holder.discountNoteTv.setVisibility(View.VISIBLE);
holder.priceTv.setPaintFlags(holder.priceTv.getPaintFlags()| Paint.STRIKE_THRU_TEXT_FLAG);
}
else {
//product is not on discount
holder.discountPriceTv.setVisibility(View.GONE);
holder.discountNoteTv.setVisibility(View.GONE);
}
try {
Glide.with(context).load(productIcon).into(holder.productIconIv);
}
catch (Exception e){
holder.productIconIv.setImageResource(R.drawable.ic_add_shopping_primary);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//handle item clicks show item details (in bottom sheet)
detailBottomProduct(productModel);
}
});
}
private void detailBottomProduct(ProductModel productModel) {
final BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(context);
View view = LayoutInflater.from(context).inflate(R.layout.bs_product_details_seller,null);
//init View
ImageButton backBtn = view.findViewById(R.id.backBtn);
ImageButton editBtn = view.findViewById(R.id.editBtn);
ImageButton deleteBtn = view.findViewById(R.id.deleteBtn);
ImageView productIconIv = view.findViewById(R.id.productIconIv);
TextView discountNoteTv = view.findViewById(R.id.discountNoteTv);
TextView titleTv = view.findViewById(R.id.titleTv);
TextView descriptionTv = view.findViewById(R.id.descriptionTv);
TextView categoryTv = view.findViewById(R.id.categoryTv);
TextView quantityTv = view.findViewById(R.id.quantityTv);
TextView discountPriceTv = view.findViewById(R.id.discountPriceTv);
TextView priceTv = view.findViewById(R.id.priceTv);
//get Data
final String id = productModel.getProductId();
String uid = productModel.getUid();
String discountAvailable = productModel.getDiscountAvailable();
String discountNote = productModel.getDiscountNote();
String discountPrice = productModel.getDiscountPrice();
String productCategory = productModel.getProductCategory();
String productIcon = productModel.getProductIcon();
final String title = productModel.getProductTitle();
String description = productModel.getProductDescription();
String productQuantity = productModel.getProductQuantity();
String timestamp = productModel.getTimestamp();
String actualPrice = productModel.getProductPrice();
//setData
titleTv.setText(title);
descriptionTv.setText(description);
categoryTv.setText(productCategory);
priceTv.setText("₹ "+ actualPrice);
quantityTv.setText(productQuantity);
discountPriceTv.setText("₹ "+discountPrice);
discountNoteTv.setText(discountNote);
if (discountAvailable.equals("true")){
//product is on discount
discountPriceTv.setVisibility(View.VISIBLE);
discountNoteTv.setVisibility(View.VISIBLE);
priceTv.setPaintFlags(priceTv.getPaintFlags()| Paint.STRIKE_THRU_TEXT_FLAG);
}
else {
//product is not on discount
discountPriceTv.setVisibility(View.GONE);
discountNoteTv.setVisibility(View.GONE);
}
try {
Glide.with(context).load(productIcon).into(productIconIv);
}
catch (Exception e){
productIconIv.setImageResource(R.drawable.ic_add_shopping_primary);
}
//set view
bottomSheetDialog.setContentView(view);
//show dialog
bottomSheetDialog.show();
// edit click
editBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bottomSheetDialog.dismiss();
//open product activity
Intent intent = new Intent(context, EditProductActivity.class);
intent.putExtra("productId",id);
context.startActivity(intent);
}
});
//delete Btn
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bottomSheetDialog.dismiss();
//show delete confirm dialog
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Delete")
.setMessage("Are you sure you want to delete product"+title+"?")
.setPositiveButton("DELETE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//delete
deleteProduct(id);
}
}).setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//cancel dialog dismiss
dialog.dismiss();
}
})
.show();
}
});
//back btn
backBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//dismiss bottom sheet
bottomSheetDialog.dismiss();
}
});
}
private void deleteProduct(String id) {
//delete product with string id
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Sellers");
reference.child(firebaseAuth.getUid()).child("products").child(id).removeValue()
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(context, "Product Deleted...", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
//failed deleting product
Toast.makeText(context, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return productList.size();
}
#Override
public Filter getFilter() {
if (filter == null){
filter = new FilterProduct(this,filterList);
}
return filter;
}
class HolderProductSeller extends RecyclerView.ViewHolder{
/* holds view of recycler view */
private ImageView productIconIv,nextIv;
private TextView discountNoteTv,titleTv,quantityTv,
discountPriceTv,priceTv;
public HolderProductSeller(#NonNull View itemView) {
super(itemView);
productIconIv = itemView.findViewById(R.id.productIconIv);
nextIv = itemView.findViewById(R.id.nextIv);
discountNoteTv = itemView.findViewById(R.id.discountNoteTv);
titleTv = itemView.findViewById(R.id.titleTv);
quantityTv = itemView.findViewById(R.id.quantityTv);
quantityTv = itemView.findViewById(R.id.quantityTv);
discountPriceTv = itemView.findViewById(R.id.discountPriceTv);
priceTv = itemView.findViewById(R.id.priceTv);
}
}
}
When I clicked any items in the appFirebase showing the crashes closed an exception error occursLogcat showing Crashes

Sub total of recycler view nodes keeps increasing in android app

MY ORIGINAL QUESTION
I am making an android app with firebase Realtime database. I am getting sum of the firebase nodes in side recycler view. I have a text view out side the recycler view where I am getting the sub total of the values of the recycler view. MY PROBLEM is that I cannot get the actual sum and also the sum keeps increasing when I scroll up and down. Here is my Main activity JAVA code:
public class MainActivity extends AppCompatActivity {
FirebaseDatabase myfire;
DatabaseReference myRef;
private FirebaseRecyclerOptions<entry> options;
int totalEarned = 0;
int totalSpent = 0;
int totalSaved=0;
#Override
public void onBackPressed() {
final AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
dialog.setTitle("Are you sure to exit?");
dialog.setPositiveButton("Play", (dialog1, which) -> {
});
dialog.setNegativeButton("Exit", (dialog12, which) -> {
FirebaseAuth.getInstance().signOut();
MainActivity.this.finish();
});
dialog.show();
}
private String getUID() {
FirebaseUser mUser = FirebaseAuth.getInstance().getCurrentUser();
if (mUser != null) {
String strUID = mUser.getUid();
if (!TextUtils.isEmpty(strUID)) {
return strUID;
}
}
return "";
}
#SuppressLint("SetTextI18n")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//==============
final RecyclerView userlist = (RecyclerView) findViewById(R.id.idRecycleView);
myfire = FirebaseDatabase.getInstance();
userlist.setLayoutManager(new LinearLayoutManager(this));
//==================
final TextView tvTotalIncome = findViewById(R.id.idTotalIncome);
final TextView tvTotalExpanse = findViewById(R.id.idTotalExpanse);
final TextView tvTotalSaved = findViewById(R.id.idTotalSaved);
//==================
final FloatingActionButton btnBudget = findViewById(R.id.idCreateBudget);
myfire = FirebaseDatabase.getInstance();
final String strUID = getUID();
if (TextUtils.isEmpty(strUID)) {
//handle case of null UID
}
final Intent i = getIntent();
final String month = Objects.requireNonNull(i.getExtras()).getString("Month");
//-------------------------------
btnBudget.setOnClickListener(v -> {
Intent o;
o = new Intent(MainActivity.this, AddBudgetActivity.class);
o.putExtra("Month",month);
startActivity(o);
finish();
});
if (type.equals("Income")) {
try {
totalEarned = (totalEarned+sum);
} catch (NumberFormatException ex) {
}
tvTotalIncome.setText("-)"+String.valueOf( totalEarned));
holder.btnIcon.setBackgroundResource(R.drawable.circlegreen);
holder.tvEntry.setText("(+)"+String.valueOf(sum) );
try {
totalSaved = (totalEarned-totalSpent);
} catch (NumberFormatException ex) {
}
tvTotalSaved.setText("(=)"+String.valueOf( totalSaved));
}else if (type.equals("Expanse")) {
try {
totalSpent = (totalSpent+sum);
} catch (NumberFormatException ex) {
}
tvTotalExpanse.setText("-)"+String.valueOf( totalSpent));
holder.btnIcon.setBackgroundResource(R.drawable.circlered);
holder.tvEntry.setText("(-)"+String.valueOf(sum) );
try {
totalSaved = (totalEarned-totalSpent);
} catch (NumberFormatException ex) {
}
tvTotalSaved.setText("(=)"+String.valueOf( totalSaved));
}else {
Toast.makeText(MainActivity.this, " Something Went Wrong !", Toast.LENGTH_SHORT).show();
}
//======================
myRef = myfire.getReference().child("Data").child(strUID).child(month);
//-------------------------
options = new FirebaseRecyclerOptions.Builder<entry>()
.setQuery(myRef, entry.class)
.build();
final FirebaseRecyclerAdapter<entry, holder_menu> adapter = new FirebaseRecyclerAdapter<entry, holder_menu>(options) {
#Override
protected void onBindViewHolder(#NonNull #NotNull holder_menu holder, final int i, #NonNull #NotNull entry model) {
final String title = getRef(i).getKey();
assert title != null;
myRef = myfire.getReference().child("Data").child(strUID).child(month).child(title).child("Budget");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
int budget = 0;
if (dataSnapshot.getValue() == null) {
Toast.makeText(getApplicationContext(), "Data Not Available", Toast.LENGTH_LONG).show();
} else {
final String stData1 = (Objects.requireNonNull(dataSnapshot.child("stData1").getValue())).toString();
final String stData2 = (Objects.requireNonNull(dataSnapshot.child("stData2").getValue())).toString();
final String stData3 = (Objects.requireNonNull(dataSnapshot.child("stData3").getValue())).toString();
final String stData4 = (Objects.requireNonNull(dataSnapshot.child("stData4").getValue())).toString();
entry basic = new entry(stData1, stData2, stData3, stData4);
String first = stData2.substring(0, 1);
holder.btnIcon.setText(first);
holder.tvHead.setText(stData2);
String type;
type=(stData3);
holder.tvBudget.setText("#" + stData4);
int amount = 0;
//important line
try {
amount = (Integer.parseInt(stData4));
} catch (NumberFormatException ex) {
}
//======================
budget = amount;
myRef = myfire.getReference().child("Data").child(strUID).child(month).child(title).child("Entry");
final int finalBudget = budget;
myRef.addValueEventListener(new ValueEventListener() {
int sum = 0;
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
String section = data.child("stData2").getValue(String.class);
String value = data.child("stData4").getValue(String.class);
assert value != null;
int total = 0;
//important line
try {
total = (Integer.parseInt(value));
} catch (NumberFormatException ex) {
}
//======================
sum = sum + total;
//==============
//======================
if (section.equals("Saving")) {
holder.tvHead.setBackgroundColor(getResources().getColor(R.color.saving));
}else if (section.equals("Paying")) {
holder.tvHead.setBackgroundColor(getResources().getColor(R.color.paying));
}else if (section.equals("Using")) {
holder.tvHead.setBackgroundColor(getResources().getColor(R.color.using));
}else if (section.equals("Earning")) {
holder.tvHead.setBackgroundColor(getResources().getColor(R.color.earning));
}else if (section.equals("Taking")) {
holder.tvHead.setBackgroundColor(getResources().getColor(R.color.taking));
}else if (section.equals("Drawing")) {
holder.tvHead.setBackgroundColor(getResources().getColor(R.color.drawing));
}else {
Toast.makeText(MainActivity.this, " Something Went Wrong !", Toast.LENGTH_SHORT).show();
}
}
holder.tvEntry.setText("(+)" + String.valueOf(sum) );
holder.tvBalance.setText("(=)" + String.valueOf(finalBudget - sum) );
//important line
holder.btnView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent o;
o = new Intent(MainActivity.this, ViewHistoryActivity.class);
o.putExtra("Title", title);
o.putExtra("Month", month);
o.putExtra("Type", type);
startActivity(o);
finish();
}
});
holder.btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (type.equals("Income")) {
Intent o;
o = new Intent(MainActivity.this, EntryIncomeActivity.class);
o.putExtra("Title", title);
o.putExtra("Month", month);
o.putExtra("Type", type);
startActivity(o);
finish();
}else if (type.equals("Expanse")) {
Intent o;
o = new Intent(MainActivity.this, EntryExpanseActivity.class);
o.putExtra("Title", title);
o.putExtra("Month", month);
o.putExtra("Type", type);
startActivity(o);
finish();
}else {
Toast.makeText(MainActivity.this, " Something Went Wrong !", Toast.LENGTH_SHORT).show();
}
}
});
if (type.equals("Income")) {
try {
totalEarned = (totalEarned+sum);
} catch (NumberFormatException ex) {
}
tvTotalIncome.setText("-)"+String.valueOf( totalEarned));
holder.btnIcon.setBackgroundResource(R.drawable.circlegreen);
holder.tvEntry.setText("(+)"+String.valueOf(sum) );
try {
totalSaved = (totalEarned-totalSpent);
} catch (NumberFormatException ex) {
}
tvTotalSaved.setText("(=)"+String.valueOf( totalSaved));
}else if (type.equals("Expanse")) {
try {
totalSpent = (totalSpent+sum);
} catch (NumberFormatException ex) {
}
tvTotalExpanse.setText("-)"+String.valueOf( totalSpent));
holder.btnIcon.setBackgroundResource(R.drawable.circlered);
holder.tvEntry.setText("(-)"+String.valueOf(sum) );
try {
totalSaved = (totalEarned-totalSpent);
} catch (NumberFormatException ex) {
}
tvTotalSaved.setText("(=)"+String.valueOf( totalSaved));
}else {
Toast.makeText(MainActivity.this, " Something Went Wrong !", Toast.LENGTH_SHORT).show();
}
//======================
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException(); // never ignore errors
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException(); // never ignore errors
}
});
}
#NonNull
#Override
public holder_menu onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item1, parent, false);
return new holder_menu(v);
}
};
adapter.startListening();
userlist.setAdapter(adapter);
}
}
EDITED QUESTION As per #androidLearner 's suggestion
MAIN ACTIVITY
public class MainActivity extends AppCompatActivity {
FirebaseDatabase myfire;
DatabaseReference myRef;
int totalEarned = 0;
int totalSpent = 0;
int totalSaved=0;
madapter adapter;
String iconsData;
String headsData;
int budgetsData=0;
int enteriesData=0;
int balancesData=0;
#Override
public void onBackPressed() {
final AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
dialog.setTitle("Are you sure to exit?");
dialog.setPositiveButton("Play", (dialog1, which) -> {
});
dialog.setNegativeButton("Exit", (dialog12, which) -> {
FirebaseAuth.getInstance().signOut();
MainActivity.this.finish();
});
dialog.show();
}
private String getUID() {
FirebaseUser mUser = FirebaseAuth.getInstance().getCurrentUser();
if (mUser != null) {
String strUID = mUser.getUid();
if (!TextUtils.isEmpty(strUID)) {
return strUID;
}
}
return "";
}
#RequiresApi(api = Build.VERSION_CODES.N)
#SuppressLint("SetTextI18n")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//==============
final RecyclerView userlist = (RecyclerView) findViewById(R.id.idRecycleView);
myfire = FirebaseDatabase.getInstance();
userlist.setLayoutManager(new LinearLayoutManager(this));
//==================
final TextView tvTotalIncome = findViewById(R.id.idTotalIncome);
final TextView tvTotalExpanse = findViewById(R.id.idTotalExpanse);
final TextView tvTotalSaved = findViewById(R.id.idTotalSaved);
//==================
final FloatingActionButton btnBudget = findViewById(R.id.idCreateBudget);
myfire = FirebaseDatabase.getInstance();
final String strUID = getUID();
if (TextUtils.isEmpty(strUID)) {
//handle case of null UID
}
final Intent i = getIntent();
final String month = Objects.requireNonNull(i.getExtras()).getString("Month");
//-------------------------------
btnBudget.setOnClickListener(v -> {
Intent o;
o = new Intent(MainActivity.this, AddBudgetActivity.class);
o.putExtra("Month",month);
startActivity(o);
finish();
});
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&---new method
myRef = myfire.getReference().child("Data").child(strUID).child(month);
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
String title = dataSnapshot.getKey();
assert title != null;
myRef = myfire.getReference().child("Data").child(strUID).child(month).child(title).child("Budget");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() == null) {
Toast.makeText(getApplicationContext(), "Data Not Available", Toast.LENGTH_LONG).show();
} else {
final String stData1 = (Objects.requireNonNull(dataSnapshot.child("stData1").getValue())).toString();
final String stData2 = (Objects.requireNonNull(dataSnapshot.child("stData2").getValue())).toString();
final String stData3 = (Objects.requireNonNull(dataSnapshot.child("stData3").getValue())).toString();
final String stData4 = (Objects.requireNonNull(dataSnapshot.child("stData4").getValue())).toString();
entry basic = new entry(stData1, stData2, stData3, stData4);
iconsData = stData2.substring(0, 1);
headsData=stData2;
//---------------------------------------------------------------------------entry
myRef = myfire.getReference().child("Data").child(strUID).child(month).child(title).child("Entry");
myRef.addValueEventListener(new ValueEventListener() {
int sum = 0;
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
String section = data.child("stData2").getValue(String.class);
String value = data.child("stData4").getValue(String.class);
assert value != null;
int total = 0;
try {
total=(Integer.parseInt(value));
} catch (NumberFormatException ex) {
}
//==============
sum=sum+total;
}
enteriesData=sum;
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException(); // never ignore errors
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException(); // never ignore errors
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException(); // never ignore errors
}
});
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&------NewMethod
balancesData=budgetsData-enteriesData;
ArrayList<String> iconList = new ArrayList<>();
iconList.add(iconsData);
ArrayList<String> headList= new ArrayList<>();
headList.add(headsData);
ArrayList<Integer> budgetList = new ArrayList<>();
budgetList.add(budgetsData);
ArrayList<Integer> entryList = new ArrayList<>();
entryList.add(enteriesData);
ArrayList<Integer> balanceList = new ArrayList<>();
balanceList.add(balancesData);
adapter = new madapter ( this, iconList,headList,budgetList,entryList,balanceList);
userlist.setAdapter(adapter);
}
}
RECYCLER VIEW Adapter
public class madapter extends RecyclerView.Adapter<madapter.ViewHolder> {
private List<String> stricon;
private List<String> strhead;
private List<Integer> intbudget;
private List<Integer> intentry;
private List<Integer> intbalance;
//---
private LayoutInflater mInflater;
private ItemClickListener mClickListener;
// data is passed into the constructor
public madapter(MainActivity mainActivity, ArrayList<String> iconList, ArrayList<String> headList, ArrayList<Integer> budgetList, ArrayList<Integer> entryList, ArrayList<Integer> balanceList) {
this.mInflater = LayoutInflater.from(mainActivity);
this.stricon = iconList;
this.strhead = headList;
this.intbudget = budgetList;
this.intentry = entryList;
this.intbalance= balanceList;
}
// inflates the row layout from xml when needed
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.item1, parent, false);
return new ViewHolder(view);
}
// binds the data to the TextView in each row
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
String icons = stricon.get(position);
String heads = strhead.get(position);
int budgets = intbudget.get(position);
int entries = intentry.get(position);
int balances = intbalance.get(position);
holder.btnIcon.setText(icons);
holder.tvHead.setText(heads);
holder.tvBudget.setText(String.valueOf(budgets));
holder.tvEntry.setText(String.valueOf(entries));
holder.tvBalance.setText(String.valueOf(balances));
}
// total number of rows
#Override
public int getItemCount() {
return stricon.size();
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public Button btnIcon;
public TextView tvHead;
public TextView tvBudget;
public TextView tvEntry;
public TextView tvBalance;
public Button btnView;
public Button btnAdd;
ViewHolder(View itemView) {
super(itemView);
btnIcon= (Button) itemView.findViewById(R.id.idIcon);
tvHead = (TextView) itemView.findViewById(R.id.idHead);
tvBudget = (TextView) itemView.findViewById(R.id.idBudget);
tvEntry = (TextView) itemView.findViewById(R.id.idEntry);
tvBalance = (TextView) itemView.findViewById(R.id.idBalance);
btnView= (Button) itemView.findViewById(R.id.idView);
btnAdd = (Button) itemView.findViewById(R.id.idAdd);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
// convenience method for getting data at click position
String getItem(int id) {
return stricon.get(id);
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}
THE NEW PROBLEM AFTER EDITING
I am not able to get any data from firebase to my array list by the method datasnapshot. But yes my recycler view shows data if I add hardcore text or numbers to my list manually.
This is the crash report
2021-05-24 00:07:12.368 19933-19933/com.myappname E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.myappname, PID: 19933
java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
at java.util.ArrayList.get(ArrayList.java:437)
at com.myappname.model.rvAdapter.onBindViewHolder(mAdapter.java:54)
at com.myappname.model.rvAdapter.onBindViewHolder(mAdapter.java:16)2021-05-24 .......................................
set Adapter after got data from firebase
myRef.addValueEventListener(new ValueEventListener() {
int sum = 0;
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
String section = data.child("stData2").getValue(String.class);
String value = data.child("stData4").getValue(String.class);
assert value != null;
int total = 0;
//==============
sum=sum+total;
}
enteriesData=sum;
//Send your data to adapter as per your need from here
adapter = new madapter ( this, iconList,headList,budgetList,entryList,balanceList);
userlist.setAdapter(adapter);
}

First and last switch button getting triggred in recycler view

Hi I have switch button (switchTaskFinished) on my recycler view,when I am clicking any button, the last button is getting selected. Also when I press button it updates the data to firebase. And changes the button status accordingly. But even though buttons value is true it only updates last button status not others.
public class MyAdaptorUser extends RecyclerView.Adapter<MyAdaptorUser.myViewHolder> {
private Context context;
private ArrayList<TaskModel> taskLists;
private Switch switchTaskFinished;
private OnTaskClickListner mTaskListner;
private AlertDialog dialog;
private AlertDialog.Builder builder;
private TaskConfirmationSender taskConfirmationSender;
public MyAdaptorUser(Context c, ArrayList<TaskModel> t, OnTaskClickListner onTaskClickListner) {
context = c;
taskLists = t;
this.mTaskListner = onTaskClickListner;
}
#NonNull
#Override
public MyAdaptorUser.myViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
builder = new AlertDialog.Builder(parent.getContext());
builder.setTitle("Please Wait").setView(R.layout.my_progress_view).setCancelable(false);
dialog = builder.create();
return new MyAdaptorUser.myViewHolder(LayoutInflater.from(context).inflate(R.layout.task_preview, parent, false), mTaskListner);
}
#Override
public void onBindViewHolder(#NonNull MyAdaptorUser.myViewHolder holder, final int position) {
//Set title and description to task preview textviews
holder.title.setText(taskLists.get(position).getTaskTitle());
holder.dueDate.setText(taskLists.get(position).getDueDate());
holder.description.setText(taskLists.get(position).getTaskDescription());
//Sets the path of database to taskAwatingConfirmation/task_title/UserEmail
final DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference();
try {
String email = FirebaseAuth.getInstance().getCurrentUser().getEmail();
email = removeSpecialCharacter(email);
final DatabaseReference taskConfirmationRef = dbRef
.child("taskAwatingConfirmation")
.child(taskLists.get(position).getTaskTitle())
.child(email);
taskConfirmationRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//Fetching switchButton Status (Task finished) from database
switchTaskFinished.setChecked(false);
String buttonStatus = (String) dataSnapshot.child("buttonStatus").getValue();
if (buttonStatus != null) {
Log.d("taskerror", buttonStatus);
if (buttonStatus.equals("true")) {
switchTaskFinished.setChecked(true);
} else if (buttonStatus.equals("false")) {
switchTaskFinished.setChecked(false);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
switchTaskFinished.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(final CompoundButton buttonView, boolean isChecked) {
//dialog = builder.show();
taskConfirmationSender = new TaskConfirmationSender();
//When Task Finished button is clicked send data to database
sendConfirmationToAdmin(new FirebaseCallBack() {
#Override
public void Callback(TaskConfirmationSender taskConfirmationSender) {
taskConfirmationSender.setButtonStatus(String.valueOf(buttonView.isChecked()));
taskConfirmationSender.setTaskDueDate(taskLists.get(position).getDueDate());
if (buttonView.isChecked()) {
taskConfirmationRef.setValue(taskConfirmationSender).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
dialog.dismiss();
}
});
}else{
taskConfirmationRef.setValue(taskConfirmationSender).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
dialog.dismiss();
}
});
}
}
});
}
});
} catch (NullPointerException ignored) {
dialog.dismiss();
}
}
private String removeSpecialCharacter(String email) {
StringBuffer sbf = new StringBuffer(email);
email = String.valueOf(sbf.reverse());
int length = email.length();
email = email.substring(4, length);
StringBuffer stringBuffer = new StringBuffer(email);
email = String.valueOf(stringBuffer.reverse());
return email.replace("#", "_");
}
private void sendConfirmationToAdmin(final FirebaseCallBack firebaseCallBack) {
DatabaseReference volunteerRef = FirebaseDatabase.getInstance().getReference()
.child("Volunteer").child("Member")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
taskConfirmationSender = new TaskConfirmationSender();
try {
//Fetching details of users (full name, email) from database and setting their value to taskConfirmation Object
volunteerRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String userName = dataSnapshot.child("fullName").getValue().toString();
String userEmail = dataSnapshot.child("email").getValue().toString();
String userId = dataSnapshot.getKey();
//TODO: Fetch UID of user and set it to taskConfirmation OBject
taskConfirmationSender.setUserEmail(userEmail);
taskConfirmationSender.setUserName(userName);
taskConfirmationSender.setId(userId);
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
String submissionDate = day + "/" + month + "/" + year;
taskConfirmationSender.setSubmissionDate(submissionDate);
firebaseCallBack.Callback(taskConfirmationSender);
/**/
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
} catch (NullPointerException ee) {
}
}
private interface FirebaseCallBack {
void Callback(TaskConfirmationSender taskConfirmationSender);
}
#Override
public int getItemCount() {
return taskLists.size();
}
class myViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView title, dueDate, description;
OnTaskClickListner onTaskClickListner;
public myViewHolder(#NonNull View itemView, OnTaskClickListner onTaskClickListner) {
super(itemView);
title = itemView.findViewById(R.id.taskTitle);
dueDate = itemView.findViewById(R.id.taskDueDate);
description = itemView.findViewById(R.id.taskDescription);
switchTaskFinished = itemView.findViewById(R.id.switchTaskFinished);
this.onTaskClickListner = onTaskClickListner;
ConstraintLayout taskBar = itemView.findViewById(R.id.linearLayoutTaskBar);
itemView.setOnClickListener(this);
//hides delete task button
taskBar.setVisibility(View.GONE);
}
#Override
public void onClick(View v) {
onTaskClickListner.onTaskClick(getAdapterPosition());
}
}
public interface OnTaskClickListner {
void onTaskClick(int position);
}
}
Maybe its because of the valueEventListener that stays attached:
Instead of this:
taskConfirmationRef.addValueEventListener(new ValueEventListener() {.........
Do this:
taskConfirmationRef.addListenerForSingleValueEvent(new ValueEventListener() {......
And set the switch to checked or unchecked when you turn on or off:
if (buttonView.isChecked()) {
//here
switchTaskFinished.setChecked(true);
taskConfirmationRef.setValue(taskConfirmationSender).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
dialog.dismiss();
}
});
}else{
//here
switchTaskFinished.setChecked(false);
...................

How to upload multiple images to firebase database and retrieve

How to store all images in Firebase database under at index values.
This is sample screenshot of my firebase database structure
This is my photos uploading class but images are storing using single id and single image url only. How to upload multiple images to firebase database and retrieve . Please Help me and im new to firebase database multiple images uploading.
public class PhotoUploadActivity extends AppCompatActivity implements View.OnClickListener {
private String mListID,mInspectionID;
private FirebaseStorage firebaseStorage;
private StorageReference storageReference;
private Button openCustomGallery;
private Button mUploadPhoto;
private GridView selectedImageGridView;
private static final int CustomGallerySelectId = 1;//Set Intent Id
public static final String CustomGalleryIntentKey = "ImageArray";//Set Intent Key Value
private List<String> selectedImages;
private GalleryAdapter adapter;
private String imagesArray;
private String timestampString;
private String formattedTimestamp;
private Long timestamp;
private int failUplaod;
private int successUpload;
private ProgressDialog uploadProgress;
private String pathPhoto;
private String remarkPhoto;
private int currentprogress;
private ImageView currentImage;
private String mTestID;
private ArrayList<String > blogimages;
private String mKeyID, mAddress, mLocationKey, mRegion;
private HashMap<String,Object> photos = new HashMap<>();
private HashMap<String, String> metadata = new HashMap<>();
public static boolean loaded = false;
StorageReference mstorageReference;
DatabaseReference mdatabaseReference;
FirebaseAuth firebaseAuth;
DatabaseReference userdatabaseReference;
EditText desc;
Button upload;
private ProgressDialog mProgressbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_selected);
setTitle("Write Post");
mProgressbar = new ProgressDialog(this);
initViews();
setListeners();
mstorageReference = FirebaseStorage.getInstance().getReference();
mdatabaseReference = FirebaseDatabase.getInstance().getReference().child("Blog");
firebaseAuth = FirebaseAuth.getInstance();
userdatabaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child(firebaseAuth.getCurrentUser().getUid());
upload = (Button)findViewById(R.id.new_post_submit);
desc = (EditText)findViewById(R.id.new_post_text);
upload.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
UploadTask uploadTask;
if( selectedImageGridView.getChildCount()!= 0)
{
blogimages = new ArrayList<>();
mProgressbar.setMessage("Post Uploading_Please Wait.....");
mProgressbar.show();
for ( int i = 0; i < selectedImages.size(); i++) {
Uri uri = Uri.parse("file://"+selectedImages.get(i));
Log.v("URIIII", String.valueOf(uri));
final String CurrentUser = firebaseAuth.getCurrentUser().getUid();
StorageReference reference = mstorageReference.child("Blog_pics/users").child(uri.getLastPathSegment());
uploadTask = reference.putFile(uri);
uploadTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
//todo: if want to make this the full progress bar, just need to make this as the sum of all progress and add to the main progress dialog
double progress = (100.0 * (taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount());
mProgressbar.setMessage("Uploading Images.....");
mProgressbar.show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
final Uri downloaduri = taskSnapshot.getDownloadUrl();
Log.v("DOWNLOAD URI", String.valueOf(downloaduri));
blogimages.add(downloaduri.toString());
Log.v("BLOGGIMAGES", String.valueOf(blogimages));
// final String path= uri.getLastPathSegment();
final String key = mdatabaseReference.push().getKey();
final String posttitle = desc.getText().toString();
final String CurrentUser = firebaseAuth.getCurrentUser().getUid();
userdatabaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date today = Calendar.getInstance().getTime();
final String current_time = df.format(today);
Blog blog = new Blog();
long millis = System.currentTimeMillis();
int timestamp = ((int) (millis/1000))* -1;
blog.setTimestamp(current_time);
blog.setTime(timestamp);
blog.setTitle(posttitle);
blog.setUrl(blogimages);
blog.setUid(firebaseAuth.getCurrentUser().getUid());
blog.setUsername(dataSnapshot.child("name").getValue().toString());
blog.setImage(dataSnapshot.child("image").getValue().toString());
mdatabaseReference.child(key).setValue(blog) .addOnSuccessListener(new OnSuccessListener<Void>()
{
#Override
public void onSuccess(Void aVoid)
{
Intent mm = new Intent(PhotoUploadActivity.this, MainActivity.class);
startActivity(mm);
}
}).addOnFailureListener(new OnFailureListener()
{
#Override
public void onFailure(#NonNull Exception e)
{
Toast.makeText(PhotoUploadActivity.this,"Failed to post the blog.. Try again later",Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onCancelled(DatabaseError error) {
}
});
}
}) .addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Toast.makeText(getApplicationContext(), exception.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}else
{
Toast.makeText(PhotoUploadActivity.this,"Please enter all fields and Select images.",Toast.LENGTH_LONG).show();
}
}
});
selectedImageGridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
AlertDialog.Builder deleteDialog = new AlertDialog.Builder(PhotoUploadActivity.this)
.setTitle("Delete Item?")
.setMessage("Do you want to remove this item?")
.setNegativeButton("No", null)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
adapter.removeitem(position);
adapter.notifyDataSetChanged();
/*Or you can do it this way if the top one doesnt work:
selectedImageGridView.setAdapter(null);*/
}
});
deleteDialog.create().show();
return true;
}
});
}
private void initViews() {
openCustomGallery = (Button) findViewById(R.id.openCustomGallery);
selectedImageGridView = (GridView) findViewById(R.id.selectedImagesGridView);
// mUploadPhoto = (Button) findViewById(R.id.UploadPhotos);
}
//set Listeners
private void setListeners() {
openCustomGallery.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.openCustomGallery:
//Start Custom Gallery Activity by passing intent id
Intent intent = new Intent(PhotoUploadActivity.this, CustomGalleryActivity.class);
startActivityForResult(intent, CustomGallerySelectId);
break;
}
}
#Override
protected void onActivityResult(int requestcode, int resultcode, Intent imagereturnintent) {
super.onActivityResult(requestcode, resultcode, imagereturnintent);
switch (requestcode) {
case CustomGallerySelectId:
if (resultcode == RESULT_OK) {
imagesArray = imagereturnintent.getStringExtra(CustomGalleryIntentKey);//get Intent data
//Convert string array into List by splitting by ',' and substring after '[' and before ']'
selectedImages = Arrays.asList(imagesArray.substring(1, imagesArray.length() - 1).split(", "));
//loadGridView(new ArrayList<String>(selectedImages));//call load gridview method by passing converted list into arrayList
adapter = new GalleryAdapter(PhotoUploadActivity.this,new ArrayList<>(selectedImages),false);
selectedImageGridView.setAdapter(adapter);
}
break;
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
//I'm saving the instance state of photos.. let's see how
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable("Photos",photos);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
savedInstanceState.getSerializable("Photos");
}
}
To solve this, store the image urls in a Map. Your database structure should look like this:
Firebase-root
|
--- Blog
|
--- blogId
|
--- urls
| |
| --- "https://firebasestorage...": true
| |
| --- "https://firebasestorage...": true
|
--- //the other blog details
To display all those images, just get the urls object, which is a map and iterate to get the keys which are actual the urls of your photos.
Edit:
There is also an alternative structure which looks like this:
Firebase-root
|
--- Blog
|
--- blogId
|
--- urls
| |
| --- pushedKeyOne: "https://firebasestorage..."
| |
| --- pushedKeyTwo: "https://firebasestorage..."
|
--- //the other blog details

Increment the value of an Int using a button from a custom listview layout

I have recently managed to make a custom listview layout and populate that data from a listview.
The listview contains a "Like" Button and a textview storing the amount of likes. Yet i cant seem to figure out how to take that int and increment it on button press as the will be performed in the CustomAdapter.
Data Model:
public class MessagesListDataModel {
private String uid;
private String msg;
private String likes;
private String date;
private Button like;
private Button reply;
public MessagesListDataModel(String uid, String msg, String date) {
this.uid = uid;
this.msg = msg;
this.date = date;
this.likes = likes;
}
public MessagesListDataModel(){
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getLikes() {
return likes;
}
public void setLikes(String likes) {
this.likes = likes;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public Button getLike() {
return like;
}
public void setLike(Button like) {
this.like = like;
}
}
The Adapter:
public class MessagesListAdapter extends ArrayAdapter<MessagesListDataModel> {
private ArrayList<MessagesListDataModel> dataModels;
public MessagesListAdapter(Context context, ArrayList<MessagesListDataModel> dataModels){
super(context,0, dataModels);
this.dataModels = dataModels;
}
/*
* we are overriding the getView method here - this is what defines how each
* list item will look.
*/
public View getView(int position, View convertView, ViewGroup parent){
MessagesListDataModel messagesListDataModel = dataModels.get(position);
// first check to see if the view is null. if so, we have to inflate it.
// to inflate it basically means to render, or show, the view.
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.chat_messages_layout, parent, false);
}
TextView uid = (TextView) convertView.findViewById(R.id.textViewUserID);
TextView message = (TextView) convertView.findViewById(R.id.textViewMessage);
TextView likes = (TextView) convertView.findViewById(R.id.textViewLikes);
TextView date = (TextView) convertView.findViewById(R.id.textViewDateTime);
Button like = (Button) convertView.findViewById(R.id.buttonLike);
Button reply = (Button) convertView.findViewById(R.id.buttonReply);
uid.setText(messagesListDataModel.getUid());
message.setText(messagesListDataModel.getMsg());
date.setText(messagesListDataModel.getDate());
likes.setText(messagesListDataModel.getLikes());
like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast toast = Toast.makeText(getContext(), "Like button pressed", Toast.LENGTH_SHORT);
toast.show();
//Increment the value of the likes textview and reload that textview to display new likes. Limit the likes to only be able to like a post once.
}
});
reply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast toast = Toast.makeText(getContext(), "reply button pressed", Toast.LENGTH_SHORT);
toast.show();
//passing data for the reference in the replies class.
}
});
return convertView;
}
}
In the like.SetOnClickListener, how can i retrieve data from firebase database stored as "likes", update the int by adding 1 and store it back into the database?
Can this even be done in the adapter or does this need to take place in the "main activity" of where the data gets populated? Im not sure how to go about this.
Also another problem is that the textviews dont accept Int's so i need to be converting from string to int and back when doing this?
Main Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_room);
//for sending messages to database
btn_send_msg = (Button) findViewById(R.id.btn_send);
input_msg = (EditText) findViewById(R.id.msg_Input);
//Date time
//DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
//dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
//Date date = new Date();
//String dtSent = ((dateFormat.format(date).toString()));
//UserData student ID
FirebaseUser loggedinFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
String userId = loggedinFirebaseUser.getUid();
room_name = getIntent().getExtras().get("room_name").toString();
setTitle(" Room - " + room_name);
//stores the reference as a string to be passed onto the userDataReference table
databaseUrlRef = "users/userData" + "/" + userId;
userDataRef = FirebaseDatabase.getInstance().getReference(databaseUrlRef + "/SID");
chatroomsref = FirebaseDatabase.getInstance().getReference("Chatrooms").child(room_name);
///////
final MessagesListAdapter arrayAdapter = new MessagesListAdapter(this,arrayMessages);
ListViewMessages = (ListView) findViewById(R.id.chatRoomMessagesListview);
ListViewMessages.setAdapter(arrayAdapter);
chatroomsref.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
//fetchData();
//for (DataSnapshot child : dataSnapshot.getChildren()) {
MessagesListDataModel messagesListDataModel =
dataSnapshot.getValue(MessagesListDataModel.class);
arrayMessages.add(messagesListDataModel);
arrayAdapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
/////
//reference to the database that is within the chatrooms and the room name of the name that was clicked and passed onto this activity.
root = FirebaseDatabase.getInstance().getReference("Chatrooms/" + room_name);
userDataRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String Name = dataSnapshot.getValue().toString();
user_name = Name;
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
//https://stackoverflow.com/questions/40891268/how-to-get-firebase-data-into-a-listview
btn_send_msg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Date date = new Date();
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String dtSent = ((dateFormat.format(date).toString()));
Map<String, Object> map = new HashMap<String, Object>();
temp_key = root.push().getKey();
// temp key is the randomly generated key
root.updateChildren(map);
DatabaseReference message_root = root.child(temp_key);
Map<String, Object> map2 = new HashMap<String, Object>();
map2.put("uid", user_name);
map2.put("msg", input_msg.getText().toString());
map2.put("likes","0");
map2.put("date",dtSent);
message_root.updateChildren(map2);
input_msg.setText("");
}
});
}
}
What im mainly looking for is how could i access this(Chatrooms/RoomName/UNIQUE_ID/likes) as structured in the database, and update it. Where the Unique id is an actual unique id.
FATAL EXCEPTION: main
Process: com.brunelcs.group13.anyquestions, PID: 8808
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference
at com.brunelcs.group13.anyquestions.ChatRoom$1.onButtonClick(ChatRoom.java:87)
at com.brunelcs.group13.anyquestions.MessagesListAdapter$1.onClick(MessagesListAdapter.java:81)
at android.view.View.performClick(View.java:6256)
at android.view.View$PerformClick.run(View.java:24697)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Toast toast = Toast.makeText(getApplicationContext(), getPostKey.toString(), Toast.LENGTH_SHORT);
toast.show();
that i put after getPostKey,
and the other one:
if (btnClickListener != null)
btnClickListener.onButtonClick((Integer) view.getTag());}
Also the arrayAdapter had to be changed to this as it was comming up with errors:
final MessagesListAdapter arrayAdapter = new MessagesListAdapter(this, arrayMessages, new MessagesListAdapter.ButtonClickListener() {}
This is how i am posting the data into firebase:
btn_send_msg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Date date = new Date();
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String dtSent = ((dateFormat.format(date).toString()));
Map<String, Object> map = new HashMap<String, Object>();
temp_key = root.push().getKey();
// temp key is the randomly generated key
root.updateChildren(map);
DatabaseReference message_root = root.child(temp_key);
Map<String, Object> map2 = new HashMap<String, Object>();
map2.put("uid", user_name);
map2.put("msg", input_msg.getText().toString());
map2.put("likes","0");
map2.put("date",dtSent);
message_root.updateChildren(map2);
input_msg.setText("");
}
});
As you can see from answer I posted you in comment you can create an interface inside your Adapter class with one void method and int as parametar for example:
public interface ButtonClickListener {
public abstract void onButtonClick(int position);
}
Then use this in constructor of your adapter class so you can override it inside your Activity and preform ButtonClick. For example:
private ButtonClickListener btnClickListener = null;
public MessagesListAdapter(Context context, ArrayList<MessagesListDataModel> dataModels, ButtonClickListener btnClickListener){
super(context,0, dataModels);
this.dataModels = dataModels;
this.btnClickListener = btnClickListener;
}
After that inside your Adapter class setTag on like button and setOnclickListener on it and get the tag. For example:
likes.setTag(position);
likes.setOnClickListener(new View.OnClickListener{
#Override
public void onClick(View v) {
if(btnClickListener != null)
btnClickListener.onButtonClick((Integer) v.getTag());
}
});
When you are done with this you will be able to implement click listener inside your adapter creation in Activity and then inside using position get the key of post and with that key, retrieve how many likes you have on specific post, make increment and set the value again. Create a new getter and setter inside your model class to store key for example:
private String postKey;
public String getPostKey() {
return postKey;
}
public void setPostKey(String postKey) {
this.postKey = postKey;
}
You will need to store the key inside sePostKey so you can get the key from getPostKey. And then you can easily get it from your MessagesListDataModel:
final MessagesListAdapter arrayAdapter = new MessagesListAdapter(this,arrayMessages, new ButtonClickListener(){
#Override
public void onButtonClick(int position) {
String getPostKey = arrayMessages.get(position).getPostKey();
//Now you have a key to run another query to get data from specific post and with that number of likes as well
}
});
Probably process could be simplified or to use some another better approach but this is just an idea how you could achieve what you want. I didn't test this code I hope it will work.

Categories

Resources