public class ShowingParticularProducts extends AppCompatActivity {
FirebaseFirestore mFirebaseFireStore;
private FirestoreRecyclerAdapter<ProductModel, showingParticularProductAdapter.showingParticularProductViewHolder> adapter;
public RecyclerView mRecyclerView;
List<String> AllProductName=new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_showing_particular_products);
mRecyclerView = findViewById(R.id.RecyclerViewParticularProducts);
mFirebaseFireStore = FirebaseFirestore.getInstance();
ImageView returnHome = findViewById(R.id.ImageViewHome);
ImageView Cart=findViewById(R.id.ImageViewCartParticularProducts);
String SearchText=getIntent().getStringExtra("SearchName");
loadAllProductName();
if(SearchText != null) {
List<String> suggest=new ArrayList<>();
for(String search:AllProductName) {
if (search.toLowerCase().contains(SearchText)) {
suggest.add(search.toLowerCase());
}
}
Query query1 = mFirebaseFireStore.collection("Products").whereIn("SearchID", Collections.singletonList(suggest));
FirestoreRecyclerOptions<ProductModel> options1 = new FirestoreRecyclerOptions.Builder<ProductModel>().setQuery(query1, ProductModel.class).build();
adapter = new showingParticularProductAdapter(options1);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setAdapter(adapter);
}
returnHome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ShowingParticularProducts.this, HomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
});
Cart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent cartActivity=new Intent(ShowingParticularProducts.this,CartActivity.class);
startActivity(cartActivity);
}
});
}
private void loadAllProductName() {
mFirebaseFireStore=FirebaseFirestore.getInstance();
Query query2=mFirebaseFireStore.collection("Products");
query2.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if(task.isSuccessful()){
for(QueryDocumentSnapshot queryDocumentSnapshot: Objects.requireNonNull(task.getResult())){
AllProductName.add(queryDocumentSnapshot.getString("Name"));
}
}
}
});
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
}
No data is showing in RecyclerView after query each data using loop with the field in firestore..First I have load all the name of product in a array list then I query whether each name contain the search text, if contain then show all the data acording to that in RecyclerView.I hope this is clear to everybody.
Related
In my case I have passed a data from recycler view to an another activity and in the second i have put a delete button. And on click of that delete button I want to delete that particular document. As I have passed position of the document with other fields and wrote a code like this in my second activity
private ActivityItemDetailsBinding binding;
FirebaseFirestore db;
ArrayList<DataModalClass> itemsData;
ItemsDataAdapterClass adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityItemDetailsBinding.inflate(getLayoutInflater());
View view = binding.getRoot();
setContentView(view);
itemsData = new ArrayList<>();
db.collection("items").orderBy("date", Query.Direction.DESCENDING).get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
List<DocumentSnapshot> itemsList = queryDocumentSnapshots.getDocuments();
for (DocumentSnapshot documentSnapshot : itemsList) {
DataModalClass dataModalClass = documentSnapshot.toObject(DataModalClass.class);
itemsData.add(dataModalClass);
}
}
});
db = FirebaseFirestore.getInstance();
int position = Integer.parseInt(getIntent().getStringExtra("position"));
Picasso.get().load(getIntent().getStringExtra("image")).into(binding.itemImageDetailImageView);
binding.itemTitleDetailTextView.setText(getIntent().getStringExtra("name"));
binding.itemBrandDetailTextView.setText(getIntent().getStringExtra("brand"));
binding.itemPriceDetailTextView.setText("₹" + getIntent().getStringExtra("price") + "/-");
if (getIntent().getStringExtra("stock").equals("0")) {
binding.itemStockDetailTextView.setText("Out of Stock");
binding.itemStockDetailTextView.setTextColor(Color.parseColor("#FF0000"));
} else {
binding.itemStockDetailTextView.setText("In stock (" + getIntent().getStringExtra("stock") + ")");
}
binding.itemDescriptionDetailTextView.setText(getIntent().getStringExtra("description"));
binding.itemCategoryDetailTextView.setText("Category: " + getIntent().getStringExtra("category"));
binding.deleteLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
db.collection("items").document(itemsData.get(position).getId()).delete()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
});
}
});
}
}```
but my app is crashing after opening this second activity
After Successful log in my SignIn activity intent to BloodBank activity and the activity check if there any Currentuser or not.
In my case when it comes to BloodBank activity after log in, the method returning current user is null always
Is there any idea how I can resolve this issue?
Here is my SignIn Activity.java
public class SignIn extends AppCompatActivity {
Button signIn,forgetPass;
TextView backToSignUp,number,password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
signIn=findViewById(R.id.signInButtonId);
forgetPass=findViewById(R.id.forgetPassButtonId);
backToSignUp=findViewById(R.id.signUpBack);
number=findViewById(R.id.signInNumberId);
password=findViewById(R.id.signInPasswordId);
signIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String _phone = number.getText().toString().trim();
final String _password = password.getText().toString().trim();
if (_phone.isEmpty()) {
number.setError("Enter Your Phone Number");
number.requestFocus();
return;
}
if (_password.isEmpty()) {
password.setError("Enter a password");
password.requestFocus();
return;
}
DatabaseReference reference= FirebaseDatabase.getInstance().getReference("BloodBank_users");
Query checkUser=reference.orderByChild("phone").equalTo(_phone);
checkUser.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
number.setError(null);
number.setEnabled(true);
String passwordFromDB = snapshot.child(_phone).child("password").getValue(String.class);
if (passwordFromDB.equals(_password)) {
password.setError(null);
password.setEnabled(true);
Intent intent = new Intent(getApplicationContext(),BloodBankMain.class);
startActivity(intent);
finish();
} else {
password.setError("Wrong Password Or User Name");
password.requestFocus();
}
}
else {
number.setError("This Number Is Not Registered");
number.requestFocus();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
});
}
}
Here is my BloodBank.Java
public class BloodBank extends AppCompatActivity {
private FirebaseAuth firebaseAuth;
FirebaseAuth.AuthStateListener mAuthListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_blood_bank);
firebaseAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener(){
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth){
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(user!=null){
Intent intent = new Intent(BloodBank.this, BloodBankMain.class);
startActivity(intent);
finish();
}
else{
Intent intent = new Intent(BloodBank.this,SignIn.class);
startActivity(intent);
finish();
}
}
};
}
#Override
protected void onStart() {
super.onStart();
firebaseAuth.addAuthStateListener(mAuthListener);
}
#Override
protected void onResume() {
super.onResume();
firebaseAuth.addAuthStateListener(mAuthListener);
}
#Override
protected void onStop() {
super.onStop();
firebaseAuth.removeAuthStateListener(mAuthListener);
}
}
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();
}
}
Thats the Fragment containing the recyclerView which leads to activity with Chat
public class FragmentBusinessHome extends Fragment {
/* For to do adapter */
private List<String> namesToDo;
private List<String> uids;
private List<String> servicesNames;
private AdapterToDo adapterToDo;
private RecyclerView toDoRecyclerView;
/* For checking requests adapter */
private List<String> userUids;
private List<String> serviceNames;
private List<String> userNames;
private AdapterPendingRequests adapterPendingRequests;
private RecyclerView pendingRequestsRecyclerView;
private FirebaseAuth mAuth;
public FragmentBusinessHome(){
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_business_home, container, false);
mAuth = FirebaseAuth.getInstance();
namesToDo = new ArrayList<>();
uids = new ArrayList<>();
servicesNames = new ArrayList<>();
userUids = new ArrayList<>();
serviceNames = new ArrayList<>();
userNames = new ArrayList<>();
toDoRecyclerView = view.findViewById(R.id.toDoRecyclerView);
pendingRequestsRecyclerView = view.findViewById(R.id.requestsToApproveRecyclerView);
LinearLayoutManager layoutManagerActive = new LinearLayoutManager(getActivity());
layoutManagerActive.setStackFromEnd(true);
layoutManagerActive.setReverseLayout(true);
toDoRecyclerView.setLayoutManager(layoutManagerActive);
LinearLayoutManager layoutManagerPendingRequests = new LinearLayoutManager(getActivity());
layoutManagerPendingRequests.setStackFromEnd(true);
layoutManagerPendingRequests.setReverseLayout(true);
pendingRequestsRecyclerView.setLayoutManager(layoutManagerPendingRequests);
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference checkRequests = FirebaseDatabase.getInstance().getReference("Providers").child(uid).child("Gigs");
checkRequests.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
if (ds.getValue(String.class).equals("active")) {
DatabaseReference getRequests = FirebaseDatabase.getInstance().getReference("Services").child(ds.getKey()).child(uid).child("Gigs").child("pending");
getRequests.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
serviceNames.clear(); userNames.clear(); userUids.clear();
for (DataSnapshot data : dataSnapshot.getChildren()) {
String userName = data.child("names").getValue(String.class);
String serviceName = ds.getKey();
String userUid = data.getKey();
userNames.add(userName);
serviceNames.add(serviceName);
userUids.add(userUid);
adapterPendingRequests = new AdapterPendingRequests(getActivity(), userUids, userNames, serviceNames, mAuth.getCurrentUser().getUid());
adapterPendingRequests.notifyDataSetChanged();
pendingRequestsRecyclerView.setAdapter(adapterPendingRequests);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
DatabaseReference getActive = FirebaseDatabase.getInstance().getReference("Services").child(ds.getKey()).child(uid).child("Gigs").child("active");
getActive.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
userUids.clear(); namesToDo.clear(); servicesNames.clear();
for(DataSnapshot datas : dataSnapshot.getChildren()){
String userUid = datas.getKey();
String userName = datas.child("names").getValue(String.class);
String serviceName = ds.getKey();
userUids.add(userUid);
namesToDo.add(userName);
servicesNames.add(serviceName);
Log.d("TAG", userUids.toString());
adapterToDo = new AdapterToDo(getActivity(), namesToDo, userUids, servicesNames);
adapterToDo.notifyDataSetChanged();
toDoRecyclerView.setAdapter(adapterToDo);
if(!userUids.isEmpty()){
LinearLayout toDoLayout = view.findViewById(R.id.toDoLayout);
toDoLayout.setVisibility(View.VISIBLE);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
return view;
}
}
Thats fragment's activity
private ImageButton moreBtn, chatsBtn;
private BottomNavigationView bottomNavigationView;
private FirebaseAuth mAuth;
private FirebaseUser mUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_business_home);
getSupportFragmentManager().beginTransaction().replace(R.id.fragmentContainer, new FragmentBusinessHome()).commit();
mAuth = FirebaseAuth.getInstance();
mUser = mAuth.getCurrentUser();
bottomNavigationView = findViewById(R.id.bottomNavigationView);
bottomNavigationView.setOnNavigationItemSelectedListener(navigationListener);
moreBtn = findViewById(R.id.moreBtn);
chatsBtn = findViewById(R.id.chatsBtn);
moreBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final PopupMenu popup = new PopupMenu(BusinessHomeActivity.this, moreBtn);
popup.getMenuInflater().inflate(R.menu.popup_toolbar_more_menu, popup.getMenu());
popup.show();
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()){
case R.id.sign_out_btn:
mAuth.signOut();
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
Intent to_login_activity = new Intent(BusinessHomeActivity.this, WelcomeActivity.class);
startActivity(to_login_activity);
finish();
}
}, 1000);
}
return true;
}
});
}
});
chatsBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(BusinessHomeActivity.this, "Will be available soon!", Toast.LENGTH_LONG).show();
}
});
}
private BottomNavigationView.OnNavigationItemSelectedListener navigationListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment selectedFragment = null;
switch (menuItem.getItemId()){
case R.id.home:
selectedFragment = new FragmentBusinessHome();
break;
case R.id.inbox:
selectedFragment = new FragmentInbox();
break;
case R.id.profile:
selectedFragment = new FragmentProfile();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragmentContainer, selectedFragment).commit();
return true;
}
};
That's the adapter for the fragment
public class AdapterToDo extends RecyclerView.Adapter<AdapterToDo.MyHolder> {
Context context;
List<String> namesToDo;
List<String> uids;
List<String> servicesNames;
public AdapterToDo(Context context, List<String> namesToDo, List<String> uids, List<String> servicesNames) {
this.context = context;
this.namesToDo = namesToDo;
this.uids = uids;
this.servicesNames = servicesNames;
}
#NonNull
#Override
public AdapterToDo.MyHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.to_do_item, parent, false);
return new AdapterToDo.MyHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final AdapterToDo.MyHolder holder, final int position) {
holder.userNames.setText(namesToDo.get(position));
String currentUid = uids.get(position);
String currentOppositeName = namesToDo.get(position);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent to_chat_activity = new Intent(context, ChatActivity.class);
to_chat_activity.putExtra("oppositeUid", currentUid);
to_chat_activity.putExtra("oppositeNames", currentOppositeName);
to_chat_activity.putExtra("class", getClass().getName());
context.startActivity(to_chat_activity);
}
});
}
#Override
public int getItemCount() {
return uids.size();
}
class MyHolder extends RecyclerView.ViewHolder {
private TextView userNames;
private MyHolder(#NonNull View itemView) {
super(itemView);
userNames = itemView.findViewById(R.id.userNames);
}
}
}
That is the Activity where the fragment's adapter leads to
private String oppositeUid, oppositeNames, className;
private TextView oppositeNamesTextView;
private Button sendBtn;
private EditText message;
private FirebaseAuth mAuth;
private RecyclerView recyclerView;
private List<ModelChat> modelChatList;
private AdapterChat chatAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
mAuth = FirebaseAuth.getInstance();
Intent intent = getIntent();
oppositeUid = intent.getStringExtra("oppositeUid");
oppositeNames = intent.getStringExtra("oppositeNames");
className = intent.getStringExtra("class");
Log.d("CLASSNAME", className);
modelChatList = new ArrayList<>();
oppositeNamesTextView = findViewById(R.id.oppositeNames);
sendBtn = findViewById(R.id.sendBtn);
message = findViewById(R.id.message);
recyclerView = findViewById(R.id.chatRecyclerView);
LinearLayoutManager linearLayout = new LinearLayoutManager(this);
linearLayout.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayout);
oppositeNamesTextView.setText(oppositeNames);
sendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String mMessage = message.getText().toString().trim();
if(!TextUtils.isEmpty(mMessage)){
HashMap<Object, String> hashMap = new HashMap<>();
hashMap.put("sender", mAuth.getCurrentUser().getUid());
hashMap.put("receiver", oppositeUid);
hashMap.put("message", mMessage);
hashMap.put("timestamp", String.valueOf(System.currentTimeMillis()));
if(className.equals("com.example.uploy.AdapterToDo$1")){
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Providers").child(mAuth.getCurrentUser().getUid()).child("Chats").child(oppositeUid);
databaseReference.push().setValue(hashMap).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
message.setText("");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(ChatActivity.this, "An error occurred!", Toast.LENGTH_SHORT).show();
}
});
DatabaseReference databaseReference1 = FirebaseDatabase.getInstance().getReference("Users").child(oppositeUid).child("Chats").child(mAuth.getCurrentUser().getUid());
databaseReference1.push().setValue(hashMap).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
message.setText("");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(ChatActivity.this, "An error occurred!", Toast.LENGTH_SHORT).show();
}
});
}else{
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Providers").child(oppositeUid).child("Chats").child(mAuth.getCurrentUser().getUid());
databaseReference.push().setValue(hashMap).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
message.setText("");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(ChatActivity.this, "An error occurred!", Toast.LENGTH_SHORT).show();
}
});
DatabaseReference databaseReference1 = FirebaseDatabase.getInstance().getReference("Users").child(mAuth.getCurrentUser().getUid()).child("Chats").child(oppositeUid);
databaseReference1.push().setValue(hashMap).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
message.setText("");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(ChatActivity.this, "An error occurred!", Toast.LENGTH_SHORT).show();
}
});
}
}
}
});
if(className.equals("com.example.uploy.AdapterToDo$1")){
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Providers").child(mAuth.getCurrentUser().getUid()).child("Chats").child(oppositeUid);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
modelChatList.clear();
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
if(snapshot.getKey().equals("details")){
continue;
}
ModelChat modelChat = snapshot.getValue(ModelChat.class);
modelChatList.add(modelChat);
chatAdapter = new AdapterChat(ChatActivity.this, modelChatList);
chatAdapter.notifyDataSetChanged();
recyclerView.setAdapter(chatAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}else{
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Users").child(mAuth.getCurrentUser().getUid()).child("Chats").child(oppositeUid);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
modelChatList.clear();
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
if(snapshot.getKey().equals("details")){
continue;
}
ModelChat modelChat = snapshot.getValue(ModelChat.class);
modelChatList.add(modelChat);
chatAdapter = new AdapterChat(ChatActivity.this, modelChatList);
chatAdapter.notifyDataSetChanged();
recyclerView.setAdapter(chatAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
Log.d("TAG", "PRESSED");
}
The PROBLEM is that when the fragment opens the activity (it contains messages in chat between to users, which are loaded perfectly fine) and the activity detects any change in the chats database reference it stops and loads the previous activity (where the fragment is placed). I wonder what the solution is and I would be glad if you help me.
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)