What could be wrong in my code? I use HashMap to make update easier in the database, but whenever I try to fetch this data from the database to FirebaseRecyclerAdapter I keep getting an error.
I have searched for many similar problems, tried their solutions but not working.
Below is the exception
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.project.android.designlibdemo.model.RecipeModel
Getter and setter
public class RecipeModel {
private String name;
public RecipeModel(){
}
public RecipeModel(String name){
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
ViewHolder class
public class ViewHolderRecipe extends RecyclerView.ViewHolder {
String LOG_TAG = ViewHolderRecipe.class.getSimpleName();
public View view;
private TextView ingredient_txt;
public ViewHolderRecipe(View itemView) {
super(itemView);
view = itemView;
ingredient_txt = itemView.findViewById(R.id.ingredient_list);
}
public void setRecipeName(String recipe){
ingredient_txt.setText(recipe);
}
How i send data to database
Map postRecipeMap = new HashMap();
final DatabaseReference sendRecp = FirebaseDatabase.getInstance().getReference().child
("Post").child("PostRecipe").push();
sendRecp.updateChildren(postRecipeMap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
mProgressDialog.dismiss();
AlertDialog.Builder alertDialogBuilder = new android.support.v7.app
.AlertDialog.Builder(PostingRecipeActivity.this);
alertDialogBuilder.setTitle("Successfully");
alertDialogBuilder.setMessage("You can click next");
alertDialogBuilder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
//Launch PostDetailActivity
Intent i = new Intent(PostingRecipeActivity.this, ContentIngredientList.class);
final String reportKey = sendRecp.getKey();
i.putExtra(ContentIngredientList.EXTRA_FIR_KEY, reportKey);
mProgressDialog.dismiss();
startActivity(i);
}
});
AlertDialog aDialog = alertDialogBuilder.create();
aDialog.show();
}
How I retrieve the data
public class ContentIngredientList extends AppCompatActivity {
public static final String EXTRA_FIR_KEY = "recipeKey";
private FirebaseRecyclerAdapter<RecipeModel, ViewHolderRecipe> mAdapter;
//private RecyclerView mIngredient_list;
String LOG_TAG = PostingRecipeActivity.class.getSimpleName();
private String recipeKey;
public ContentIngredientList(){
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_ingredient_list);
// Get post key from intent
recipeKey = getIntent().getStringExtra(EXTRA_FIR_KEY);
if (recipeKey == null) {
throw new IllegalArgumentException("Must pass EXTRA_POST_KEY");
}
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference().child("Post").child
("PostRecipe").child(recipeKey);
RecyclerView mRcyclerViewIngredient = findViewById(R.id.ingredient_list_recycler);
//mIngredient_list = findViewById(R.id.ingredient_list);
Log.e(LOG_TAG, "url" + mDatabase.getRef()) ;
// [END create_database_reference]
// mDirectionList.setHasFixedSize(true);
mRcyclerViewIngredient.setLayoutManager(new LinearLayoutManager(this));
// mIngredient_list.setHasFixedSize(true);
//mIngredient_list.setLayoutManager(new LinearLayoutManager(this));
mAdapter = new FirebaseRecyclerAdapter<RecipeModel, ViewHolderRecipe>(RecipeModel.class,
R.layout.ingredient_posting, ViewHolderRecipe.class, mDatabase) {
#Override
protected void populateViewHolder(ViewHolderRecipe viewHolder, RecipeModel model, int position) {
viewHolder.setRecipeName(model.getName());
}
};
mRcyclerViewIngredient.setAdapter(mAdapter);
}
}
To get the list of post recepies, then your database shoundn't be:
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference().child("Post").child
("PostRecipe").child(recipeKey);
But rather:
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference().child("Post").child
("PostRecipe");
You were referencing a particular PostRecipe, then when Firebase UI tried to get the object it only found the string name.
Related
I want to retrieve data from Firebase to recyclerView through FirebaseRecyclerOptionsbut it keeps showing blanks pages,I want to display the registered Users in my App and there details in a layout,I have no idea where I have gone wrong,I have multi check on my codes and I can't see any error Please can Anyone help me here.
Here Are Code for ListAdapter,Model and ListActivity
public class ListActivity extends AppCompatActivity {
private FirebaseAuth firebaseAuth;
private DatabaseReference reference;
RecyclerView recyclerView;
ListAdapter listAdapter;
private String CurrentUserID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
recyclerView = findViewById(R.id.children_home_list);
firebaseAuth = FirebaseAuth.getInstance();
CurrentUserID = firebaseAuth.getCurrentUser().getUid();
reference = FirebaseDatabase.getInstance().getReference().child("Children Home Details");
recyclerView.setLayoutManager(new LinearLayoutManager(this));
FirebaseRecyclerOptions<Model> options =
new FirebaseRecyclerOptions.Builder<Model>()
.setQuery(reference, Model.class)
.build();
listAdapter = new ListAdapter(options);
}
#Override
protected void onStart() {
super.onStart();
listAdapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
listAdapter.stopListening();
}
public class ListAdapter extends FirebaseRecyclerAdapter<Model,ListAdapter.ListViewHolder> {
public ListAdapter(#NonNull FirebaseRecyclerOptions<Model> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull ListViewHolder holder, int position, #NonNull Model model) {
holder.Name.setText(model.getName());
holder.Phone.setText(model.getPhone());
holder.Location.setText(model.getLocation());
holder.Email.setText(model.getMailAddress());
//Glide.with(holder.circleImageView.getContext()).load(model.IMAGELINK()).into(holder.circleImageView);
}
#NonNull
#Override
public ListViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.singlerow,parent,false);
return new ListViewHolder(view);
}
class ListViewHolder extends RecyclerView.ViewHolder {
CircleImageView circleImageView;
TextView Name,Phone,Email,Location;
public ListViewHolder(#NonNull View itemView) {
super(itemView);
circleImageView = itemView.findViewById(R.id.img1);
Name = itemView.findViewById(R.id.HomeName);
Phone = itemView.findViewById(R.id.phoneName);
Email = itemView.findViewById(R.id.paypalAddress);
Location = itemView.findViewById(R.id.location);
}
}
}
public class Model {
String Name,Phone,Location,MailAddress;
public Model(String name, String phone, String location, String mailAddress) {
Name = name;
Phone = phone;
Location = location;
MailAddress = mailAddress;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getPhone() {
return Phone;
}
public void setPhone(String phone) {
Phone = phone;
}
public String getLocation() {
return Location;
}
public void setLocation(String location) {
Location = location;
}
public String getMailAddress() {
return MailAddress;
}
public void setMailAddress(String mailAddress) {
MailAddress = mailAddress;
}
}
I working with an app but when I am trying to access firebase data the getter method of the POJO returns null. I can not access data and setup in RecyclerView
Here is what I did:
My Firebase Structure:
My app debugging mode:
My Book Class
public class Book {
private String bookId;
private String bookImage;
private String bookName;
private String writerName;
private String publisherName;
private String shortDesc;
public Book() {
}
public Book(String bookImage, String bookName,
String writerName, String publisherName,String shortDesc) {
this.bookImage = bookImage;
this.bookName = bookName;
this.writerName = writerName;
this.publisherName = publisherName;
this.shortDesc = shortDesc;
}
public Book(String bookId, String bookImage, String bookName,
String writerName, String publisherName, String shortDesc) {
this.bookId = bookId;
this.bookImage = bookImage;
this.bookName = bookName;
this.writerName = writerName;
this.publisherName = publisherName;
this.shortDesc = shortDesc;
}
public String getBookId() {
return bookId;
}
public String getBookImage() {
return bookImage;
}
public String getBookName() {
return bookName;
}
public String getWriterName() {
return writerName;
}
public String getPublisherName() {
return publisherName;
}
public String getShortDesc() {
return shortDesc;
}
public void setBookId(String bookId) {
this.bookId = bookId;
}
My BookListFragment where I'm showing my book list
public class BookListFragment extends Fragment {
private Button button1,button2,button3;
private RecyclerView bookListRv;
private ArrayList<Book> bookList;
private BookAdapter bookAdapter;
private String adminId;
private FirebaseAuth firebaseAuth;
private DatabaseReference databaseReference;
public BookListFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_book_list, container, false);
init(view);
adminId = firebaseAuth.getUid();
Book book = new Book();
String bookid =book.getBookId();
configRV();
getBooks();
return view;
}
private void init(View view) {
bookListRv = view.findViewById(R.id.bookRVId);
firebaseAuth = firebaseAuth.getInstance();
databaseReference = FirebaseDatabase.getInstance().getReference();
bookList = new ArrayList<>();
bookAdapter = new BookAdapter(bookList, getContext());
}
private void configRV() {
bookListRv.setLayoutManager(new LinearLayoutManager(getContext()));
bookListRv.setAdapter(bookAdapter);
}
private void getBooks() {
DatabaseReference showBookRef = databaseReference.child("Books").child(adminId);
showBookRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot data:dataSnapshot.getChildren()){
Book book = data.getValue(Book.class);
bookList.add(book);
bookAdapter.notifyDataSetChanged();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
My AddBookActivity
public class AddBookActivity extends AppCompatActivity {
private Button addBookBtn;
private ImageView bookIv;
private EditText bookNameEt,writerNameEt,publisherNameEt,shortDescEt;
private Uri imgUrl = null;
private FirebaseAuth firebaseAuth;
private DatabaseReference databaseReference;
private StorageReference imgReference;
private String adminId,imgUri="";
private FirebaseUser mFirebaseUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_book);
init();
if(mFirebaseUser!=null){
adminId = mFirebaseUser.getUid();
}
bookIv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent,1);
}
});
addBookBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addBookData();
}
});
}
private void init() {
firebaseAuth = FirebaseAuth.getInstance();
mFirebaseUser = firebaseAuth.getCurrentUser();
imgReference = FirebaseStorage.getInstance().getReference();
databaseReference = FirebaseDatabase.getInstance().getReference();
addBookBtn = findViewById(R.id.addBookBtnId);
bookIv = findViewById(R.id.addBookIvId);
bookNameEt = findViewById(R.id.addBookNameEtId);
writerNameEt = findViewById(R.id.addBookWriterNameEtId);
publisherNameEt = findViewById(R.id.addBookPublisherNameEtId);
shortDescEt = findViewById(R.id.addBookDescripEtId);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==1 && resultCode==RESULT_OK){
if(data!=null){
imgUrl = data.getData();
bookIv.setImageURI(imgUrl);
}
}
}
private void addBookData() {
if (imgUrl!=null) {
final StorageReference filePath = imgReference.child("Book_images").child(String.valueOf(System.currentTimeMillis()));
filePath.putFile(imgUrl).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
imgUri=uri.toString();
}
});
}
}
});
}
String bookName = bookNameEt.getText().toString();
String writerName = writerNameEt.getText().toString();
String publisherName = publisherNameEt.getText().toString();
String bookDesc = shortDescEt.getText().toString();
String bookImg = imgUri;
if(TextUtils.isEmpty(bookName) && TextUtils.isEmpty(writerName)
&& TextUtils.isEmpty(publisherName) && TextUtils.isEmpty(bookDesc) && TextUtils.isEmpty(bookImg)){
Toast.makeText(this,"Please Fill The Blank Field",Toast.LENGTH_LONG).show();
}
else if(!TextUtils.isEmpty(bookName) && !TextUtils.isEmpty(writerName)
&& !TextUtils.isEmpty(publisherName) && !TextUtils.isEmpty(bookDesc) && !TextUtils.isEmpty(bookImg)){
saveBook(bookImg,bookName,writerName,publisherName,bookDesc);
}
}
private void saveBook(String url, String bookName, String writerName, String publisherName, String bookDesc) {
DatabaseReference bookRef = databaseReference.child("Books").child(adminId);
String bookId = bookRef.push().getKey();
if(bookId!=null){
Book book = new Book(bookId,url,bookName,writerName,publisherName,bookDesc);
bookRef.child(bookId).child("BookInfo").setValue(book).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
}
});
}
}
}
My BookAdapter
public class BookAdapter extends RecyclerView.Adapter {
private List<Book> books;
private Context context;
public BookAdapter(List<Book> books, Context context) {
this.books = books;
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_book_layout,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
final Book currentBook = books.get(position);
// holder.bookIv.setIm(currentBook.getBookImage());
holder.bookNameTv.setText(currentBook.getBookName());
holder.writerNameTv.setText(currentBook.getWriterName());
holder.publisherNameTv.setText(currentBook.getPublisherName());
holder.shortDescTv.setText(currentBook.getShortDesc());
}
#Override
public int getItemCount() {
return books.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView bookNameTv,writerNameTv,publisherNameTv,shortDescTv;
private ImageView bookIv;
public ViewHolder(#NonNull View itemView) {
super(itemView);
bookIv = itemView.findViewById(R.id.bookListIvId);
bookNameTv = itemView.findViewById(R.id.bookListNameTvId);
writerNameTv = itemView.findViewById(R.id.bookListWriterNameTvId);
publisherNameTv = itemView.findViewById(R.id.bookListPubNameTvId);
shortDescTv = itemView.findViewById(R.id.bookListShortDescTvId);
}
}
}
Now when I am debugging my app the debugger showing me the Book class reference book is all field null.
Any help me for appreciated
It's because you are creating book object in app and book is not fetched from firebase. You need to query for books using adminId
You have to go one more level deep to get BookInfo. Try using below code:
showBookRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot data: dataSnapshot.getChildren()) {
Book book = data.child("BookInfo").getValue(Book.class);
bookList.add(book);
}
bookAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
You have to have your BookInfo directly outside i.e. YourRootId->SubId->YourInfo but this is what you have used as YourRootId->SubId->BookInfo->YourInfo (this is right if you want to retrieve only that particular data)
So First setup a FirebaseRecyclerAdapter
Query query = FirebaseDatabase.getInstance()
.getReference()
.child("yourRootId/");
FirebaseRecyclerOptions<Book> options = FirebaseRecyclerOptions.Builder<Book>()
.setQuery(query, Book.class)
.build();
FirebaseRecyclerAdapter adapter = new FirebaseRecyclerAdapter<Book, BookHolder>(options) {
#Override
public BookHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// Create a new instance of the ViewHolder, in this case we are using a custom
// layout called R.layout.message for each item
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.yourlayout, parent, false);
return new BookHolder(view);
}
#Override
protected void onBindViewHolder(BookHolder holder, int position, Book model) {
// assign all data in here
}
};
then create a viewholder
public class BookHolder extends RecyclerView.ViewHolder {
public LinearLayout root;
public TextView abc;
public TextView xyz;
public ViewHolder(View itemView) {
super(itemView);
abc= itemView.findViewById(R.id.list_title);
xyz= itemView.findViewById(R.id.list_desc);
}
}
Sorry if i m asking lame questions i m new to android development.
I have a activity in which i m populating firebase recycler adapter problem is that it is not populating recycler (loadFoodlist) when i click on that activity once.
But when i click that activity twice or thrice after that it is getting data perfectly fine i don't know what is the problem it happens whenever i relaunch the app?
Database structure
database image
public class FoodDetailModel {
String name, price, description, type;
public FoodDetailModel(){
}
public FoodDetailModel(String name, String price, String description, String type) {
this.name = name;
this.price = price;
this.description = description;
this.type = type;
}
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 getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
public class FoodDetailViewHolder extends RecyclerView.ViewHolder {
public TextView foodname,price,description;
public Button delete;
public ImageView type;
public FoodDetailViewHolder(#NonNull View itemView) {
super(itemView);
foodname = (TextView) itemView.findViewById(R.id.food_name);
price = (TextView) itemView.findViewById(R.id.food_price);
description = (TextView) itemView.findViewById(R.id.food_description);
delete = (Button) itemView.findViewById(R.id.add_to_cart);
type = itemView.findViewById(R.id.type);
}
}
public class FoodDetail extends AppCompatActivity {
FirebaseDatabase database;
FirebaseAuth mAuth;
DatabaseReference ref;
FirebaseRecyclerAdapter<FoodDetailModel, FoodDetailViewHolder> adapter;
RecyclerView recycler_menu;
RecyclerView.LayoutManager layoutManager;
CollapsingToolbarLayout collapsingToolbarLayout;
ProgressDialog dialog1 ;
String resID = "", resName = "";
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food_detail);
dialog1 = new ProgressDialog(FoodDetail.this);
mAuth = FirebaseAuth.getInstance();
imageView = (ImageView) findViewById(R.id.food_img);
if(getIntent() != null){
resID = getIntent().getStringExtra("restraunt_id");
resName = getIntent().getStringExtra("name");
}
// init firebase
collapsingToolbarLayout = findViewById(R.id.collapsing);
collapsingToolbarLayout.setExpandedTitleTextAppearance(R.style.ExpandedAppBar);
collapsingToolbarLayout.setCollapsedTitleTextAppearance(R.style.CollapsedAppBar);
collapsingToolbarLayout.setTitle(resName);
// load restuarant list from firebase
recycler_menu = (RecyclerView) findViewById(R.id.foodmenu_list);
recycler_menu.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recycler_menu.setLayoutManager(layoutManager);
loadFoodList();
loadName();
}
private void loadName() {
DatabaseReference ref1 = FirebaseDatabase.getInstance().getReference();
DatabaseReference mostafa = ref1.child("restaurant").child(resID).child("img");
mostafa.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String imgURL = dataSnapshot.getValue(String.class);
Picasso.with(getBaseContext()).load(imgURL).fit().into(imageView);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void loadFoodList() {
ref = FirebaseDatabase.getInstance().getReference().child("menu").child(resID);
System.out.println("getttts here" + ref.toString());
adapter = new FirebaseRecyclerAdapter<FoodDetailModel, FoodDetailViewHolder>
(FoodDetailModel.class,R.layout.food_detail_blueprint, FoodDetailViewHolder.class,ref) {
#Override
protected void populateViewHolder(final FoodDetailViewHolder viewHolder, final FoodDetailModel model, final int position) {
final String x = adapter.getRef(position).toString();
viewHolder.foodname.setText(model.getName());
viewHolder.price.setText("₹"+model.getPrice());
viewHolder.description.setText(model.getDescription());
String typ = model.getType();
if (typ.equals("veg")){
viewHolder.type.setImageResource(R.drawable.veg);
} else {
viewHolder.type.setImageResource(R.drawable.nonveg);
}
viewHolder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder alert = new AlertDialog.Builder(FoodDetail.this);
alert.setTitle("Delete entry");
alert.setMessage("Are you sure you want to delete?");
alert.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alert.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// close dialog
dialog.cancel();
}
});
alert.show();
}
});
}
};
recycler_menu.setAdapter(adapter);
}
}
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.
Can anyone help me to retrieve data from the node "foods" and put it in the RecyclerView. These are the file I've been working on but it turns out to be an empty list. I have viewed a tutorial on Internet but most of them were with an older version of Firebase. Recently, Firebase UI has been updated and the data binding process has changed to their new FirebaseRecyclerAdapter structure
This is my database structure:
"foods" : {
"AntipastoSalad" : {
"duration" : "30",
"img" : "https://firebasestorage.googleapis.com/v0/b/mealplanner-ec8ca.appspot.com/o/res%2Fsalad.jpg?alt=media&token=257d4392-8a1f-4fb7-84b5-b63abb4643f4",
"name" : "Antipasto salad",
"type" : "Salad"
},
This is my activity:
private RecyclerView mRecycleView;
private Query query;
private FirebaseRecyclerOptions<Meal> options;
private DatabaseReference mDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food_list_row);
mDatabase = FirebaseDatabase.getInstance().getReference().child("foods");
//Recycle View
mRecycleView = (RecyclerView) findViewById(R.id.meal_items);
mRecycleView.setHasFixedSize(true);
mRecycleView.setLayoutManager(new LinearLayoutManager(this));
}
#Override
protected void onStart() {
super.onStart();
query = FirebaseDatabase.getInstance().getReferenceFromUrl("https://mealplanner-ec8ca.firebaseio.com/foods/AntipastoSalad");
options = new FirebaseRecyclerOptions.Builder<Meal>()
.setQuery(query, Meal.class)
.build();
FirebaseRecyclerAdapter<Meal, FoodListRowActivity.MealRowHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Meal, FoodListRowActivity.MealRowHolder>(
options) {
#Override
public FoodListRowActivity.MealRowHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.food_row, parent, false);
return new FoodListRowActivity.MealRowHolder(v);
}
#Override
protected void onBindViewHolder(FoodListRowActivity.MealRowHolder holder, int position, Meal current) {
holder.setTitle(current.getName());
String duration = current.getDuration() + "min";
holder.setDuration(duration);
}
};
//Populate Item into Adapter
mRecycleView.setAdapter(firebaseRecyclerAdapter);
mRecycleView.addOnItemTouchListener(new RecycleViewItemClickListener(this, mRecycleView, new RecycleViewItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Intent viewMeal = new Intent(FoodListRowActivity.this, CookingInstructionActivity.class);
startActivity(viewMeal);
}
#Override
public void onLongItemClick(View view, int position) {
//TODO: DELETE
}
}));
}
public static class MealRowHolder extends RecyclerView.ViewHolder {
View mView;
public MealRowHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setTitle(String title) {
TextView foodTitle = (TextView) mView.findViewById(R.id.list_item_foodList_name);
foodTitle.setText(title);
}
public void setDuration(String title) {
TextView foodDuration = (TextView) mView.findViewById(R.id.list_item_foodList_calories);
foodDuration.setText(title);
}
}
}
and class structure:
public class Meal{
private String img;
private String duration;
private String name;
private String instruction;
public Meal(){
}
public Meal (String img, String duration, String name, String instruction){
this.img = img;
this.name = name;
this.duration = duration;
this.instruction = instruction;
}
public void update(String duration, String name, String instruction)
{
this.name = name;
this.duration = duration;
this.instruction = instruction;
}
public String getName(){
return name;
}
public String getDuration() {
return duration;
}
public String getInstruction() {
return instruction;
}
public String getImg(){return img;}
The query specified in the setQuery() method should be a reference to the root of the list you want to show in the RecyclerView, so like this:
query = FirebaseDatabase.getInstance().getReference().child("foods");
You also need to call startListening() on the adapter to instruct it to start retrieving data from the database.
From the FirebaseRecyclerAdapter lifecycle documentation:
The FirebaseRecyclerAdapter uses an event listener to monitor changes to the Firebase query. To begin listening for data, call the startListening() method. You may want to call this in your onStart() method. Make sure you have finished any authentication necessary to read the data before calling startListening() or your query will fail.
#Override protected void onStart() {
super.onStart();
adapter.startListening();
}
Similarly, the stopListening() call removes the event listener and all data in the adapter. Call this method when the containing Activity or Fragment stops:
#Override protected void onStop() {
super.onStop();
adapter.stopListening();
}
Please override getItemCount() method of FirebaseRecyclerAdapter.
#Override
public int getItemCount() {
return 1;
}
Reference.
This is how I'm retrieving my data in recyclerview using Firebase UI:
private FirebaseRecyclerAdapter<TaskPOJO, TaskViewHolder> adapter;
private void loadTasks() {
database = FirebaseDatabase.getInstance();
tasks = database.getReference("Tasks");
adapter = new FirebaseRecyclerAdapter<TaskPOJO, TaskViewHolder>(TaskPOJO.class, R.layout.task_item, TaskViewHolder.class, tasks) {
#Override
protected void populateViewHolder(TaskViewHolder viewHolder, final TaskPOJO model, int position) {
Log.wtf("valueTEst", "populateViewHolder: "+model.toString() );
Log.wtf("TEstScript1", "populateViewHolder: "+model.getTitle() );
viewHolder.title.setText(model.getTitle());
viewHolder.desc.setText(model.getDescripttion()+"\n");
viewHolder.remaining.setText(model.getRemaining()+"/"+model.getPoint());
viewHolder.points.setText("Points "+model.getRemaining());
Glide.with(viewHolder.title.getContext())
.load(model.getImage())
.into(viewHolder.image);
viewHolder.setClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
Toast.makeText(getActivity(), "" /*+ model.getTitle()*/, Toast.LENGTH_SHORT).show();
Intent TaskPOJODetail = new Intent(getActivity(), Main.class);
TaskPOJODetail.putExtra("value","detail");
TaskPOJODetail.putExtra("taskId",adapter.getRef(position).getKey());
startActivity(TaskPOJODetail);
}
});
}
};
progressBar.setVisibility(View.GONE);
recyclerViewTasks.setAdapter(adapter);
}
this is my firebase structure :
hope this will help you.