How to retrieve an object from firebase database? - java

I'm trying to retrieve an object from an ArrayList in the database but when I'm retrieving it one of the object attributes returns an empty string instead of the string saved in the database, however, the other attributes are returning their values.
The databse image:
getAmount returns the matching string from the database but getFoodName returns an empty string instead of "egg".
reference.child(userId).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
User userProfile=snapshot.getValue(User.class);
if(userProfile!=null)
{
if(userProfile.morning_List!=null)
{
for(int i=0;i<userProfile.morning_List.size();i++)
{
FoodItem foodItem=new FoodItem(userProfile.morning_List.get(i));
mFoodList.add(new FoodItem(foodItem.getFoodName(),foodItem.getAmount()));
}
}
foodItem class
public class FoodItem {
private String fdName;
private String amount;
public FoodItem(String foodName, String foodAmount) {
this.fdName = foodName;
this.amount=foodAmount;
}
public String getFoodName() {
return this.fdName;
}
public String getAmount() {
return this.amount;
}
}
List adapter class:
public class FoodListAdapter extends RecyclerView.Adapter<FoodListAdapter.FoodViewHolder>{
private ArrayList<FoodItem> mFoodList;
public static class FoodViewHolder extends RecyclerView.ViewHolder{
public TextView mFoodName;
public TextView mAmount;
public FoodViewHolder(#NonNull View itemView,final OnItemClickListener listener) {
super(itemView);
mFoodName = itemView.findViewById(R.id.fdName);
mAmount = itemView.findViewById(R.id.amount);
}
}
public FoodListAdapter(ArrayList<FoodItem> foodList) {
mFoodList = foodList;
}
#NonNull
#Override
public FoodListAdapter.FoodViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.food_item, parent, false);
FoodViewHolder evh = new FoodViewHolder(v, mListener);
return evh;
}
#Override
public void onBindViewHolder(#NonNull FoodListAdapter.FoodViewHolder holder, int position) {
FoodItem currentItem = mFoodList.get(position);
holder.mFoodName.setText(currentItem.getFoodName());
holder.mAmount.setText(currentItem.getAmount());
}
#Override
public int getItemCount() {
return mFoodList.size();
}
}

I think this may come from the fact that your field is called fdName, while the property in the database is called foodName.
Firebase uses either the getter and setter to determine the name of the property, or if those are missing, the name of the field. So it's looking for a property called fdName in the database.
The solution is to rename your field to match the property name in the database:
public class FoodItem {
private String foodName; // 👈
private String amount;
public FoodItem(String foodName, String foodAmount) {
this.foodName = foodName;
this.amount=foodAmount;
}
public String getFoodName() {
return this.foodName; // 👈
}
public String getAmount() {
return this.amount;
}
}

Related

Error while displaying data from Firebase Database to RecyclerView

We have been facing this error while our app tries to display data from our Firebase Database. Here is the error shown in logcat:
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.example.projectrefill.retailer_model_datewise_dispwhenpressed
Here is the screenshot of the database where we are trying to display data from
Retailer> Kamath Bakery> r_history > (date_with_time) > (number)> :
Java Class (retailerside_datewisetransaction_Fragment) :
FirebaseRecyclerOptions<retailer_model_datewise_dispwhenpressed> options =
new FirebaseRecyclerOptions.Builder<retailer_model_datewise_dispwhenpressed>()
.setQuery(FirebaseDatabase.getInstance().getReference().child("Retailer").child(username).child("r_history").child(datenew),retailer_model_datewise_dispwhenpressed.class)
.build();
adapter=new adapter_retailerside_datewise_dispoforder(options);
adapter.startListening();
recyclerView.setAdapter(adapter);
Model Class (retailer_model_datewise_dispwhenpressed) :
public class retailer_model_datewise_dispwhenpressed {
String name,price,quan,totalamount,weight;
public retailer_model_datewise_dispwhenpressed() {
}
public retailer_model_datewise_dispwhenpressed(String name, String price, String quan, String totalamount, String weight) {
this.name = name;
this.price = price;
this.quan = quan;
this.totalamount = totalamount;
this.weight = weight;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getQuan() {
return quan;
}
public void setQuan(String quan) {
this.quan = quan;
}
public String getTotalamount() {
return totalamount;
}
public void setTotalamount(String totalamount) {
this.totalamount = totalamount;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
}
Adapter Class (adapter_retailerside_datewise_dispoforder) :
public class adapter_retailerside_datewise_dispoforder extends FirebaseRecyclerAdapter<retailer_model_datewise_dispwhenpressed,adapter_retailerside_datewise_dispoforder.myviewholder> {
public adapter_retailerside_datewise_dispoforder(#NonNull FirebaseRecyclerOptions<retailer_model_datewise_dispwhenpressed> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull myviewholder holder, int position, #NonNull retailer_model_datewise_dispwhenpressed model) {
holder.name.setText("Name: "+model.getName());
holder.price.setText("Price: "+model.getPrice());
holder.quan.setText("Quan: "+model.getQuan());
holder.totprice.setText(model.getTotalamount());
holder.weight.setText("Weight: "+model.getWeight());
}
#NonNull
#Override
public myviewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.single_row_retailer_datewise_whenpressed,parent,false);
return new myviewholder(view);
}
public class myviewholder extends RecyclerView.ViewHolder {
TextView name,price,quan,weight,totprice;
public myviewholder(#NonNull View itemView) {
super(itemView);
name=itemView.findViewById(R.id.datewisename);
price=itemView.findViewById(R.id.datewiseprice);
quan=itemView.findViewById(R.id.datewisequan);
weight=itemView.findViewById(R.id.datewiseweight);
totprice=itemView.findViewById(R.id.totalpricehere);
}
}
}
Since you pass this path to the FirebaseUI adapter:
FirebaseDatabase.getInstance().getReference().child("Retailer").child(username).child("r_history").child(datenew)
Firebase will read each child node under that path and try to create a retailer_model_datewise_dispwhenpressed object out of it.
This works fine for the child 1, as it has the properties that your class has. But then Firebase tries to do the same for Pmode, and that is just a string value, which is not a valid retailer_model_datewise_dispwhenpressed object.
You'll have to ensure that you only have child nodes that are valid retailer_model_datewise_dispwhenpressed objects under the path that you load.

incompatible types: cant compare a class to a native ad

I am new to android studios I am currently changing my FirestoreRecyclerOptions to a regular recycler view because I want to add native ads every 5 posts. The current issue I am facing is that the method getItemViewType what I want it to return is if it's either an ad or regular post using instance of. In the tutorial videos they do something along the line of
#Override
public int getItemViewType(int position) {
if (noteList.get(position) instanceof UnifiedNativeAd) {
return TYPE_AD;
}else {
return TYPE_REG;
}
}
But the condition inside the if statement is giving me this error
error: incompatible types: Note cannot be converted to UnifiedNativeAd
if (noteList.get(position) instanceof UnifiedNativeAd) {
CLASS
public class Note {
public int timestamp;
public List<String> replies;
public String ownerName;
public String ownerId;
public String text;
public String imageURL;
public List<String> usersLiked;
public String message;
public String timePosted;
public int likes;
public int replyCount;
public Note() {
}
public Note(int timestamp, String ownerId, String text, String ownerName, String imageURL, List<String> replies, List<String>
usersLiked, String message, String timePosted, int likes, int replyCount) {
this.timestamp = timestamp;
this.ownerId = ownerId;
this.text = text;
this.ownerName = ownerName;
this.imageURL = imageURL;
this.replies = replies;
this.usersLiked = usersLiked;
this.message = message;
this.timePosted = timePosted;
this.likes = likes;
this.replyCount = replyCount;
}
public int getTime() {
return timestamp;
}
public String getOwnerName() {
return ownerName;
}
public String getId() {
return ownerId;
}
public String getPost() {
return text;
}
public List<String> getreplies() {
return replies;
}
public String getImageURL() {
return imageURL;
}
public List<String> getUsersLiked() {
return usersLiked;
}
public String getMessage() {
return message;
}
public String getTimePosted() {
return timePosted;
}
public int getLikes() {
return likes;
}
public int getReplyCount() {
return replyCount;
}
}
FULL RECYCLERVIEW
ublic class adapterRegular extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final static int TYPE_AD=0;
private final static int TYPE_REG=1;
private Context context;
private List<Note> noteList;
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
context = parent.getContext();
if(viewType == TYPE_AD){
View view = LayoutInflater.from(context).inflate(R.layout.reclyerads,parent,false);
return new AdTemplateViewHolder(view);
}
View view = LayoutInflater.from(context).inflate(R.layout.list_row,parent,false);
return new noteHolder(view);
}
#Override
public int getItemCount() {
return noteList.size();
}
public class noteHolder extends RecyclerView.ViewHolder{
TextView ownerName;
TextView timestamp;
TextView text;
ImageView imageURL;
TextView replies;
TextView likes;
ImageView heart;
public noteHolder(#NonNull View itemView) {
super(itemView);
ownerName = itemView.findViewById(R.id.userName);
timestamp = itemView.findViewById(R.id.time);
text = itemView.findViewById(R.id.post);
imageURL = itemView.findViewById(R.id.profilePic);
replies = itemView.findViewById(R.id.REPLY);
likes = itemView.findViewById(R.id.likes);
heart = itemView.findViewById(R.id.heart);
}
}
public class AdTemplateViewHolder extends RecyclerView.ViewHolder{
TemplateView templateView;
public AdTemplateViewHolder(#NonNull View itemView) {
super(itemView);
templateView = itemView.findViewById(R.id.my_template);
NativeTemplateStyle style = new NativeTemplateStyle.Builder()
.withMainBackgroundColor(new ColorDrawable(Color.parseColor("#FFFFFF"))).build();
templateView.setStyles(style);
}
public void setUnifiedNativeAd(UnifiedNativeAd ads){
templateView.setNativeAd(ads);
}
}
#Override
public int getItemViewType(int position) {
if (noteList.get(position) instanceof UnifiedNativeAd) {
return TYPE_AD;
}else {
return TYPE_REG;
}
}
}
ANY HELP OR SUGGESTION IS APPERCIATED
Change this
private List<Note> noteList;
To this
private List<Object> noteList;

How to update recyclerview data from ItemTouchHelper?

I have a recyclerview of tasks. When user will swipe an element I want to change one parameter(variable "isChecked" from false to true - that will mean the task is completed) in that task.
I created new ItemTouchHelper instance in my activity:
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, #NonNull RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
Sorted current = adapter.getSortedAtPosition(viewHolder.getAdapterPosition());
int time = current.getSortedDuration() + current.getSortedTimeBegin();
int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
int minute = Calendar.getInstance().get(Calendar.MINUTE);
if (hour > time/60){
//change
Toast.makeText(ShowSortedActivity.this, "check1", Toast.LENGTH_SHORT).show();
}
else if (hour == time/60){
if (minute > time % 60){
//change
Toast.makeText(ShowSortedActivity.this, "check2", Toast.LENGTH_SHORT).show();
}
else{
//do nothing
Toast.makeText(ShowSortedActivity.this, "uncheck1", Toast.LENGTH_SHORT).show();
}
}
else{
//do nothing
Toast.makeText(ShowSortedActivity.this, "uncheck2", Toast.LENGTH_SHORT).show();
}
}
}).attachToRecyclerView(showSorted);
}
Here I'm getting the task of class "Sorted" and check if the ending time of the task is less than the current time of the day. If so, I want to change the variable.
My adapter class:
public class SortedAdapter extends RecyclerView.Adapter<SortedAdapter.SortedViewHolder> {
private List<Sorted> list = new ArrayList<>();
#NonNull
#Override
public SortedViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.tasks2_layout , parent, false);
return new SortedAdapter.SortedViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull final SortedViewHolder holder, final int position) {
final Sorted data = list.get(position);
holder.title.setText(data.getSortedName());
holder.date.setText(data.getSortedDate());
holder.category.setText(String.valueOf(data.getSortedCategory()));
holder.attach.setText(String.valueOf(data.isSortedAttach()));
holder.to.setText(String.valueOf(toTime(data.getSortedDuration() + data.getSortedTimeBegin())));
holder.from.setText(String.valueOf(toTime(data.getSortedTimeBegin())));
holder.isChecked.setText(String.valueOf(data.isChecked()));
}
public void setSortedData(List<Sorted> sortedList){
this.list = sortedList;
notifyDataSetChanged();
}
public Sorted getSortedAtPosition(int position){
return list.get(position);
}
public void setSorted(Sorted data){
}
#Override
public int getItemCount() {
return list.size();
}
static class SortedViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private TextView title;
private TextView date;
private TextView from;
private TextView to;
private TextView category;
private TextView attach;
private TextView isChecked;
SortedViewHolder(#NonNull View itemView) {
super(itemView);
title = itemView.findViewById(R.id.tv_title1);
date = itemView.findViewById(R.id.tv_date1);
from = itemView.findViewById(R.id.tv_from3);
to = itemView.findViewById(R.id.tv_to3);
category = itemView.findViewById(R.id.tv_category1);
attach = itemView.findViewById(R.id.tv_attach1);
isChecked = itemView.findViewById(R.id.tv_isChecked);
}
}
private static String toTime(int a) {
String s = "";
int b = a/60;
int c = a%60;
if (c < 10) {
s = b + " : " + 0 + c;
}
else {
s = b + " : " + c;
}
return s;
}
}
Sorted class:
#Entity
public class Sorted {
#PrimaryKey(autoGenerate = true)
public int id;
public String name;
public int timeBegin;
public int duration;
public int category;
public boolean attach;
public String date;
public String categoryChart;
public boolean checked;
public Sorted(String name, int timeBegin, int duration, int category, boolean attach, String date, String categoryChart, boolean checked) {
this.name = name;
this.timeBegin = timeBegin;
this.duration = duration;
this.category = category;
this.attach = attach;
this.date = date;
this.categoryChart = categoryChart;
this.checked = checked;
}
public void setSortedId(int id) {
this.id = id;
}
public String getSortedName() {
return name;
}
public int getSortedTimeBegin() {
return timeBegin;
}
public int getSortedDuration() {
return duration;
}
public int getSortedCategory() {
return category;
}
public boolean isSortedAttach() {
return attach;
}
public String getSortedDate() {
return date;
}
public String getSortedCategoryChart() {
return categoryChart;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
}
My problem is that I don't really understand how to do it. Is there any way to update the data, not create a new task? Or do I need to delete the task I got and insert a new one, with one parameter changed? Maybe I could do it the same way I update the list? :
public void setSortedData(List<Sorted> sortedList){
this.list = sortedList;
notifyDataSetChanged();
}
Or maybe I don't need to deal with my adapter, only with database? (I'm using Room).
Thanks in advance for help. If it's needed, I will add more information to the question.
In method onSwipe to change UI you only need call some method to set for model current and call adapter.notifyItemChange(viewHolder.getAdapterPosition()) no need create new object or new list
I know you using Room don't forget update it to database. Additional if you using RxJava or Flow and LiveData one thing you need is update entity. Room auto update new list for you

How to get details when clicking on an item in a RecyclerView?

I am trying to get the details of the Recipe from which Recipe I have clicked in recycler view. I am using this to go to an edit/delete feature. Here is the code for my main activity.
The details that I am trying to get is getting the Name, Ingredients and method.
public class MainActivity extends AppCompatActivity implements RecipeListAdapter.OnItemClickListener {
private RecipeViewModel mRecipeViewModel;
public static final int NEW_WORD_ACTIVITY_REQUEST_CODE = 1;
public String Name;
public String Ingredients;
public String Method;
private RecipeListAdapter mAdapter;
private RecipeDao recDao;
private LiveData<List<Recipe>> RecipeList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = findViewById(R.id.recyclerview);
final RecipeListAdapter adapter = new RecipeListAdapter(this);
recyclerView.setAdapter(adapter);
adapter.setOnItemClickListener(MainActivity.this);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecipeViewModel = new ViewModelProvider(this).get(RecipeViewModel.class);
mRecipeViewModel.getAllRecipes().observe(this, new Observer<List<Recipe>>() {
#Override
public void onChanged(#Nullable final List<Recipe> recipes) {
// Update the cached copy of the words in the adapter.
adapter.setWords(recipes);
}
});
void onItemClick(int position) {
//Delete Below test to pass data through
Recipe recipe = new Recipe("Test", "Yeet", "Jim");
// showAlertDialogBox();
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("Edit or Delete...");
alertDialog.setPositiveButton("Edit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent update = new Intent(MainActivity.this, UpdateRecipeActivity.class);
update.putExtra("Name", recipe.getName());
update.putExtra("Ingredients", recipe.getIngredients());
update.putExtra("Method", recipe.getMethod());
startActivity(update);
}
});
alertDialog.setNegativeButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Delete
}
});
alertDialog.show();
}
Here is the Recipe.class if you needed it!
#Entity(tableName = "recipe_table")
public class Recipe {
#PrimaryKey(autoGenerate = true)
#ColumnInfo(name= "recipeId")
private int RecipeId;
private String name;
private String Ingredients;
private String Method;
#Ignore
public Recipe(String name, String Ingredients, String Method) {
this.RecipeId = RecipeId;
this.name = name;
this.Ingredients = Ingredients;
this.Method = Method;
}
public Recipe(String name) {
this.name = name;
}
public void changeText1(String text){
name = text;
}
//Add Image somehow!
public int getRecipeId() {
return RecipeId;
}
public void setRecipeId(int recipeId) {
RecipeId = recipeId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMethod() {
return Method;
}
public void setMethod(String method) {
Method = method;
}
public String getIngredients() {
return Ingredients;
}
public void setIngredients(String ingredients) {
Ingredients = ingredients;
}
}
If you need anymore files, these are the files I have:
- RecipeListAdapter
- RecipeDao
- RecipeRepository
- RecipeRoomDatabase
- RecipeViewModel
Recipe Adapter code
public class RecipeListAdapter extends RecyclerView.Adapter {
private OnItemClickListener mListener;
private List recipeList;
public interface OnItemClickListener{
void onItemClick(int position, Recipe recipe);
}
public void setOnItemClickListener(OnItemClickListener listener){
mListener = listener;
}
class RecipeViewHolder extends RecyclerView.ViewHolder {
private final TextView recipeItemView;
private RecipeViewHolder(View itemView) {
super(itemView);
recipeItemView = itemView.findViewById(R.id.textView);
itemView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if (mListener != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION){
mListener.onItemClick(position,
recipeList.get(getAdapterPosition()));
}
}
}
});
}
}
private final LayoutInflater mInflater;
private List<Recipe> mRecipes; // Cached copy of words
RecipeListAdapter(Context context) {
mInflater = LayoutInflater.from(context);
this.recipeList = recipeList;
}
#Override
public RecipeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = mInflater.inflate(R.layout.recyclerview_item, parent,
false);
return new RecipeViewHolder(itemView);
}
#Override
public void onBindViewHolder(RecipeViewHolder holder, int position) {
if (mRecipes != null) {
Recipe current = mRecipes.get(position);
holder.recipeItemView.setText(current.getName());
} else {
// Covers the case of data not being ready yet.
holder.recipeItemView.setText("No Recipes");
}
}
void setWords(List<Recipe> recipes){
mRecipes = recipes;
notifyDataSetChanged();
}
// getItemCount() is called many times, and when it is first called,
// mWords has not been updated (means initially, it's null, and we can't
return null).
#Override
public int getItemCount() {
if (mRecipes != null)
return mRecipes.size();
else return 0;
}
public interface OnNoteListener{}
}
Inside the onItemClick there is one more parameter need to add.
void onItemClick(int position, Recipe recipe) {
//Delete selected recipe from recipe list
arrayList.remove(recipe)
}
The onItemClick method will get called from adapter, from there you have to pass the selected receipe. In the adapter you have to use recipeList.get(getAdapterPosition()) to get the clicked receipe and pass this to the interface method, onItemClick along with the position.
So your code will look like this way inside the adapter,
itemClickListener.onItemClick(position,
recipeList.get(getAdapterPosition()))
Just as a note, please ensure instead of List, you need to take ArrayList to perform remove operation.

How to Retrieve Value in RecyclerView I tried a lot but it Retrieve a Null Value from Generated ID by Firebase after Push Data in Database in Android

How to retrieve value in RecyclerView I tried a lot but it retrieve a null value from generated id by Firebase after push data in database and if I don't using this method "push" the data stored in second id directly and retrieved well in Android and in log cat:
W/ClassMapper: No setter/field for -L9VWgoCymRWj9zbgK5H [image for database stracture][1]
This is my code:
public class TasksListActivity extends AppCompatActivity {
RecyclerView recyclerView;
TaskAdapter adapter;
List<Tasks>tasksList;
FirebaseDatabase FDB;
DatabaseReference DBR;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tasks_list);
recyclerView=(RecyclerView) findViewById(R.id.testingss);
RecyclerView.LayoutManager manager=new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(manager);
recyclerView.setHasFixedSize(true);
mAuth = FirebaseAuth.getInstance();
tasksList=new ArrayList<>();
adapter=new TaskAdapter(tasksList);
FDB=FirebaseDatabase.getInstance();
GetDataFirebase();
}
void GetDataFirebase (){
FirebaseUser currentUser = mAuth.getCurrentUser();
final String currentid=currentUser.getUid();
DBR=FDB.getReference("tasks").child(currentid);
DBR.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Tasks data=dataSnapshot.getValue(Tasks.class);
//Toast.makeText(getApplicationContext(),tas,Toast.LENGTH_SHORT).show();
tasksList.add(data);
adapter.notifyDataSetChanged();
recyclerView.setAdapter(adapter);
}
#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) {
}
});
}
public class TaskAdapter extends RecyclerView.Adapter<TaskAdapter.TaskViewHolder>{
List<Tasks> data=new ArrayList<>();
public TaskAdapter(List<Tasks> tasks){
this.data=tasks;
}
#Override
public TaskAdapter.TaskViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.taskslistitem,parent,false);
return new TaskViewHolder(view);
}
#Override
public void onBindViewHolder(TaskAdapter.TaskViewHolder holder, int position) {
Tasks tasks=data.get(position);
holder.taskName.setText(tasks.getmTaskname());
Toast.makeText(getApplicationContext(),tasks.getmTaskname(),Toast.LENGTH_SHORT).show();
//Toast.makeText(getApplication(),tasks.getmTaskname(),Toast.LENGTH_SHORT).show();
// Toast.makeText(getApplicationContext(),holder.taskName.getText(),Toast.LENGTH_SHORT).show();
}
#Override
public int getItemCount() {
return data.size();
}
public class TaskViewHolder extends RecyclerView.ViewHolder {
TextView taskName;
public TaskViewHolder(View itemView) {
super(itemView);
taskName=(TextView) itemView.findViewById(R.id.tasksnameId);
}
}
}
}
the class about tasks model
public class Tasks {
private String mMemberEmail;
private String mTaskname;
private String mTaskDsc;
private String mTaskDeadline;
public Tasks() {
}
public Tasks(String mMemberEmail, String mTaskname, String mTaskDsc, String mTaskDeadline) {
this.mMemberEmail = mMemberEmail;
this.mTaskname = mTaskname;
this.mTaskDsc = mTaskDsc;
this.mTaskDeadline = mTaskDeadline;
}
public String getmMemberEmail() {
return mMemberEmail;
}
public void setmMemberEmail(String mMemberEmail) {
this.mMemberEmail = mMemberEmail;
}
public String getmTaskname() {
return mTaskname;
}
public void setmTaskname(String mTaskname) {
this.mTaskname = mTaskname;
}
public String getmTaskDsc() {
return mTaskDsc;
}
public void setmTaskDsc(String mTaskDsc) {
this.mTaskDsc = mTaskDsc;
}
public String getmTaskDeadline() {
return mTaskDeadline;
}
public void setmTaskDeadline(String mTaskDeadline) {
this.mTaskDeadline = mTaskDeadline;
}
}
final Tasks tasks=new Tasks(mMemberEmail,mTasksName,mTaskDsc,mTaskDeadline);
mUserDatabase.child("tasks").child(current_id).child(id).push().setValue(tasks).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
mAuth = FirebaseAuth.getInstance();
user = mAuth.getCurrentUser();
String current_id = user.getUid();
Tasks tasks=new Tasks(mMemberEmail,mTasksName,mTaskDsc,mTaskDeadline);
String id = child.getKey();
mUserDatabase.child("tasks").child(id).child(current_id).push().setValue(tasks);
}
});
}
You are getting the following warning:
W/ClassMapper: No setter/field for -L9VWgoCymRWj9zbgK5H
Because you are using wrong getters for your fields. The correct getter for a field that looks like this:
private String mMemberEmail;
Should be:
public String getMMemberEmail() { //See the first capital M
return mMemberEmail;
}
The correct naming for the fields and getters inside a model should be:
public class Tasks {
private String memberEmail;
private String taskName;
private String taskDsc;
private String taskDeadline;
public Tasks() {}
public Tasks(String memberEmail, String taskName, String taskDsc, String taskDeadline) {
this.memberEmail = memberEmail;
this.taskName = taskName;
this.taskDsc = taskDsc;
this.taskDeadline = taskDeadline;
}
public String getMemberEmail() {return memberEmail;}
public String getTaskName() {return taskName;}
public String getTaskDsc() {return taskDsc;}
public String getTaskDeadline() {return taskDeadline;}
}
So remember, when the Firebase Realtime Database SDK deserializes objects coming from the database, is looking for fields that follow the principles of the JavaBeans and are named accordingly to Java Naming Conventions. So the corresponding getter for a field like memberEmail is getMemberEmail() and not getmemberEmail(). To make it work entirely, delete old data and add fresh one.

Categories