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

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);
}

Related

Firebase UI : RecyclerView items are not shown

I have been trying to implement Firebase-UI in my app with RecyclerView.
I created a recyclerView users list in a chat app with Realtime database and Firebase-UI, I wanted to retrieve data from ProfileActivity and display them in my AllUsersActivity. The issue is that the RecyclerView items are not displaying and I'm getting this error :
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.schoolteacher, PID: 19631
java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.database.ChildEventListener com.google.firebase.database.Query.addChildEventListener(com.google.firebase.database.ChildEventListener)' on a null object reference
at com.firebase.ui.database.FirebaseArray.onCreate(FirebaseArray.java:54)
at com.firebase.ui.common.BaseObservableSnapshotArray.addChangeEventListener(BaseObservableSnapshotArray.java:97)
at com.firebase.ui.database.FirebaseRecyclerAdapter.startListening(FirebaseRecyclerAdapter.java:52)
at com.example.schoolteacher.AllUsersActivity.onStart(AllUsersActivity.java:112)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1419)
at android.app.Activity.performStart(Activity.java:7479)
at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3454)
at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:180)
at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:165)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:142)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:70)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2199)
at android.os.Handler.dispatchMessage(Handler.java:112)
at android.os.Looper.loop(Looper.java:216)
at android.app.ActivityThread.main(ActivityThread.java:7625)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)
Here is my code :
AllUsersActivity.java
public class AllUsersActivity extends AppCompatActivity {
private DatabaseReference mUsersDatabase;
private LinearLayoutManager linearLayoutManager;
private RecyclerView recyclerView;
private Query query;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_users);
recyclerView = findViewById(R.id.recycler_view);
linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
query = FirebaseDatabase.getInstance().getReference().child("Users");
}
FirebaseRecyclerOptions<Users> options = new FirebaseRecyclerOptions.Builder<Users>()
.setQuery(query, Users.class)
.build();
FirebaseRecyclerAdapter adapter = new FirebaseRecyclerAdapter<Users, UsersViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull UsersViewHolder holder, int position, #NonNull Users model) {
holder.setName(model.getName());
}
#Override
public UsersViewHolder 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.activity_all_users, parent, false);
return new UsersViewHolder(view);
}
};
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
}
class UsersViewHolder extends RecyclerView.ViewHolder {
View mView;
UsersViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setName(String name) {
TextView mName = mView.findViewById(R.id.user_single_name);
mName.setText(name);
}
}
ProfileInfoActivity
public class ProfileInfoActivity extends AppCompatActivity {
private DatabaseReference mDatabaseReference;
private FirebaseUser mCurrentUser;
private CircleImageView mDisplayImage;
private TextView mName;
private TextInputEditText mEditName, mEmail;
private TextView mStatus;
private ImageButton mStatusBtn;
private static final int GALLERY_PICK = 1;
private StorageReference mImageStorage;
private ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_info);
mDisplayImage = findViewById(R.id.circle_image);
mName = findViewById(R.id.name);
mEditName = findViewById(R.id.et_name);
mEmail = findViewById(R.id.et_email_address);
mStatus = findViewById(R.id.status);
mStatusBtn = findViewById(R.id.status_btn);
mImageStorage = FirebaseStorage.getInstance().getReference();
mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
String userID = mCurrentUser.getUid();
mDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child(userID);
mDatabaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String name = dataSnapshot.child("name").getValue().toString();
String et_name = dataSnapshot.child("name").getValue().toString();
String et_email_adress = dataSnapshot.child("email").getValue().toString();
String image = dataSnapshot.child("image").getValue().toString();
String status = dataSnapshot.child("status").getValue().toString();
String thumb_image = dataSnapshot.child("thumb_image").getValue().toString();
mName.setText(name);
mEditName.setText(et_name);
mEmail.setText(et_email_adress);
mStatus.setText("Teacher at "+ status);
Picasso.get().load(image).into(mDisplayImage);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
mDisplayImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(galleryIntent, "SELECT IMAGE"), GALLERY_PICK);
}
});
mStatusBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//send status data to changeSchoolActivity to retrieve it
String status_value = mStatus.getText().toString();
Intent status_intent = new Intent(ProfileInfoActivity.this, ChangeSchoolActivity.class);
status_intent.putExtra("status_value", status_value);
startActivity(status_intent);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GALLERY_PICK && resultCode == RESULT_OK ) {
Uri imageUri = data.getData();
CropImage.activity(imageUri)
.setAspectRatio(1, 1)
.start(this);
//Toast.makeText(ProfileInfoActivity.this, imageUri, Toast.LENGTH_SHORT).show();
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
mProgressDialog = new ProgressDialog(ProfileInfoActivity.this);
mProgressDialog.setTitle("Uploading Image...");
mProgressDialog.setMessage("Please wait while we upload and process the image");
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.show();
Uri resultUri = result.getUri();
String current_user_id = mCurrentUser.getUid();
final StorageReference filepath = mImageStorage.child("profile_images").child(current_user_id + ".jpg");
filepath.putFile(resultUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
filepath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String download_url = uri.toString();
mDatabaseReference.child("image").setValue(download_url).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
mProgressDialog.dismiss();
Toast.makeText(ProfileInfoActivity.this,"Success Uploading",Toast.LENGTH_SHORT).show();
}
});
}
});
}
});
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
}
According to your last comment:
protected void onStart() { super.onStart(); firebaseRecyclerAdapter.startListening(); }
Is the line at which the error occurs. To solve this, please create the firebaseRecyclerAdapter variable as a global variable by adding the following line of code:
private FirebaseRecyclerAdapter firebaseRecyclerAdapter;
Right after:
private Query query;
And remove the type declaration from your code:
//FirebaseRecyclerAdapter does not exist anymore
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Users, UsersViewHolder>(firebaseRecyclerOptions) {
#NonNull
#Override
public UsersViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View mView = LayoutInflater.from(parent.getContext()).inflate(R.layout.users_single_layout, parent, false);
return new UsersViewHolder(mView);
}
#Override
protected void onBindViewHolder(#NonNull UsersViewHolder holder, int position, #NonNull Users model) {
holder.setName(model.getName());
}
};

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 set ProgressBar value using this code?

I've two values in my document which will help me to set progress bar in the app.
for ex joined and slots. both are numbers.
and below i am fetching the values and setting the progressbar value using the slots and joined number which i fetched from the firestore :
public class Home extends AppCompatActivity {
private FirebaseFirestore mDatabase;
private FirestoreRecyclerAdapter adapter;
RecyclerView recyclerView;
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
FirebaseAuth mAuth = FirebaseAuth.getInstance();
FirebaseUser mUser = mAuth.getCurrentUser();
mDatabase = FirebaseFirestore.getInstance();
recyclerView = findViewById(R.id.rv);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
if (mUser != null) {
fetch();
} else {
Intent intent = new Intent(Home.this, Login.class);
startActivity(intent);
finish();
}
}
private void fetch() {
Query query = mDatabase.collection("batches");
FirestoreRecyclerOptions<batches> options = new FirestoreRecyclerOptions.Builder<batches>()
.setQuery(query, new SnapshotParser<batches>() {
#NonNull
#Override
public matches parseSnapshot(#NonNull DocumentSnapshot snapshot) {
return new matches(
snapshot.getLong("slots"),
snapshot.getLong("joined")
);
}
}).build();
adapter = new FirestoreRecyclerAdapter<batches,BatchHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull BatchHolder holder, int position, #NonNull batches model) {
holder.progressBar.setProgress(model.getJoined().intValue()/model.getSlots().intValue()*100);
}
#NonNull
#Override
public BatchHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_items,viewGroup,false);
return new BatchHolder(view);
}
};
recyclerView.setAdapter(adapter);
}
public class BatchHolder extends RecyclerView.ViewHolder {
ProgressBar progressBar;
public BatchHolder(#NonNull View itemView) {
super(itemView);
progressBar = itemView.findViewById(R.id.progressBar);
}
}
and in batches.class :
public class batches {
private Long slots, joined;
public matches(Long slots, Long joined) {
this.slots = slots;
this.joined = joined;
}
public Long getSlots() {
return slots;
}
public void setSlots(Long slots) {
this.slots = slots;
}
public Long getJoined() {
return joined;
}
public void setJoined(Long joined) {
this.joined = joined;
}
but when i run the app it says the following error :
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ProgressBar.setProgress(int)' on a null object reference
at app.Home$2.onBindViewHolder(Home.java:109)
at app.Home$2.onBindViewHolder(Home.java:100)
at com.firebase.ui.firestore.FirestoreRecyclerAdapter.onBindViewHolder(FirestoreRecyclerAdapter.java:125)
at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6781)
at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6823)
at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5752).... so on

picasso does not load image on start of appication

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.

Categories