onbindViewholder include null object - java

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)

Related

RecyclerView duplicates other items after delete item

RecyclerView duplicates other items after deleting an item.
Tried to clear ArrayList but it's not working
I'm a newbie so some information got from the internet.
Also in the firebase item deleting multiple times.
please help me
There's my code and firebase picture:
Adapter
public class MovieFavAdapter extends RecyclerView.Adapter<FavViewHolder> {
private Activity activity;
private List<MovieDetail> results;
int id;
FirebaseAuth auth;
String uid;
private ImageView deleteItem;
DatabaseReference db;
MovieDetail result;
FavViewHolder favViewHolder;
int i;
Intent intent;
#Override
public void setHasStableIds(boolean hasStableIds) {
super.setHasStableIds(hasStableIds);
}
public MovieFavAdapter(Activity activity, List<MovieDetail> results) {
this.activity = activity;
this.results = results;
}
#NonNull
#Override
public FavViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(activity.getApplicationContext()).inflate(R.layout.fav_items,parent, false);
favViewHolder = new FavViewHolder(view);
return favViewHolder;
}
#Override
public void onBindViewHolder(#NonNull FavViewHolder holder, #SuppressLint("RecyclerView") int position) {
result = results.get(position);
auth = FirebaseAuth.getInstance();
holder.setPosterImageView(activity, result.getPoster_path());
String title = result.getTitle();
holder.poster_title_movie.setText(title);
i = holder.getAdapterPosition();
if (title != null) {
holder.poster_title_movie.setVisibility(View.VISIBLE);
holder.poster_title_movie.setText(title);
} else {
holder.poster_title_movie.setVisibility(View.GONE);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
id = result.getId();
Intent intent = new Intent(view.getContext(), MovieDetailActivity.class);
intent.putExtra("id", String.valueOf(id));
activity.startActivity(intent);
activity.onBackPressed();
}
});
holder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
id = results.get(i).getId();
uid = auth.getCurrentUser().getUid();
db = FirebaseDatabase.getInstance().getReference();
db.child("MovieId").child(uid).child(String.valueOf(id)).removeValue();
results.remove(i);
notifyItemRemoved(i);
notifyItemRangeChanged(i, results.size());
Toast.makeText(activity.getApplicationContext(), "Delete "+ i, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return results.size();
}
}
Fragment
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
databaseReference = FirebaseDatabase.getInstance().getReference("MovieId");
results=new ArrayList<>();
auth = FirebaseAuth.getInstance();
uid = auth.getUid();
retrofitService = RetrofitClient.getClient().create(RetrofitService.class);
if (!results.isEmpty()){
results.clear();
}
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fav_movie_layout, container, false);
favRecycler = v.findViewById(R.id.fav_movie_list);
favRecycler.setHasFixedSize(true);
favRecycler.setItemAnimator(null);
favRecycler.setLayoutManager(new LinearLayoutManager(getContext()));
movieFavAdapter = new MovieFavAdapter(getActivity(), results);
movieFavAdapter.notifyDataSetChanged();
movieFavAdapter.setHasStableIds(true);
databaseReference.child(uid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot: snapshot.getChildren()){
results.clear();
Call<MovieDetail> movieDetailCall = retrofitService.getMovieDetailsById(Integer.parseInt(dataSnapshot.getKey()), BuildConfig.Api_Key);
movieDetailCall.enqueue(new Callback<MovieDetail>() {
#Override
public void onResponse(Call<MovieDetail> call, Response<MovieDetail> response) {
MovieDetail movieDetail = response.body();
results.add(movieDetail);
movieFavAdapter.notifyDataSetChanged();
}
#Override
public void onFailure(Call<MovieDetail> call, Throwable t) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
favRecycler.setAdapter(movieFavAdapter);
return v;
}
}
Firebase
enter image description here

How do I get the Uid of the current user and of other users from firebase realtime database

I had user shared preferences to get the current Uid or other Uid from realtime database. But I need to do the same without the use of shared preferences. This is for my ProfileActivity and I am using viewpager with three different fragments. The shared preferences show only the current user's profile even when searched for other user in the app.
The image attached is the output of the profile activity in my smartphone. The top bar containing the username and the logout button is of the profile activity and the rest below the blue banner is of the viewpager
public class ProfileActivity extends AppCompatActivity {
private ImageView logout;
private TextView post;
private FloatingActionButton floatingActionButton;
private TabLayout tabLayout;
private ViewPager viewPager;
private TextView username;
private FirebaseUser fUser;
private DatabaseReference databaseReference;
private FirebaseDatabase firebaseDatabase;
private FirebaseAuth firebaseAuth;
String profileId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
fUser = FirebaseAuth.getInstance().getCurrentUser();
firebaseAuth = FirebaseAuth.getInstance();
databaseReference = FirebaseDatabase.getInstance().getReference()
.child("Users").child(Objects.requireNonNull(firebaseAuth.getUid()));
String data = getBaseContext().getSharedPreferences("PROFILE", Context.MODE_PRIVATE)
.getString("profileId", "none");
if (data.equals("none")){
profileId = fUser.getUid();
} else{
profileId = data;
}
logout = findViewById(R.id.log_out);
username = findViewById(R.id.username);
floatingActionButton = findViewById(R.id.floatingActionButton);
post = findViewById(R.id.posts_account);
tabLayout = findViewById(R.id.tab_layout);
viewPager = findViewById(R.id.view_pager);
tabLayout.setupWithViewPager(viewPager);
VPAdapter vpAdapter = new VPAdapter(getSupportFragmentManager(), FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
vpAdapter.addFragment(new Profile(), "Profile");
vpAdapter.addFragment(new MyPosts(), "Posts");
if (profileId.equals(fUser.getUid())){
vpAdapter.addFragment(new SavedPosts(), "Saved");
}
viewPager.setAdapter(vpAdapter);
getPostCount();
userInfo();
getSupportActionBar().hide();
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(ProfileActivity.this, PostActivity.class));
finish();
}
});
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog alertDialog = new AlertDialog.Builder(ProfileActivity.this).create();
alertDialog.setTitle("Are you sure to logout?");
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(ProfileActivity.this, StartActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK));
finish();
}
});
alertDialog.show();
alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE)
.setTextColor(ContextCompat.getColor(ProfileActivity.this, R.color.colorRed));
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE)
.setTextColor(ContextCompat.getColor(ProfileActivity.this, R.color.colorRed));
}
});
}
private void getPostCount() {
FirebaseDatabase.getInstance().getReference().child("Posts").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
int counter = 0;
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
Posts posts = snapshot.getValue(Posts.class);
if (posts.getPublisher().equals(profileId)) counter ++;
}
post.setText(String.valueOf(counter));
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void userInfo() {
FirebaseDatabase.getInstance().getReference().child("Users").child(profileId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
User user = snapshot.getValue(User.class);
username.setText("#" + user.getUsername());
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
The above is the code of the profile activity
public class MyPosts extends Fragment {
private RecyclerView recyclerView;
private PostAdapter photoAdapter;
private List<Posts> myPhotoList;
private FirebaseUser fUser;
String profileId;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_my_thoughts, container, false);
fUser = FirebaseAuth.getInstance().getCurrentUser();
String data = getContext().getSharedPreferences("PROFILE", Context.MODE_PRIVATE)
.getString("profileId", "none");
if (data.equals("none")){
profileId = fUser.getUid();
} else{
profileId = data;
}
recyclerView = view.findViewById(R.id.recycler_view_pictures);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 1));
myPhotoList = new ArrayList<>();
photoAdapter = new PostAdapter(getContext(), myPhotoList);
recyclerView.setAdapter(photoAdapter);
myPhotos();
return view;
}
private void myPhotos() {
FirebaseDatabase.getInstance().getReference().child("Posts").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
myPhotoList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
Posts post = snapshot.getValue(Posts.class);
if (post.getPublisher().equals(profileId)){
myPhotoList.add(post);
}
}
Collections.reverse(myPhotoList);
photoAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
the above is the code for the posts fragments inside the viewpager of the profile activity
public class Profile extends Fragment {
private CircleImageView imageProfile;
private TextView followers;
private TextView following;
private TextView fullname;
private TextView bio;
private CircleImageView verification;
private TextView usernamebottom;
private Button editProfile;
private FirebaseUser fUser;
String profileId;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_profile, container, false);
fUser = FirebaseAuth.getInstance().getCurrentUser();
String data = getContext().getSharedPreferences("PROFILE", Context.MODE_PRIVATE)
.getString("profileId", "none");
if (data.equals("none")){
profileId = fUser.getUid();
} else{
profileId = data;
getContext().getSharedPreferences("PROFILE", Context.MODE_PRIVATE).edit().clear().apply();
}
imageProfile = view.findViewById(R.id.image_profile);
verification = view.findViewById(R.id.verification_profile);
followers = view.findViewById(R.id.followers);
following = view.findViewById(R.id.following);
fullname = view.findViewById(R.id.full_name);
bio = view.findViewById(R.id.bio);
usernamebottom = view.findViewById(R.id.username_btm);
editProfile = view.findViewById(R.id.edit_profile);
getFollowersAndFollowingCount();
userInfo();
if (profileId.equals(fUser.getUid())){
editProfile.setText("Edit profile");
} else {
checkFollowingStatus();
}
editProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String btnText = editProfile.getText().toString();
if (btnText.equals("Edit profile")){
//Go to edit profile
startActivity(new Intent(getContext(), EditProfileActivity.class));
} else{
if (btnText.equals("follow")){
FirebaseDatabase.getInstance().getReference().child("Follow").child(fUser.getUid())
.child("following").child(profileId).setValue(true);
FirebaseDatabase.getInstance().getReference().child("Follow")
.child(profileId).child("followers").child(fUser.getUid()).setValue(true);
} else {
FirebaseDatabase.getInstance().getReference().child("Follow").child(fUser.getUid())
.child("following").child(profileId).removeValue();
FirebaseDatabase.getInstance().getReference().child("Follow")
.child(profileId).child("followers").child(fUser.getUid()).removeValue();
}
}
}
});
return view;
}
private void checkFollowingStatus() {
FirebaseDatabase.getInstance().getReference().child("Follow").child(fUser.getUid()).child("following")
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.child(profileId).exists()) {
editProfile.setText("following");
} else {
editProfile.setText("follow");
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void getFollowersAndFollowingCount() {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Follow").child(profileId);
ref.child("followers").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
followers.setText("" + dataSnapshot.getChildrenCount());
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
ref.child("following").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
following.setText("" + dataSnapshot.getChildrenCount());
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void userInfo() {
FirebaseDatabase.getInstance().getReference().child("Users").child(profileId).addValueEventListener(new ValueEventListener() {
#SuppressLint("SetTextI18n")
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
User user = snapshot.getValue(User.class);
if (user.getImageurl().equals("default")){
imageProfile.setImageResource(R.drawable.ic_empty_profile);
} else {
Picasso.get().load(user.getImageurl()).into(imageProfile);
}
usernamebottom.setText("#" + user.getUsername());
fullname.setText(user.getName());
bio.setText(user.getBio());
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
The above is the code of the user detail fragment also in the view pager of my profile activity

implementing search with FirestoreUI

I have been trying to implement search using firestoreUI but when i run my code the logcat says that:
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.firebase.ui.firestore.FirestoreRecyclerAdapter.startListening()' on a null object reference
at com.example.homebarberv1.Search.onStart(Search.java:93)
below is my code:
public class Search extends AppCompatActivity implements FirebaseAuth.AuthStateListener{
private EditText searchField;
private Button searchButton;
private RecyclerView searchRecyclerview;
private FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
private FirestoreRecyclerAdapter<User, UsersViewHolder> adapter;
private String searchText;
static {
FirebaseFirestore.setLoggingEnabled(true);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_search);
searchField = findViewById(R.id.SearchField);
searchButton = findViewById(R.id.SearchButton);
searchRecyclerview = findViewById(R.id.SearchContainer);
LinearLayoutManager manager = new LinearLayoutManager(this);
manager.setReverseLayout(true);
manager.setStackFromEnd(true);
searchRecyclerview .setHasFixedSize(true);
searchRecyclerview .setLayoutManager(manager);
BottomNavigationView bottomNavigationView = findViewById(R.id.bottomNavigationView);
bottomNavigationView.setSelectedItemId(R.id.search);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.search:
return true;
case R.id.appointment:
startActivity(new Intent(getApplicationContext(),HomePage.class));
overridePendingTransition(0,0);
return true;
case R.id.profile:
startActivity(new Intent(getApplicationContext(),Profile.class));
overridePendingTransition(0,0);
return true;
}
return false;
}
});
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
searchText = searchField.getText().toString();
firebaseUserSearch(searchText);
}
});
}
#Override
public void onStart() {
super.onStart();
if (isSignedIn()) {
adapter.startListening();
}
firebaseAuth.addAuthStateListener(this);
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
FirebaseAuth.getInstance().removeAuthStateListener(this);
}
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth auth) {
if (isSignedIn()) {
adapter.startListening();
} else {
Toast.makeText(Search.this,"user are not signed in",Toast.LENGTH_LONG);
}
}
private boolean isSignedIn() {
return FirebaseAuth.getInstance().getCurrentUser() != null;
}
#NonNull
private void firebaseUserSearch(String searchText){
CollectionReference sCollection =
FirebaseFirestore.getInstance().collection("Barbers");
Query sQuery = sCollection.startAt(searchText).endAt(searchText + "\uf8ff");
FirestoreRecyclerOptions<User> options =
new FirestoreRecyclerOptions.Builder<User>()
.setQuery(sQuery, User.class)
.setLifecycleOwner(this)
.build();
adapter = new FirestoreRecyclerAdapter<User, UsersViewHolder>(options) {
#NonNull
#Override
public UsersViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.searchlist, parent, false);
return new UsersViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull UsersViewHolder holder, int position, #NonNull User model) {
holder.setName(model.getShopname());
holder.setPic(model.getPiclink());
holder.setAddress(model.getAddress() + ", " + model.getPostcode().toString() + ", " + model.getCity());
}
};
searchRecyclerview.setAdapter(adapter);
}
public class UsersViewHolder extends RecyclerView.ViewHolder {
private View mView;
public UsersViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setName(String name){
TextView userNameView = (TextView) mView.findViewById(R.id.shopNameS);
userNameView.setText(name);
}
public void setPic(String link){
ImageView imageView = (ImageView)mView.findViewById(R.id.imageS);
Picasso.get().load(link).into(imageView);
}
public void setAddress(String address){
TextView addressView = (TextView) mView.findViewById(R.id.shopAddressS);
addressView.setText(address);
}
}
}
the error refers to this line:
adapter.startListening();
I'm still new to Android, so I do not really understand what I'm doing wrong here, help is really appreciated
You need to ensure that adapter has been given a value, before you call adapter.startListening on it.
That means that in onStart you need to ensure the adapter exists:
#Override
public void onStart() {
super.onStart();
if (isSignedIn() && adapter != null) {
adapter.startListening();
}
firebaseAuth.addAuthStateListener(this);
}
And then also start listening on the adapter when you create it and the user is signed in. So:
adapter = new FirestoreRecyclerAdapter<User, UsersViewHolder>(options) {
...
});
if (isSignedIn()) {
adapter.startListening();
}

My activity goes to previous activity when firebase database change is detected

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.

Firebase retrieving data to customlistview [Android]

My Error:
E/UncaughtException: com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.stitch.fractions.Profile.userInfo.UserInformation
at com.google.android.gms.internal.zzamy.zze(Unknown Source)
at com.google.android.gms.internal.zzamy.zzb(Unknown Source)
at com.google.android.gms.internal.zzamy.zza(Unknown Source)
at com.google.firebase.database.DataSnapshot.getValue(Unknown Source)
at com.stitch.fractions.Scoreboard.activity.activity.ScoreboardActivity$1.onDataChange(ScoreboardActivity.java:49)
at com.google.firebase.database.Query$1.onDataChange(Unknown Source)
at com.google.android.gms.internal.zzajp.zza(Unknown Source)
at com.google.android.gms.internal.zzakp.zzcxi(Unknown Source)
at com.google.android.gms.internal.zzaks$1.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:743)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:150)
at android.app.ActivityThread.main(ActivityThread.java:5546)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:794)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:684)
I/FA: Tag Manager is not found and thus will not be used
I/Process: Sending signal. PID: 22183 SIG: 9
Disconnected from the target VM, address: 'localhost:8604', transport: 'socket'
My Activity Class:
public class ScoreboardActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
private DatabaseReference dbRef;
private ArrayList<UserInformation> mArrayUserInfo = new ArrayList<>();
private String userId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scoreboard);
mAuth = FirebaseAuth.getInstance();
userId = mAuth.getCurrentUser().getUid();
dbRef = FirebaseDatabase.getInstance().getReference();
displayData();
}
public void displayData() {
dbRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot users : dataSnapshot.getChildren()) {
for (DataSnapshot user : users.getChildren()) {
if (user.getKey().equals(userId)) {
for (DataSnapshot sItem : user.getChildren()) {
if (!(sItem.getKey().equals("age"))) {
UserInformation scoreActivity = sItem.getValue(UserInformation.class);
mArrayUserInfo.add(scoreActivity);
ScoreAdapter sAdapter = new ScoreAdapter(getApplicationContext(), mArrayUserInfo);
ListView listScore = (ListView)findViewById(R.id.lvScore);
listScore.setAdapter(sAdapter);
}
}
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(ScoreboardActivity.this, "Error Kid", Toast.LENGTH_SHORT).show();
}
});
}
}
Here is My Model Class:
public class UserInformation {
public String name;
public String age;
public String score;
public UserInformation() {
}
public UserInformation(String name, String age, String score) {
this.name = name;
this.age = age;
this.score = score;
}
public String getName() {
return name;
}
public String getAge() {
return age;
}
public String getScore(){
return score;
}
}
}
Here is how i Wrote to Database:
public class ProfileActivity extends AppCompatActivity {
private FirebaseAuth firebaseAuth;
private TextView mUserEmail, mUserScore;
private Button mBtnLogOut, mBtnSave, mBtnScore;
private EditText mEdtProfileName, mEdtProfileAge;
private DatabaseReference dbRefer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
initComponent();
getCurrentUser();
checkCurrentUser();
firebaseDatabase();
mBtnLogOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
firebaseAuth.signOut();
finish();
Intent back = new Intent(ProfileActivity.this, HomeActivity.class);
startActivity(back);
Toast.makeText(ProfileActivity.this, "Good Bye", Toast.LENGTH_SHORT).show();
}
});
mBtnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveUserInfor();
}
});
mBtnScore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent game = new Intent(ProfileActivity.this, ScoreboardActivity.class);
startActivity(game);
}
});
}
public void initComponent() {
mBtnLogOut = (Button) findViewById(R.id.btnOut);
mUserEmail = (TextView) findViewById(R.id.userEmail);
firebaseAuth = FirebaseAuth.getInstance();
mEdtProfileName = (EditText) findViewById(R.id.edtProfileName);
mEdtProfileAge = (EditText) findViewById(R.id.edtProfileAge);
mBtnSave = (Button) findViewById(R.id.btnSave);
mUserScore = (TextView) findViewById(R.id.userScore);
mBtnScore = (Button) findViewById(R.id.btnScore);
}
public void checkCurrentUser() {
firebaseAuth = FirebaseAuth.getInstance();
if (firebaseAuth.getCurrentUser() == null) {
finish();
Intent home = new Intent(ProfileActivity.this, HomeActivity.class);
startActivity(home);
}
}
public void getCurrentUser() {
FirebaseUser user = firebaseAuth.getCurrentUser();
mUserEmail.setText("Current User: " + user.getEmail());
}
public void firebaseDatabase() {
dbRefer = FirebaseDatabase.getInstance().getReference();
mEdtProfileName.getText().toString().trim();
mEdtProfileAge.getText().toString().trim();
}
public void saveUserInfor() {
String name = mEdtProfileName.getText().toString().trim();
String age = mEdtProfileAge.getText().toString().trim();
SharedPreferences prefsName = getSharedPreferences("Name", MODE_PRIVATE);
SharedPreferences.Editor editorName = prefsName.edit();
editorName.putString("sentname", name);
editorName.commit();
SharedPreferences prefsAge = getSharedPreferences("Age", MODE_PRIVATE);
SharedPreferences.Editor editorAge = prefsAge.edit();
editorAge.putString("sentage", age);
editorAge.commit();
SharedPreferences prefs = getSharedPreferences("Data",MODE_PRIVATE);
String data = prefs.getString("time","hi");
if (TextUtils.isEmpty(name)) {
mEdtProfileName.setError("Empty Field !!!");
return;
}
if (TextUtils.isEmpty(age)) {
mEdtProfileAge.setError("Empty Field !!!");
return;
}
UserInformation userInfo = new UserInformation(name, age, data);
FirebaseUser user = firebaseAuth.getCurrentUser();
dbRefer.child("User").child(user.getUid()).setValue(userInfo);
Toast.makeText(this, "Data Saved", Toast.LENGTH_SHORT).show();
}
}
My Adapter Class:
public class ScoreAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater mScoreInflater;
private ArrayList<UserInformation> mUserInfo;
public ScoreAdapter(Context mContext, ArrayList<UserInformation> userInfo) {
this.mContext = mContext;
this.mScoreInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.mUserInfo = userInfo;
}
#Override
public int getCount() {
return mUserInfo.size();
}
#Override
public Object getItem(int position) {
return mUserInfo.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
classScoreHolder holder;
if (convertView == null) {
convertView = mScoreInflater.inflate(R.layout.scoreboard_row, parent, false);
holder = new classScoreHolder();
holder.mTvScoreName = (TextView) convertView.findViewById(R.id.tvScoreName);
holder.mTvScorePoint = (TextView) convertView.findViewById(R.id.tvScorePoint);
convertView.setTag(holder);
} else {
holder = (classScoreHolder) convertView.getTag();
}
TextView tvScoreName = holder.mTvScoreName;
TextView tvScorePoint = holder.mTvScorePoint;
UserInformation getUserInfo = (UserInformation) getItem(position);
tvScoreName.setText("User Name: " + getUserInfo.getName());
tvScorePoint.setText("User Score: " + getUserInfo.getScore());
return convertView;
}
private static class classScoreHolder {
public TextView mTvScoreName;
public TextView mTvScorePoint;
}
current database has name, age and score. What I'm trying to get is only Name and Age from Firebase Database into Customlistview.
Not 100% sure, but it look like you go one level too far in your hierarchy. If I am right, this would simplify your code. Try this :
public void displayData() {
dbRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot users : dataSnapshot.getChildren()) {
for (DataSnapshot user : users.getChildren()) {
if (user.getKey().equals(userId)) {
UserInformation scoreActivity = user.getValue(UserInformation.class);
mArrayUserInfo.add(scoreActivity);
}
}
}
ScoreAdapter sAdapter = new ScoreAdapter(getApplicationContext(), mArrayUserInfo);
ListView listScore = (ListView)findViewById(R.id.lvScore);
listScore.setAdapter(sAdapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(ScoreboardActivity.this, "Error Kid", Toast.LENGTH_SHORT).show();
}
});
}

Categories