picasso does not load image on start of appication - java

I have used picasso on my MainActivity. On start of application it does not load image from the firebase link. However, when i go to another activity and go back, it starts loading image and show it. Actually, i am trying to get user image according to user ID (uid) in post.
My MainActivity code:
P.S. Sorry for such ugly coding, I am very beginner.
String userImage = null;
String postKey = null;
String uid = null;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDatabase = FirebaseDatabase.getInstance().getReference().child("Posts");
mDatabaseUsers = FirebaseDatabase.getInstance().getReference("Users");
mUsers = FirebaseDatabase.getInstance().getReference("Users");
mDatabaseUsers.keepSynced(true);
mAuth = FirebaseAuth.getInstance();
mPostList = findViewById(R.id.postList);
mPostList.setHasFixedSize(true);
mPostList.setLayoutManager(new LinearLayoutManager(this));
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
final FirebaseRecyclerAdapter<Post, PostViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Post, PostViewHolder>(
Post.class,
R.layout.post_row,
PostViewHolder.class,
mDatabase) {
#Override
protected void populateViewHolder(PostViewHolder viewHolder, Post model, int position) {
postKey = getRef(position).getKey();
viewHolder.setImage(getUserImage());
viewHolder.setFrom(model.getFrom());
viewHolder.setTo(model.getTo());
viewHolder.setPrice(model.getPrice());
viewHolder.setDate(model.getDate());
viewHolder.setDate(model.getDate());
viewHolder.setCar(model.getCar());
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent particularPostIntent = new Intent(MainActivity.this, ParticularPostActivity.class);
particularPostIntent.putExtra("PostId", postKey);
startActivity(particularPostIntent);
}
});
}
};
mPostList.setAdapter(firebaseRecyclerAdapter);
}
public static class PostViewHolder extends RecyclerView.ViewHolder {
View mView;
public PostViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setFrom(String from){
TextView postFrom = mView.findViewById(R.id.rowFrom);
postFrom.setText("From: " +from);
}
public void setTo(String to){
TextView postTo = mView.findViewById(R.id.rowTo);
postTo.setText("To: " + to);
}
public void setPrice(String price){
TextView postPrice = mView.findViewById(R.id.rowPrice);
postPrice.setText("Price: " + price);
}
public void setDate(String date){
TextView postDate = mView.findViewById(R.id.rowDate);
postDate.setText("Date: " + date);
}
public void setCar(String car){
TextView postCar = mView.findViewById(R.id.rowCar);
postCar.setText("Car: " + car);
}
public void setImage(String image){
ImageView userImageView = mView.findViewById(R.id.rowProfileImage);
Picasso.with(mView.getContext()).setLoggingEnabled(true);
Picasso.with(mView.getContext()).load(image).placeholder(R.mipmap.ic_account_circle_black_48dp).into(userImageView);
}
}
public String getUserImage(){
mDatabase.child(postKey).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
uid = (String) dataSnapshot.child("userID").getValue();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mUsers.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
userImage = (String) dataSnapshot.child(uid).child("Image").getValue();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return userImage;
}

To solve this, i recomand you using Glide instead of Picasso. To make it work, add the following line of code in the dependencies of your build.gradle (Module: app) file.
compile 'com.github.bumptech.glide:glide:3.7.0'
To display the image just use the following line of code:
Glide.with(getApplicationContext())
.load(photoUrl)
.centerCrop()
.transform(new CircleTransform(getApplicationContext()))
.override(45,45)
.into(imageView);
Where photoUrl is the actual url of your photo and imageView is the ImageView where you want to display the photo.

Related

I have this error : "Can't convert object of type java.lang.String to type com.flashpub.flash.imageSection" and i don't know why

I've created a listView, and since i'm opening one of the item, the application need to fetch all image of the application, but it's doesn't work, i can't figure it out why that's showing me this error.
Thank you for helping !
That's my model on Firebase :
imageSection.java
package com.flashpub.flash;
import java.util.List;
public class imageSection {
String imageUrl;
public imageSection(){
}
public imageSection(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getImageUrl() {
return imageUrl;
}
}
chooseSection.java
package com.flashpub.flash;
import java.util.List;
public class chooseSection {
String sectionn;
public chooseSection() {
}
public chooseSection(String sectionn) {
this.sectionn = sectionn;
}
public String getSectionn() {
return sectionn;
}
}
chooseSectionActivity.java
public class ChooseSectionActivity extends AppCompatActivity {
ListView listView;
FirebaseListAdapter<chooseSection> adapter;
chooseSection sectionChosse;
//private HashMap<Integer, String> allItemsList = new HashMap<Integer, String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choose_section);
listView = findViewById(R.id.listView);
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference();
myRef.keepSynced(true);
Query query = FirebaseDatabase.getInstance().getReference().child("Sections");
Log.i("salut", query.toString());
FirebaseListOptions<chooseSection> options = new FirebaseListOptions.Builder<chooseSection>()
.setLayout(R.layout.section_list)
.setQuery(query,chooseSection.class)
.build();
adapter = new FirebaseListAdapter<chooseSection>(options) {
#Override
protected void populateView(#NonNull View view, #NonNull chooseSection model, int position) {
TextView sectionView = (TextView) view.findViewById(R.id.sectionView);
sectionView.setText(model.getSectionn());
chooseSection lu = sectionChosse;
//String LatLng = lu.getLocationUserLatitude() + "," + lu.getLocationUserLongitude();
//allItemsList.put(position, model.getSectionn());
}
};
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//String item = allItemsList.get(position);
Intent intent = new Intent(ChooseSectionActivity.this, PubsSectionActivity.class);
//intent.putExtra("key", item);
startActivity(intent);
}
});
listView.setAdapter(adapter);
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
}
PubsSectionActivity.java
public class PubsSectionActivity extends AppCompatActivity {
ViewFlipper viewFlipp;
private DatabaseReference databaseReference;
private List<imageSection> slideLists;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pubs_section);
viewFlipp = findViewById(R.id.viewFlipper);
databaseReference = FirebaseDatabase.getInstance().getReference();
slideLists = new ArrayList<>();
}
#Override
protected void onStart() {
super.onStart();
usingFirebaseDatabase();
}
private void usingFirebaseDatabase() {
String lolipop = "Coiffeur";
databaseReference.child("Sections/Restaurant")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
slideLists.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
imageSection model = snapshot.getValue(imageSection.class);
slideLists.add(model);
}
Toast.makeText(PubsSectionActivity.this, "All data fetched", Toast.LENGTH_SHORT).show();
usingFirebaseImages(slideLists);
} else {
Toast.makeText(PubsSectionActivity.this, "No images in firebase", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(PubsSectionActivity.this, "NO images found \n" + databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
private void usingFirebaseImages(List<imageSection> slideLists) {
for (int i = 0; i < slideLists.size(); i++) {
String downloadImageUrl = slideLists.get(i).getImageUrl();
Toast.makeText(this, downloadImageUrl, Toast.LENGTH_LONG).show();
ImageView imageView = new ImageView(this);
Picasso.get().load(downloadImageUrl).fit().centerCrop().into(imageView);
viewFlipp.addView(imageView);
viewFlipp.setInAnimation(this, android.R.anim.slide_in_left);
viewFlipp.setOutAnimation(this, android.R.anim.slide_out_right);
}
}
}
Help me please, i'm stuck !!
i don't know why there is this error...
You're attaching a listener to Sections/Restaurant. Since that is one specific restaurant, you don't need to loop over the children in onDataChange.
So:
databaseReference.child("Sections/Restaurant")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
slideLists.clear();
imageSection model = snapshot.getValue(imageSection.class);
slideLists.add(model);
Toast.makeText(PubsSectionActivity.this, "All data fetched", Toast.LENGTH_SHORT).show();
usingFirebaseImages(slideLists);
} else {
Toast.makeText(PubsSectionActivity.this, "No images in firebase", Toast.LENGTH_SHORT).show();
}
}

onbindViewholder include null object

When I run the activity it shows me items that I want plus a null card view(when i delete tostring() from holder.setTitle("product name:"+model.getName().toString()); I'm trying so hard to solve this problem but I didn't find a solution.
this is my class Client_order:
public class Client_order extends AppCompatActivity {
FragmentManager fragmentManager;
Fragment Settingsfrag,Orderfrag,panierfrag;
TextView delorder;
Order model2;
Button submit;
DatabaseReference ref,ref1,ref2;
private Toolbar hometoolbar;
private ImageView settingsbtn, orderIV, imageView7,imageView10;
private RecyclerView orderrv;
private FirebaseAuth mAuth;
private FirebaseUser currentUser;
private DatabaseReference mDatabase;
private String user_id;
Spinner spinnerorder;
private String name;
private String email;
private String phone;
TextView tvName;
Orderviewholder holder1;
private FirebaseRecyclerAdapter<Order, Orderviewholder> orderAdapter;
DatabaseReference dborder,dbpanier;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client_order);
tvName = findViewById(R.id.tvName);
hometoolbar = findViewById(R.id.hometoolbarorder);
hometoolbar.setTitle("ordre");
hometoolbar.setTitleTextColor(Color.WHITE);
settingsbtn = findViewById(R.id.settingsbtn);
orderIV = findViewById(R.id.orderIV);
imageView7 = findViewById(R.id.imageView7);
fragmentManager=getSupportFragmentManager();
Orderfrag=fragmentManager.findFragmentById(R.id.orderfrag);
Settingsfrag=fragmentManager.findFragmentById(R.id.settingsfrag);
mAuth = FirebaseAuth.getInstance();
currentUser = mAuth.getCurrentUser();
mDatabase = FirebaseDatabase.getInstance().getReference();
if (currentUser == null) {
Intent intent=new Intent(Client_order.this,Login.class);
startActivity(intent);
} else {
if (!mAuth.getCurrentUser().isEmailVerified()) {
Toast.makeText(getApplicationContext(), "Please verify your email address", Toast.LENGTH_LONG).show();
Intent startActivity = new Intent(this, Login.class);
startActivity(startActivity);
finish();
} else {
user_id = currentUser.getUid();
}
}
Toast.makeText(getApplicationContext(),user_id, Toast.LENGTH_LONG).show();
panierfrag=fragmentManager.findFragmentById(R.id.panierfrag);
submit=findViewById(R.id.submit);
submit.setVisibility(View.VISIBLE);
fragmentManager.beginTransaction()
.hide(panierfrag)
.show(Orderfrag)
.hide(Settingsfrag)
.commit();
imageView7.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(Client_order.this,Client_panier.class);
startActivity(intent);
}
});
settingsbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fragmentManager.beginTransaction()
.hide(panierfrag)
.hide(Orderfrag)
.show(Settingsfrag)
.commit();
}
});
orderIV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fragmentManager.beginTransaction()
.hide(panierfrag)
.show(Orderfrag)
.hide(Settingsfrag)
.commit();
}
});
dborder = FirebaseDatabase.getInstance().getReference().child("order");
dborder.keepSynced(true);
orderrv = (RecyclerView) findViewById(R.id.orderrv);
DatabaseReference personsRef = FirebaseDatabase.getInstance().getReference().child("order").child(user_id.toString());
Query personsQuery = personsRef.orderByKey();
orderrv.hasFixedSize();
orderrv.setLayoutManager(new LinearLayoutManager(this));
FirebaseRecyclerOptions personsOptions = new FirebaseRecyclerOptions.Builder<Order>().setQuery(personsQuery, Order.class).build();
orderAdapter=new FirebaseRecyclerAdapter<Order, Orderviewholder>(personsOptions) {
#Override
protected void onBindViewHolder(#NotNull Orderviewholder holder, int position, #NotNull Order model) {
holder.setTitle("product name:"+model.getName().toString());
holder1=holder;
imageView10=holder.mView.findViewById(R.id.imageVieworder);
Picasso.get().load(model.getImage()).into(imageView10, new Callback() {
#Override
public void onSuccess() {
ProgressBar progressbar3;
progressbar3=holder1.mView.findViewById(R.id.progressBar4);
progressbar3.setVisibility(View.INVISIBLE);
}
#Override
public void onError(Exception e) {
}
});
holder.setdesc(model.getDesc().toString());
holder.setprice(model.getPrice());
holder.setquantity(model.getQuantity());
TextView status;
status=holder.mView.findViewById(R.id.statusorder);
status.setText(model.getStatus());
status.setVisibility(View.VISIBLE);
delorder=holder.mView.findViewById(R.id.orderDelbtn);
delorder.setText("done");
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
delorder.setVisibility(View.VISIBLE);
}
});
model2=model;
delorder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dborder.child(currentUser.getUid()).child(model2.getId()).removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NotNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(Client_order.this, "order deleted successfully", Toast.LENGTH_LONG).show();
}
}
});
}
});
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ref=FirebaseDatabase.getInstance().getReference().child("order").child(user_id.toString());
ref2=FirebaseDatabase.getInstance().getReference().child("order").child(user_id.toString()).child("submitted");
ref1=FirebaseDatabase.getInstance().getReference().child("order").child("admin");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NotNull DataSnapshot dataSnapshot) {
for (DataSnapshot orderSnapshot: dataSnapshot.getChildren()) {
Order category = orderSnapshot.getValue(Order.class);
//if (category!=null){
ref1.child(category.getId()).setValue(category);
Toast.makeText(Client_order.this,"product successfully submitted", Toast.LENGTH_LONG).show();
ref2.child(category.getId()).setValue(category);
ref.child(category.getId()).removeValue();
// }
}
}
#Override
public void onCancelled(#NotNull DatabaseError databaseError) {
}
});
}
});
}
#NotNull
#Override
public Orderviewholder onCreateViewHolder(#NotNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.product_list_itemorder, parent, false);
return new Orderviewholder(view);
}
};
orderrv.setAdapter(orderAdapter);
}
#Override
protected void onStart() {
super.onStart();
orderAdapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
orderAdapter.stopListening();
}
public static class Orderviewholder extends RecyclerView.ViewHolder{
View mView;
public Orderviewholder(View itemView){
super(itemView);
mView = itemView;
}
public void setTitle(String title){
TextView post_title = (TextView)mView.findViewById(R.id.order_name);
post_title.setText(title);
}
public void setdesc(String desc) {
TextView post_title = (TextView) mView.findViewById(R.id.order_description);
post_title.setText(desc);
}
public void setprice(int price) {
TextView post_title = (TextView) mView.findViewById(R.id.order_price);
post_title.setText(Integer.toString(price)+" dhs");
}
public void setquantity(int quantity) {
TextView post_title = (TextView) mView.findViewById(R.id.order_quantity);
post_title.setText(Integer.toString(quantity));
}
}
}
it shows me this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference
at com.omar.lazywork.Client_order$4.onBindViewHolder(Client_order.java:207)
at com.omar.lazywork.Client_order$4.onBindViewHolder(Client_order.java:204)

Can't convert object of type java.lang.String to type (Firebase,RecyclerView)

I got two RecyclerView on the same page at this moments which are Breakfast and Lunch RecyclerView but I am facing the following error Can't convert object of type java.lang.String to type com.example
It highlights this line
userRecordslist.add(ds.getValue(UserRecordsModel.class));
I have tried several ways.
but when I used this code , the data from different record was displayed in the Breakfast RecyclerView
myRef = FirebaseDatabase.getInstance().
getReference("UsersRecords").child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child(date_record);
these are the screenshots of my Firebase and my App. You can see both data from different record is displayed on the same RecyclerView.
and later I tried to use this "new" code for database reference, the data that was supposedly retrieved from Firebase was NOT be displayed on the Breakfast Recycler View and I got the Can't convert object of type java.lang.String to type error
myRef = FirebaseDatabase.getInstance().
getReference("UsersRecords").child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child(date_record).child("BreakfastRecord");
I want to fetch the data and display it in the "suppose" RecyclerView. Please help out.
This code for my PlanMeal activity:
//BUTTON
Button backBtn;
Button addMealBreakBtn;
Button addMealLunchBtn;
Button addMealDinnerBtn;
//DATABASE
FirebaseAuth mAuth;
FirebaseUser currentUser;
DatabaseReference userRecordRef, myRef,requiredCalorieRef, mylunchRef;
//TEXT VIEW
TextView userRequiredCalorie;
ArrayList<UserRecordsModel> userRecordslist;
RecyclerView recyclerView, recyclerViewlunch;
private RecyclerView.Adapter userRecordHolder;
//DATE
String date_record ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_plan_meal_user);
date_record = new SimpleDateFormat("yyMMdd", Locale.getDefault()).format(new Date());
//create a date string.
String date_n = new SimpleDateFormat("MMM dd, yyyy", Locale.getDefault()).format(new Date());
//get hold of textview.
TextView date = (TextView) findViewById(R.id.datePlanMeal);
//set it as current date.
date.setText(date_n);
//INI VIEWS
userRequiredCalorie= (TextView) findViewById(R.id.outputPlanMealCalorie);
//FIREBASE AUTH
mAuth = FirebaseAuth.getInstance();
currentUser=mAuth.getCurrentUser();
//DATABASE REFERENCE
myRef = FirebaseDatabase.getInstance().
getReference("UsersRecords").child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child(date_record);
/*mylunchRef=FirebaseDatabase.getInstance().
getReference("UsersRecords").child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child(date_record).child("LunchRecord");*/
//myRef = FirebaseDatabase.getInstance().getReference("UsersRecords").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
//mylunchRef = FirebaseDatabase.getInstance().getReference("UsersRecords").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
//RECYCLER VIEW
//*********BREAKFAST******************************************//
recyclerView = findViewById(R.id.userRecordRecylerView);
LinearLayoutManager manager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(manager);
recyclerView.setHasFixedSize(true);
//ADAPTER
userRecordslist = new ArrayList<>();
userRecordHolder = new UserRecordsHolder(userRecordslist);
recyclerView.setAdapter(userRecordHolder);
//*********LUNCH******************************************//
recyclerViewlunch = findViewById(R.id.userRecordRecylerViewLunch);
LinearLayoutManager manager1 = new LinearLayoutManager(this);
recyclerViewlunch.setLayoutManager(manager1);
recyclerViewlunch.setHasFixedSize(true);
//ADAPTER
userRecordslist = new ArrayList<>();
userRecordHolder = new UserRecordsHolder(userRecordslist);
recyclerViewlunch.setAdapter(userRecordHolder);
//BUTTON
addMealBreakBtn = (Button) findViewById(R.id.addMealBreakBtn);
backBtn = (Button)findViewById(R.id.backBtnPlan) ;
//**********************DATABASE REFERENCE FOR USER REQUIRED CALORIE***************************//
requiredCalorieRef = FirebaseDatabase.getInstance().getReference("Users").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
requiredCalorieRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String userCalorieSuggestion = String.valueOf((dataSnapshot.child("daily calorie").getValue()));
userRequiredCalorie.setText((userCalorieSuggestion +"kcal"));
/*String userCalorieSuggestion = Double.toString((Double) dataSnapshot.child("daily calorie").getValue());
showDailyCalorie.setText(("Daily Calorie Suggestion: " + userCalorieSuggestion +"kcal"));*/
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
//BACK BUTTON*************************************************
backBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent signIn = new Intent(PlanMealUser.this,HomepageUser.class);
startActivity(signIn);
}
});
//ADD MEAL BUTTONS**********************************************
addMealBreakBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent breakfast = new Intent(PlanMealUser.this,ViewProduct.class);
startActivity(breakfast);
}
});
addMealLunchBtn = (Button) findViewById(R.id.addMealLunchBtn);
addMealLunchBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent signIn = new Intent(PlanMealUser.this,ViewProduct_Lunch.class);
startActivity(signIn);
}
});
addMealDinnerBtn = (Button) findViewById(R.id.addMealDinnerBtn);
addMealDinnerBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent signIn = new Intent(PlanMealUser.this,ViewProduct.class);
startActivity(signIn);
}
});
}
#Override
protected void onStart() {
super.onStart();
if (myRef != null) {
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
userRecordslist = new ArrayList<>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
userRecordslist.add(ds.getValue(UserRecordsModel.class));
}
UserRecordsHolder userRecordHolder = new UserRecordsHolder(userRecordslist);
recyclerView.setAdapter(userRecordHolder);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(PlanMealUser.this, databaseError.getMessage(),
Toast.LENGTH_SHORT).show();
}
});
}
}
}
This is my Model :
package com.example.buddymealplanneruser.Child.UserRecords;
public class UserRecordsModel {
private String foodName;
private String foodCalorie;
//constructor
public UserRecordsModel (String foodName,
String foodCalorie
)
{
this.foodName = foodName;
this.foodCalorie = foodCalorie;
}
public UserRecordsModel(){
}
//Getter and Setter
public String getFoodName() {
return foodName;
}
public void setFoodName(String foodName) {
this.foodName = foodName;
}
public String getFoodCalorie() {
return foodCalorie;
}
public void setFoodCalorie(String foodCalorie) {
this.foodCalorie = foodCalorie;
}
}
This is my Adapter
public class UserRecordsHolder extends RecyclerView.Adapter<UserRecordsHolder.MyURHolder> {
Context context;
ArrayList<UserRecordsModel> userRecordslist;
public UserRecordsHolder (ArrayList<UserRecordsModel> userRecordslist)
{
this.userRecordslist=userRecordslist;
}
#NonNull
#Override
public MyURHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_user_records, viewGroup,false);
return new MyURHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyURHolder myURHolder, int i) {
myURHolder.foodName.setText(userRecordslist.get(i).getFoodName());
myURHolder.foodCalorie.setText(userRecordslist.get(i).getFoodCalorie());
}
#Override
public int getItemCount()
{
return userRecordslist.size();
}
class MyURHolder extends RecyclerView.ViewHolder
{
TextView foodName, foodCalorie;
public MyURHolder (#NonNull View itemView){
super(itemView);
foodName = itemView.findViewById(R.id.userRecordsFName);
foodCalorie = itemView.findViewById(R.id.userRecordsKcal);
}
}
}
Hope someone can help.
You'll need one more level beneath BreakfastRecord or LunchRecord:
UserRecords
UID
Date
BreakfastRecord
1
foodCalorie
foodName
2
foodCalorie
foodName
3
foodCalorie
foodName

How to get key from firebase using RecyclerView

I can get key and show in Log.d but it don't show in RecyclerView. What's wrong with it?
HistoryActivity.java it contains my recyclerView:
public class HistoryActivity extends AppCompatActivity {
FirebaseFirestore mFirestore;
FirebaseAuth firebaseAuth;
FirebaseDatabase database;
RecyclerView mHisList;
ArrayList<PreviousLst> history;
adt_rv_HisList adtRvHisList;
TextView ptName;
TextView ptPort;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
getSupportActionBar().setSubtitle("History");
Intent it = getIntent();
String patName = it.getStringExtra("nm");
String patID = it.getStringExtra("idpat");
String portNum = it.getStringExtra("pNum");
String regisDate = it.getStringExtra("rdate");
ptName = findViewById(R.id.txName);
ptPort = findViewById(R.id.portpassValue);
ptName.setText(patName);
ptPort.setText(portNum);
history = new ArrayList<>();
setupRecyclerView();
setupFireBase();
loadDataFromDatabase(portNum);
}
private void setupFireBase() {
mFirestore = FirebaseFirestore.getInstance();
firebaseAuth = FirebaseAuth.getInstance();
database = FirebaseDatabase.getInstance();
}
private void setupRecyclerView() {
mHisList = findViewById(R.id.rv_prev_lst);
mHisList.setHasFixedSize(true);
mHisList.setLayoutManager(new LinearLayoutManager(this));
mHisList.setAdapter(adtRvHisList);
}
public void loadDataFromDatabase(String portNum) {
if(history.size()>0)
history.clear();
DatabaseReference myRef;
DatabaseReference passref;
switch (portNum){
case "Huang-Yai0002":
String p2 = "NETEKG-Huang-Yai0002";
myRef = database.getReference("MACHINE");
passref = myRef.child(p2).child("value");
passref.addValueEventListener(new ValueEventListener(){
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
String keydate = postSnapshot.getKey();
Log.d(TAG, "Child are: " + keydate );
PreviousLst previousLst = new PreviousLst(keydate);
history.add(previousLst);
}
adtRvHisList = new adt_rv_HisList(HistoryActivity.this, history);
mHisList.setAdapter(adtRvHisList);
}
#Override
public void onCancelled(DatabaseError error) {
Log.w(TAG, "Failed to read value.", error.toException());
}
});
break;
case "Huang-Yai0003":
String p3 = "NETEKG-Huang-Yai0003";
myRef = database.getReference("MACHINE");
passref = myRef.child(p3).child("value");
passref.addValueEventListener(new ValueEventListener(){
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
String keydate = postSnapshot.getKey();
Log.d(TAG, "Child are: " + keydate );
PreviousLst previousLst = new PreviousLst(postSnapshot.getKey());
history.add(previousLst);
}
adtRvHisList = new adt_rv_HisList(HistoryActivity.this, history);
mHisList.setAdapter(adtRvHisList);
}
#Override
public void onCancelled(DatabaseError error) {
Log.w(TAG, "Failed to read value.", error.toException());
}
});
break;
default:
Log.d(TAG, "Value is: " + portNum);
Toast.makeText(getApplicationContext(),"Error...",Toast.LENGTH_LONG).show();
break;
}
}
}
adt_rv_HisList.java Adapter:
public class adt_rv_HisList extends RecyclerView.Adapter<adtrvHisListViewHolder> {
HistoryActivity historyActivity;
ArrayList<PreviousLst> history;
public adt_rv_HisList(HistoryActivity historyActivity, ArrayList<PreviousLst> history) {
this.history = history;
this.historyActivity = historyActivity;
}
#NonNull
#Override
public adtrvHisListViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(historyActivity.getBaseContext()).inflate(R.layout.hislist_item, viewGroup, false);
return new adtrvHisListViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull adtrvHisListViewHolder holder, int position) {
holder.hdate.setText(history.get(position).getHisDate());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialogView();
}
});
}
private void dialogView() {
final Dialog dia = new Dialog(historyActivity);
dia.setContentView(R.layout.dialog_ask_view);
dia.show();
Button pvgraph = (Button)dia.findViewById(R.id.bt_pvgraph);
Button pvhr = (Button)dia.findViewById(R.id.bt_pvhrate);
Button cc = (Button)dia.findViewById(R.id.btn_cancel);
cc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dia.dismiss();
}
});
pvgraph.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dia.dismiss();
Intent it = new Intent(historyActivity, ViewgraphActivity.class);
historyActivity.startActivity(it);
}
});
pvhr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dia.dismiss();
Intent it = new Intent(historyActivity, ViewHRActivity.class);
historyActivity.startActivity(it);
}
});
}
#Override
public int getItemCount() {
return 0;
}
}
adtrvHisListViewHolder.java Contains the ViewHolder :
public class adtrvHisListViewHolder extends RecyclerView.ViewHolder {
public TextView hdate;
public adtrvHisListViewHolder(View itemView) {
super(itemView);
hdate = itemView.findViewById(R.id.his_date);
}
}
PreviousLst.java is Model class for my recyclerView:
public class PreviousLst {
String HisDate;
public PreviousLst(String HisDate){
this.HisDate = HisDate;
}
public PreviousLst(){
}
public String getHisDate() {
return HisDate;
}
public void setHisDate(String hisDate) {
HisDate = hisDate;
}
}
This is my key that I get and show in Log.d
D/ContentValues: Child are: HEART RATE
D/ContentValues: Child are:LEAD 1
Child are: LEAD 2
Child are: LEAD 3
Child are: LEAD 4
Child are: LEAD 5
Child are: LEAD 6
but it don't shoe in App.
enter image description here
#Override
public int getItemCount() {
//return 0;
replace it with history.size();
}
the added lines tells the adapter how many items, the adapter has to bind the items to the recycler view. By default it is 0, means the adapter class will never call the binView method to show the items at view side

Exception when Intent Data to another Activity android.content.Context.getPackageName()

Hello guys iam trying to get Data to putExtra => Intent from an Adapter to another Activity but every time i try to get data from the Adapter to the Activity it Gives me this Exception that
java.lang.String android.content.Context.getPackageName()'
so i tried to Enter the Context class i found it too many Errors cant fix that till now
what makes me really Believe that the problem with the Context is that when i Tried to use TinyDB
it need to define the Object inside the Adapter
tinyDB = new TinyDB(mContext);
the program Crashed and Gives Me this Exception
W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
W/System.err: at android.content.ComponentName.<init>(ComponentName.java:128)
at android.content.Intent.<init>(Intent.java:4910)
at com.team.plustegara.Views.Models.Adapters.EventsAdapter$1.onClick(EventsAdapter.java:83)
at android.view.View.performClick(View.java:5647)
at android.view.View$PerformClick.run(View.java:22465)
at android.os.Handler.handleCallback(Handler.java:754)
at android.os.Handler.dispatchMessage(Handler.java:95)
W/System.err: at android.os.Looper.loop(Looper.java:163)
at android.app.ActivityThread.main(ActivityThread.java:6238)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
i tried to Fix that but still cant handle the Context problem
Here is my Adapter
public class EventsAdapter extends RecyclerView.Adapter<EventsAdapter.EventsHolder> {
public EventsAdapter(List<EventsModel> list, Context mContext) {
this.list = list;
this.mContext = mContext;
}
private List<EventsModel> list;
private Context mContext;
FirebaseAuth mAuth;
DatabaseReference dbRef;
#NonNull
#Override
public EventsHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.events_row_item, parent, false);
EventsHolder holder = new EventsHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull final EventsHolder holder, int position) {
final EventsModel listy = list.get(position);
holder.eventTitle.setText(listy.getTitle());
holder.eventDate.setText(listy.getEventDate());
holder.eventCosts.setText("Event Costs " + listy.getCosts());
Picasso.get()
.load(listy.getEventImage())
.fit()
.centerCrop()
.placeholder(R.drawable.gradients_card)
.into(holder.eventImage);
holder.cardViewEvents.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
Intent intent = new Intent(mContext, ShowActivityEvents.class);
intent.putExtra("EventImage", listy.getEventImage());
intent.putExtra("EventTitle", listy.getTitle());
intent.putExtra("EventDate", listy.getEventDate());
intent.putExtra("EventCosts", listy.getCosts());
intent.putExtra("EventDescription", listy.getDescription());
intent.putExtra("eventID", listy.getPostID());
mContext.startActivity(intent);
dbRef = FirebaseDatabase.getInstance().getReference("PlusTeam");
mAuth = FirebaseAuth.getInstance();
String userName = mAuth.getCurrentUser().getDisplayName();
String postID = listy.getPostID();
dbRef.child("Events").child(postID).child("Views").push().setValue(userName);
} catch (Exception e) {
e.printStackTrace();
}
}
});
String postID = listy.getPostID();
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("PlusTeam");
databaseReference.child("Events").child(postID).child("Views").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
long ViewsCount = dataSnapshot.getChildrenCount();
holder.txtViews.setText(String.valueOf(ViewsCount));
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toasty.error(mContext, databaseError.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
#Override
public int getItemCount() {
return list.size();
}
public class EventsHolder extends RecyclerView.ViewHolder {
#BindView(R.id.EventImageCard)
ImageView eventImage;
#BindView(R.id.txtEventTitle)
TextView eventTitle;
#BindView(R.id.txtEventDate)
TextView eventDate;
#BindView(R.id.txtEventCosts)
TextView eventCosts;
#BindView(R.id.cardView_EventsCard)
CardView cardViewEvents;
#BindView(R.id.txtEventsViews) TextView txtViews;
public EventsHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}
here is my Activity which receive the Extras from the Adapter
public class ShowActivityEvents extends AppCompatActivity {
DatabaseReference dbRef;
FirebaseAuth mAuth;
#Override
protected void onStart() {
super.onStart();
checkIfUserAlreadyAccepttheEvent();
}
private void checkIfUserAlreadyAccepttheEvent() {
final String postID = getIntent().getExtras().getString("eventID");
final String UserID = mAuth.getCurrentUser().getUid();
dbRef.child(postID).child("PeopleComing")
.addListenerForSingleValueEvent(new ValueEventListener() {
public static final String TAG = "ShowEvents";
#SuppressLint("SetTextI18n")
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Log.e(TAG, "onChildAdded: " + dataSnapshot);
String peopleCount = String.valueOf(dataSnapshot.getChildrenCount());
txtPeopleComing.setText( peopleCount + " People Comming");
if (dataSnapshot.child(UserID).exists()) {
btnIamIn.setEnabled(false);
} else {
btnIamIn.setEnabled(true);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toasty.error(ShowActivityEvents.this, "Error code : " + 1, Toast.LENGTH_LONG).show();
}
});
}
#BindView(R.id.btnIamIn)
Button btnIamIn;
#BindView(R.id.txtPeopleComingCount)
TextView txtPeopleComing;
#BindView(R.id.imgEventPost)
ImageView imgEvent;
#BindView(R.id.txtEventTitle) TextView txtEventTitle;
#BindView(R.id.txtEventDescription) TextView txtEventDescription;
#BindView(R.id.txtEventCost) TextView txtEventCost;
#BindView(R.id.txtEventDate) TextView txtEventDate;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_events2);
ButterKnife.bind(this);
dbRef = FirebaseDatabase.getInstance().getReference("PlusTeam");
mAuth = FirebaseAuth.getInstance();
try {
loadDataFromAdapter();
} catch (Exception e) {
e.printStackTrace();
}
}
private void loadDataFromAdapter() {
String Image = getIntent().getExtras().getString("EventImage");
String Title = getIntent().getExtras().getString("EventTitle");
String Date = getIntent().getExtras().getString("EventDate");
String Costs = getIntent().getExtras().getString("EventCosts");
String Description = getIntent().getExtras().getString("EventDescription");
GlideApp.with(this)
.load(Image)
.fitCenter()
.into(imgEvent);
txtEventTitle.setText(Title);
txtEventDescription.setText(Description);
txtEventDate.setText(Date);
txtEventCost.setText(Costs);
}
#OnClick(R.id.btnIamIn) public void addPersonToEvent(){
String UserName = mAuth.getCurrentUser().getDisplayName();
String userID = mAuth.getCurrentUser().getUid();
String postID = getIntent().getExtras().getString("eventID");
dbRef.child(postID)
.child("PeopleComing").setValue(UserName);
btnIamIn.setEnabled(false);
}
}
Finally just wanted to say i searched for this kind of Problem in Google and inside questions in Stack but didn't worked
so any Suggestions
You should pass your context in adapter like in the example below
Activity
adapter = new EventsAdapter(myList,MainActivity.this);
Fragment
adapter = new EventsAdapter(myList,getActivity());
Or another way
#Override
public void onClick(View v) {
v.getContext().startActivity(v.getContext(), ShowActivityEvents.class);
}

Categories