I am using Firebase to create an app where users can sign up for a class and then view them. I am using the same recycler adapter and objects for the activities that show the classes and the activity that shows the users classes under their uid. When I run the app, the classes show up that I have input into Firebase, but the activity that shows the users' classes shows a blank cardview(same code used). The error is:`
No setter/field for room_number2 found on class com.samuelford48gmail.thsconnect.Class_model
No setter/field for date_clasname2 found on class com.samuelford48gmail.thsconnect.Class_model
No setter/field for teacher2 found on class com.samuelford48gmail.thsconnect.Class_model
My code for the fragment that shows the users' classes:
public class home_fragment extends Fragment implements View.OnClickListener {
private Button button;
//DatabaseReference dref;
//ListView listview2;
//ArrayList<String> list=new ArrayList<>();
private FirebaseDatabase database;
private DatabaseReference myRef;
private List<Listdata> list;
private RecyclerView recyclerview;
public home_fragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.home_fragment, container, false);
//FirebaseUser fbUser = FirebaseAuth.getInstance().getCurrentUser();
//if(fbUser == null) { Intent intent = new Intent(getContext(), LoginActivity.class);
// startActivity(intent);}
button = (Button) view.findViewById(R.id.button);
button.setOnClickListener(this);
recyclerview = (RecyclerView) view.findViewById(R.id.rview);
database = FirebaseDatabase.getInstance();
myRef = database.getReference("Users")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("Classes");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
list = new ArrayList<>();
// StringBuffer stringbuffer = new StringBuffer();
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
Class_model new_class = dataSnapshot1.getValue(Class_model.class);
String nameofclass = new_class.getDate_clasname();
String teacherofclass = new_class.getTeacher();
String roomnumberofclass = new_class.getRoom_number();
String class_key = new_class.getUid();
Listdata listdata = new Listdata(nameofclass, teacherofclass, roomnumberofclass, class_key);
//String name = userdetails.getName();
//String email = userdetails.getEmail();
//String address = userdetails.getAddress();
listdata.setDate_class(nameofclass);
listdata.setTeacher(teacherofclass);
listdata.setRnumber(roomnumberofclass);
list.add(listdata);
// Toast.makeText(MainActivity.this,""+name,Toast.LENGTH_LONG).show();
}
RecyclerviewAdapter2 recycler = new RecyclerviewAdapter2(list);
RecyclerView.LayoutManager layoutmanager = new LinearLayoutManager(getContext());
recyclerview.setLayoutManager(layoutmanager);
recyclerview.setItemAnimator(new DefaultItemAnimator());
recyclerview.setAdapter(recycler);
}
#Override
public void onCancelled(DatabaseError error) {
AlertDialog alertDialog = new AlertDialog.Builder(getContext()).create();
alertDialog.setTitle("Error");
alertDialog.setMessage("Check your connection! If, problem persists please email svhsdev#vigoschools.org!");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
// Failed to read value
// Log.w(TAG, "Failed to read value.",
error.toException());
}
});
return view;
}
#Override
public void onClick(View view) {
signout();
//startActivity(new Intent(home_fragment.this,
LoginActivity.class));
}
public void signout(){
FirebaseAuth.getInstance().signOut();
Intent intent = new Intent(getContext(), LoginActivity.class);
startActivity(intent);
}
}
Here is the code for my Recycler Adapter class:
public class RecyclerviewAdapter2 extends RecyclerView.Adapter<RecyclerviewAdapter2.MyHolder>{
List<Listdata> listdata;
public RecyclerviewAdapter2(List<Listdata> listdata) {
this.listdata = listdata;
}
#Override
public RecyclerviewAdapter2.MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_class_model,parent,false);
RecyclerviewAdapter2.MyHolder myHolder = new RecyclerviewAdapter2.MyHolder(view);
return myHolder;
}
public void onBindViewHolder(RecyclerviewAdapter2.MyHolder holder, final int position) {
final Listdata data = listdata.get(position);
holder.vdate_class.setText(data.getDate_class());
holder.vteacher.setText(data.getTeacher());
holder.vrnumber.setText(data.getRnumber());
//System.out.println(data.getDate_class2());
holder.itemView.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick( final View view) {
Context context = view.getContext();
Intent intent = new Intent(context, test_for_science_add_class.class);
intent.putExtra("date_class", listdata.get(position).getDate_class());
intent.putExtra("teacher", listdata.get(position).getTeacher());
intent.putExtra("room_number", listdata.get(position).getRnumber());
intent.putExtra("post_key", listdata.get(position).getUid());
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return listdata.size();
}
class MyHolder extends RecyclerView.ViewHolder{
TextView vdate_class , vteacher,vrnumber;
public MyHolder(View itemView) {
super(itemView);
vdate_class = (TextView) itemView.findViewById(R.id.date_class_name);
vteacher = (TextView) itemView.findViewById(R.id.teacher);
vrnumber = (TextView) itemView.findViewById(R.id.room_number);
}
}
}
Here is my Class_model code:
public class Class_model {
//String subject;
String date_clasname;
String teacher;
String room_number;
String uid;
public Class_model(){};
public Class_model(String date_classname, String teacher, String room_number, String uid){
this.date_clasname = date_classname;
this.teacher = teacher;
this.room_number = room_number;
this.uid = uid;
}
public String getDate_clasname() {
return date_clasname;
}
public void setDate_clasname(String date_clasname) {
this.date_clasname = date_clasname;
}
public String getTeacher() {
return teacher;
}
public void setTeacher(String teacher) {
this.teacher = teacher;
}
public String getRoom_number() {
return room_number;
}
public void setRoom_number(String room_number) {
this.room_number = room_number;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
}
Here is my code for the Listdata class:
public class Listdata {
String date_class;
String teacher;
String rnumber;
String uid;
public Listdata(String date_class, String teacher, String rnumber, String uid) {
this.date_class = date_class;
this.teacher = teacher;
this.rnumber = rnumber;
this.uid = uid;
}
public String getDate_class() {
return date_class;
}
public void setDate_class(String date_class) {
this.date_class = date_class;
}
public String getTeacher() {
return teacher;
}
public void setTeacher(String teacher) {
this.teacher = teacher;
}
public String getRnumber() {
return rnumber;
}
public void setRnumber(String rnumber) {
this.rnumber = rnumber;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
}
My Firebase structure:
"Technology" : {
"-LgxmDqmlPZnCOEyjBww" : {
"date_clasname" : "technology",
"room_number" : "d",
"teacher" : "f"
}
},
"Users" : {
"NnJlSVeqGXhJ2Nab2bhjr0HIpku2" : {
"Classes" : {
"-LhM7iyYhmwvtDvtLE-Z" : {
"date_clasname2" : "technology",
"room_number2" : "d",
"teacher2" : "f"
},
"-LhM7k0uI_eY31nQnnro" : {
"date_clasname2" : "other",
"room_number2" : "d",
"teacher2" : "f"
},
"-LhM87eT7kv7KL1JHryM" : {
"date_clasname2" : "March 5",
"room_number2" : "101",
"teacher2" : "pence"
}
},
"email" : "samuelford48#gmail.com",
"grade" : "12",
"name" : "Samuel Ford"
},
Here is my code for the activity that happens when the user clicks on one of the recycler view items:
public class test_for_science_add_class extends AppCompatActivity {
private Button add_class;
private FirebaseDatabase database;
private DatabaseReference myRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_for_science_addd_class);
final String date_class2 = getIntent().getStringExtra("date_class");
final String teacher = getIntent().getStringExtra("teacher");
final String room_number = getIntent().getStringExtra("room_number");
final String post_key = getIntent().getStringExtra("post_key");
database = FirebaseDatabase.getInstance();
myRef = database.getReference("Users").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("Classes");
//String name = getIntent().getExtra("date_class");
//String city = getIntent().getExtra("City");
//System.out.println(value);
TextView display_class_name = (TextView) findViewById(R.id.date_tv2);
display_class_name.setText(date_class2);
TextView display_teacher = (TextView) findViewById(R.id.teacher_tv2);
display_teacher.setText(teacher);
TextView display_room_number = (TextView) findViewById(R.id.rn_tv2);
display_room_number.setText(room_number);
add_class = (Button) findViewById(R.id.add_class_2);
add_class.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Class_model_without_uid new_class_to_user_uid = new Class_model_without_uid(date_class2, teacher, room_number);
myRef.push().setValue(new_class_to_user_uid);
Toast.makeText(getApplicationContext(), "test", Toast.LENGTH_SHORT).show();
}
});
}
}
In my activity that handles clicks on a recycler item, I was calling the wrong object class when pushing to Firebase.
Incorrect code:
Class_model_without_uid new_class_to_user_uid = new Class_model_without_uid(date_class2, teacher, room_number);
myRef.push().setValue(new_class_to_user_uid);
Correct code:
Class_model new_class_to_user_uid = new Class_model(date_class, teacher, room_number, null);
myRef.push().setValue(new_class_to_user_uid);
Related
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);
}
}
I have simple problem with my Android app in Android Studio. I was to create two classes to add search activity in my app and was so successful. But, I have problem. The problem is that the user wants to select the person from the results and pass the user ID to another activity "User_Profile". But, I can't do this. Can anyone help me?
Search Class:
public class Search extends AppCompatActivity {
EditText se_input;
RecyclerView results_list;
DatabaseReference mUDB;
FirebaseUser mFBU;
SearchAdapter searchAdapter;
ArrayList<String> fullNameList,userNameList, userIdList,profileImageList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
mUDB = FirebaseDatabase.getInstance().getReference();
mFBU = FirebaseAuth.getInstance().getCurrentUser();
se_input = (EditText) findViewById(R.id.se_input);
results_list = (RecyclerView) findViewById(R.id.results_list);
results_list.setHasFixedSize(true);
results_list.setLayoutManager(new LinearLayoutManager(this));
results_list.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
/*
* Create a array list for each node you want to use
*/
fullNameList = new ArrayList<>();
userNameList = new ArrayList<>();
userIdList = new ArrayList<>();
profileImageList = new ArrayList<>();
se_input.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
if (!s.toString().isEmpty()) {
setAdapter(s.toString());
} else {
/*
* Clear the list when editText is empty
*/
fullNameList.clear();
userNameList.clear();
userIdList.clear();
profileImageList.clear();
results_list.removeAllViews();
}
}
});
}
private void setAdapter(final String searchedString) {
mUDB.child("Users").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
/*
* Clear the list for every new search
*/
fullNameList.clear();
userNameList.clear();
userIdList.clear();
profileImageList.clear();
results_list.removeAllViews();
int counter = 0;
/*
* Search all users for matching searched string
*/
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
String uid = snapshot.getKey();
String full_name = snapshot.child("name").getValue(String.class);
String user_name = snapshot.child("username").getValue(String.class);
String profile_pic = snapshot.child("image").getValue(String.class);
if (full_name.toLowerCase().contains(searchedString.toLowerCase())) {
fullNameList.add(full_name);
userNameList.add(user_name);
userIdList.add(uid);
profileImageList.add(profile_pic);
counter++;
} else if (user_name.toLowerCase().contains(searchedString.toLowerCase())) {
fullNameList.add(full_name);
userNameList.add(user_name);
userIdList.add(uid);
profileImageList.add(profile_pic);
counter++;
}
/*
* Get maximum of 15 searched results only
*/
if (counter == 15)
break;
}
searchAdapter = new SearchAdapter(Search.this, fullNameList, userNameList, userIdList, profileImageList);
results_list.setAdapter(searchAdapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
SearchAdapter Class:
public class SearchAdapter extends RecyclerView.Adapter<SearchAdapter.SearchViewHolder> {
Context context;
ArrayList<String> fullNameList,userNameList, userIdList,profileImageList;
class SearchViewHolder extends RecyclerView.ViewHolder
{
ImageView profileImage;
TextView full_name, user_name,user_id;
public SearchViewHolder(View itemView) {
super(itemView);
profileImage = (ImageView) itemView.findViewById(R.id.profileImage);
full_name = (TextView) itemView.findViewById(R.id.full_name);
user_name = (TextView) itemView.findViewById(R.id.user_name);
user_id = (TextView) itemView.findViewById(R.id.user_id);
}
}
public SearchAdapter(Context context, ArrayList<String> fullNameList, ArrayList<String> userNameList, ArrayList<String> userIdList, ArrayList<String> profileImageList) {
this.context = context;
this.fullNameList = fullNameList;
this.userNameList = userNameList;
this.userIdList = userIdList;
this.profileImageList = profileImageList;
}
#Override
public SearchAdapter.SearchViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.search_list_item, parent, false);
return new SearchAdapter.SearchViewHolder(view);
}
#Override
public void onBindViewHolder(final SearchViewHolder holder, int position) {
holder.full_name.setText(fullNameList.get(position));
holder.user_name.setText(userNameList.get(position));
holder.user_id.setText(userIdList.get(position));
Glide.with(context).load(profileImageList.get(position)).into(holder.profileImage);
}
#Override
public int getItemCount() {
return fullNameList.size();
}
}
User Profile Class:
public class UserProfile extends AppCompatActivity {
private CircleImageView u_pro_img;
private TextView u_user_name, u_fullname, u_bio, u_fricou;
private Button add_fri;
private DatabaseReference mUDBR;
private TextView user_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile);
u_pro_img = (CircleImageView) findViewById(R.id.u_pro_img);
u_user_name = (TextView) findViewById(R.id.u_user_name);
u_fullname = (TextView) findViewById(R.id.u_fullname);
u_bio = (TextView) findViewById(R.id.u_bio);
u_fricou = (TextView) findViewById(R.id.u_fricou);
add_fri = (Button) findViewById(R.id.add_fri);
mUDBR = FirebaseDatabase.getInstance().getReference();
user_id = (TextView) findViewById(R.id.user_id);
}
}
I just want to pass the user id key to user profile activity when the user selects the person from the results. I hope you understand me.
Use below code to send userId to ProfileActivity(Here sending data from SearchAdapter class )
#Override
public void onBindViewHolder(final SearchViewHolder holder, int position) {
holder.full_name.setText(fullNameList.get(position));
holder.user_name.setText(userNameList.get(position));
holder.user_id.setText(userIdList.get(position));
Glide.with(context).load(profileImageList.get(position)).into(holder.profileImage);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//for sending data UserProfile
Intent intent = new Intent(context,UserProfile.class);
intent.putExtra("USER_ID",String.valueOf(userIdList.get(position)));
context.startActivity(intent);
}
});
}
on your UserProfile.cass get userId by following way :
String userId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile);
u_pro_img = (CircleImageView) findViewById(R.id.u_pro_img);
u_user_name = (TextView) findViewById(R.id.u_user_name);
u_fullname = (TextView) findViewById(R.id.u_fullname);
u_bio = (TextView) findViewById(R.id.u_bio);
u_fricou = (TextView) findViewById(R.id.u_fricou);
add_fri = (Button) findViewById(R.id.add_fri);
mUDBR = FirebaseDatabase.getInstance().getReference();
user_id = (TextView) findViewById(R.id.user_id);
//Getting data here UserId
userId = getIntent().getStringExtra("USER_ID","");
Toast toast=Toast.makeText(getApplicationContext(),"USER ID "+userId ,Toast.LENGTH_SHORT);
}}
I want to display Login user details in RecyclerView from Firebase database but I am facing the following error:
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type.
This is my model class:
public class StreetClass {
private String id;
private String semail;
private String sname;
private String stype;
private String sdetail;
private String slocation;
private String sdate;
private String imgurl;
public StreetClass(){}
public StreetClass(String id, String semail, String sname, String stype, String sdetail, String slocation, String sdate, String imgurl) {
this.id = id;
this.semail = semail;
this.sname = sname;
this.stype = stype;
this.sdetail = sdetail;
this.slocation = slocation;
this.sdate = sdate;
this.imgurl = imgurl;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSemail() {
return semail;
}
public void setSemail(String semail) {
this.semail = semail;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getStype() {
return stype;
}
public void setStype(String stype) {
this.stype = stype;
}
public String getSdetail() {
return sdetail;
}
public void setSdetail(String sdetail) {
this.sdetail = sdetail;
}
public String getSlocation() {
return slocation;
}
public void setSlocation(String slocation) {
this.slocation = slocation;
}
public String getSdate() {
return sdate;
}
public void setSdate(String sdate) {
this.sdate = sdate;
}
public String getImgurl() {
return imgurl;
}
public void setImgurl(String imgurl) {
this.imgurl = imgurl;
}
}
recyclerview Adapter class:
public class StreetAdapter extends RecyclerView.Adapter<StreetAdapter.ViewHolder> {
Context context;
private List<StreetClass>listdata ;
public StreetAdapter(Context context, List<StreetClass> list) {
this.listdata = list;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.show_items, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
StreetClass AllDetails = listdata.get(position);
holder.NameTextView.setText(AllDetails.getSname());
holder.DetailTextView.setText(AllDetails.getSdetail());
holder.DateTextView.setText(AllDetails.getSdate());
holder.LocationTextView.setText(AllDetails.getSlocation());
holder.TypeTextView.setText(AllDetails.getStype());
Picasso.with(context).load(AllDetails.getImgurl()).resize(120, 60).into(holder.ImageTextView);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = holder.getAdapterPosition();
final Intent intent;
if (position == 0){
intent = new Intent(context, ShowStreetDetails.class);
} else if (position == 1){
intent = new Intent(context, ElectricityActivity.class);
} else {
intent = new Intent(context, Water_Supply_Activity.class);
}
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return listdata.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public TextView NameTextView;
public TextView DetailTextView;
public TextView DateTextView;
public TextView LocationTextView;
public TextView TypeTextView;
public ImageView ImageTextView;
public ViewHolder(View itemView) {
super(itemView);
NameTextView = itemView.findViewById(R.id.ShowNameTextView);
DetailTextView = itemView.findViewById(R.id.ShowDetailTextView);
DateTextView = itemView.findViewById(R.id.ShowDateTextView);
LocationTextView = itemView.findViewById(R.id.ShowLocationTextView);
TypeTextView = itemView.findViewById(R.id.ShowTypeTextView);
ImageTextView = itemView.findViewById(R.id.ShowImageView);
}
}
}
Here I store my all data:
StreetClass street = new StreetClass();
street.setSname(nameString);
street.setStype(typeString);
street.setSdetail(detailString);
street.setSlocation(locationString);
street.setSdate(dateString);
street.setImgurl(ImageUrl);
String RecordIDFromServer = databaseReference.push().getKey();
// Adding the both name and number values using student details class object using ID.
databaseReference.child(RecordIDFromServer).setValue(street);
// Showing Toast message after successfully data submit.
Toast.makeText(StreetActivity.this,"Data Inserted Successfully into Firebase Database", Toast.LENGTH_LONG).show();
Mainactivity
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference databaseStatus = rootRef.child("Street Problems");
String uid = firebaseAuth.getInstance().getCurrentUser().getUid();
databaseStatus.child(uid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot ds : snapshot.getChildren()) {
for (DataSnapshot dSnapshot : ds.getChildren()) {
StreetClass streetClass = dSnapshot.getValue(StreetClass.class);
Log.d("Show", streetClass.getSname() == null ? "" : streetClass.getSname());
list.add(streetClass);
}
adapter = new StreetAdapter(ShowStreetDetails.this, list);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
progressDialog.dismiss();
}
and this is my database structure
To get the name of a single user, please use the following code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference yourRef = rootRef.child("Street Problems").child(uid);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
StreetClass streetClass = ds.getValue(StreetClass.class);
Log.d("TAG", streetClass.getSname());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
yourRef.addListenerForSingleValueEvent(eventListener);
I see in your picture that you are using the push() method to create another node which is not necessary. You can simply add those properties beneath the uid.
The problem is that you have an extra forEach loop in your onDataChange method. Simply remove it and it should be fine:
#Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot dSnapshot : snapshot.getChildren()) {
StreetClass streetClass = dSnapshot.getValue(StreetClass.class);
Log.d("Show", streetClass.getSname() == null ? "" : streetClass.getSname());
list.add(streetClass);
}
adapter = new StreetAdapter(ShowStreetDetails.this, list);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
progressDialog.dismiss();
}
I'm doing saving post feature now. I want display all saved post in one activity. I have made an activity where is RecyclerView in which I store all of posts and I have made made PostRow activity already. I have this databse:
. I want to get all post which user has saved and i dont know how to get them from database. I have made PostAdapter:
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.PostViewHolder>{
private List<Post> mPostList;
private boolean mProcessLike = false;
private String mSinglePostId;
private Context mCtx;
private DatabaseReference mDatabaseUsers;
private FirebaseUser mCurrentUser;
public PostAdapter (List<Post> postList, DatabaseReference databaseUsers, Context ctx){
this.mPostList = postList;
this.mDatabaseUsers = databaseUsers;
this.mCtx = ctx;
this.mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
}
#Override
public PostAdapter.PostViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.post_row, parent, false);
PostViewHolder postViewHolder = new PostViewHolder(v);
return postViewHolder;
}
#Override
public void onBindViewHolder(final PostAdapter.PostViewHolder holder, int position) {
Post post = mPostList.get(position);
holder.setTitle(post.getTitle());
holder.setImage(post.getImage());
holder.setPostId(post.getPostId());
holder.setLikeButton(holder.getPostId());
holder.getView().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent postSingle = new Intent(mCtx, SinglePostActivity.class);
postSingle.putExtra("postId", holder.getPostId());
mCtx.startActivity(postSingle);
}
});
holder.getLikeBtn().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mProcessLike = true;
mDatabaseUsers.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (mProcessLike){
if(dataSnapshot.child("saved").hasChild(holder.getPostId())){
mDatabaseUsers.child("saved")
.child(holder.getPostId())
.removeValue();
mProcessLike = false;
}else {
mDatabaseUsers.child("saved")
.child(holder.getPostId())
.setValue("saved");
mProcessLike = false;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
}
#Override
public int getItemCount() {
return mPostList.size();
}
public static class PostViewHolder extends RecyclerView.ViewHolder{
private TextView mPostTitle;
private ImageView mPostImage;
private Context mCtx;
private DatabaseReference mDatabaseUsers;
private FirebaseUser mCurrentUser;
private ImageButton mLikeBtn;
private String postId;
private View mView;
public PostViewHolder(View itemView) {
super(itemView);
this.mPostTitle = (TextView) itemView.findViewById(R.id.post_title);
this.mPostImage = (ImageView) itemView.findViewById(R.id.post_image);
this.mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
this.mDatabaseUsers = FirebaseDatabase.getInstance().getReference().child("Users").child(mCurrentUser.getUid());
this.mLikeBtn = (ImageButton) itemView.findViewById(R.id.like_btn);
this.mCtx = itemView.getContext();
this.mView = itemView;
}
public void setTitle(String title){
mPostTitle.setText(title);
}
public void setImage(String image){
Picasso.with(mCtx).load(image).into(mPostImage);
}
public void setPostId(String id){
this.postId = id;
}
public String getPostId(){
return this.postId;
}
public void setLikeButton(final String postKey) {
mDatabaseUsers.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.child("saved").hasChild(postKey)){
mLikeBtn.setImageResource(R.drawable.ic_favorite_pink_48dp);
}else{
mLikeBtn.setImageResource(R.drawable.ic_favorite_black_24dp);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public ImageButton getLikeBtn() {
return this.mLikeBtn;
}
public View getView() {
return this.mView;
}
}
}
I recommend changing your database structure, more specifically on the books node, to something like this:
{
"books":{
"2ExF2vKltibqCbE0oVOEHkYSRi2":{ /* the user key*/
/*list of books saved by that user*/
"-L2L2UgB...":{
"title":"Title goes here"
},
"-anotherBookKey":{
"title":"Title goes here"
}
},
"anotherUserKey":{
"hisSavedBookKey":{
"title":"Title goes here"
}
}
},
"users" : {
"2ExF2vKltibqCbE0oVOEHkYSRi2" : {
"image" : "...",
"name" : "Karol546",
"saved" : {
"-L2L2UgB...":"saved"
},
"thumb_image" : "default"
},
}
}
And when you want to list all books saved by the user 2ExF2vKltibqCbE0oVOEHkYSRi2, you'd use this DatabaseReference:
String userId = "2ExF2vKltibqCbE0oVOEHkYSRi2";
DatabaseReference savedRef = FirebaseDatabase.getInstance()
.getReference().child("books").child(userId);