How to send User to ChatActivity using onClick - java

I am creating a Chat App and I show the user their contacts. Right now the user can see the image name and status of all of their contacts. But when the user clicks on the contact I want them to go into the ChatActivity. Right now I am stuck because I don't know how to send them their.
I tried this
mAuth.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
But it doesn't work the words setOnClickListener are red. Can someone please help ?
EDIT !!!!!!
I tried both of the below answers and neither helped me. When I put these blocks
class chatLink implements View.OnClickListener {
#Override
public void onClick(View v) {
SendUserToChatActivity();
}
}
private void SendUserToChatActivity() {
Intent mainIntent = new Intent(ContactsFragment.this, MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
And I am getting a red line under here Intent mainIntent = new Intent(ContactsFragment.this, MainActivity.class);
This is the updated code(I am still trying to find a way).
private View ContactsView;
private RecyclerView myContactsList;
private DatabaseReference ContacsRef, UsersRef;
private FirebaseAuth mAuth;
private String currentUserID;
public ContactsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
ContactsView = inflater.inflate(R.layout.fragment_contacts, container, false);
myContactsList = (RecyclerView) ContactsView.findViewById(R.id.contacts_list);
myContactsList.setLayoutManager(new LinearLayoutManager(getContext()));
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
ContacsRef = FirebaseDatabase.getInstance().getReference().child("Contacts").child(currentUserID);
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
return ContactsView;
}
#Override
public void onStart() {
super.onStart();
FirebaseRecyclerOptions options =
new FirebaseRecyclerOptions.Builder<Contacts>()
.setQuery(ContacsRef, Contacts.class)
.build();
FirebaseRecyclerAdapter<Contacts, ContactsViewHolder> adapter
= new FirebaseRecyclerAdapter<Contacts, ContactsViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final ContactsViewHolder holder, int position, #NonNull Contacts model) {
String userIDs = getRef(position).getKey();
UsersRef.child(userIDs).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
if(dataSnapshot.child("userState").hasChild("state")){
String state = (dataSnapshot.child("userState").child("state")).getValue().toString();
String date = (dataSnapshot.child("userState").child("date")).getValue().toString();
String time = (dataSnapshot.child("userState").child("time")).getValue().toString();
if(state.equals("online")){
holder.onlineIcon.setVisibility(View.VISIBLE);
}
else if(state.equals("offline")){
holder.onlineIcon.setVisibility(View.INVISIBLE);
}
} else {
holder.userStatus.setText("offline");
}
if(dataSnapshot.hasChild("image")){
String userImage = dataSnapshot.child("image").getValue().toString();
String profileName = dataSnapshot.child("name").getValue().toString();
String profileStatus = dataSnapshot.child("status").getValue().toString();
holder.userName.setText(profileName);
holder.userStatus.setText(profileStatus);
Picasso.get().load(userImage).placeholder(R.drawable.profile_image).into(holder.profileImage);
}
else{
String profileName = dataSnapshot.child("name").getValue().toString();
String profileStatus = dataSnapshot.child("status").getValue().toString();
holder.userName.setText(profileName);
holder.userStatus.setText(profileStatus);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#NonNull
#Override
public ContactsViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.users_display_layout, viewGroup, false);
ContactsViewHolder viewHolder = new ContactsViewHolder(view);
return viewHolder;
}
class chatLink implements View.OnClickListener {
#Override
public void onClick(View v) {
SendUserToChatActivity();
}
}
private void SendUserToChatActivity() {
Intent mainIntent = new Intent(getApplication(), MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
}
};
myContactsList.setAdapter(adapter);
adapter.startListening();
}
public static class ContactsViewHolder extends RecyclerView.ViewHolder {
TextView userName, userStatus;
CircleImageView profileImage;
ImageView onlineIcon;
public ContactsViewHolder(#NonNull View itemView) {
super(itemView);
userName = itemView.findViewById(R.id.user_profile_name);
userStatus = itemView.findViewById(R.id.user_status);
profileImage = itemView.findViewById(R.id.users_profile_image);
onlineIcon = (ImageView) itemView.findViewById(R.id.user_online_status);
}
}

Since you want recyclerView adapter clickable, you need to setOnClickListener in holder.itemView. Inside onBindViewHolder, add this
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getContext(), ChatActivity.class);
i.putExtra("visit_user_id", userIDs);
i.putExtra("visit_user_name", profileName);
i.putExtra("visit_image", userImage);
startActivity(i);
}
});
Full Code
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
ContactsView = inflater.inflate(R.layout.fragment_contacts, container, false);
myContactsList = (RecyclerView) ContactsView.findViewById(R.id.contacts_list);
myContactsList.setLayoutManager(new LinearLayoutManager(getContext()));
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
ContacsRef = FirebaseDatabase.getInstance().getReference().child("Contacts").child(currentUserID);
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
return ContactsView;
}
#Override
public void onStart() {
super.onStart();
FirebaseRecyclerOptions options =
new FirebaseRecyclerOptions.Builder<Contacts>()
.setQuery(ContacsRef, Contacts.class)
.build();
FirebaseRecyclerAdapter<Contacts, ContactsViewHolder> adapter
= new FirebaseRecyclerAdapter<Contacts, ContactsViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final ContactsViewHolder holder, final int position, #NonNull Contacts model) {
final String userIDs = getRef(position).getKey();
UsersRef.child(userIDs).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
if (dataSnapshot.child("userState").hasChild("state")) {
String state = (dataSnapshot.child("userState").child("state")).getValue().toString();
String date = (dataSnapshot.child("userState").child("date")).getValue().toString();
String time = (dataSnapshot.child("userState").child("time")).getValue().toString();
if (state.equals("online")) {
holder.onlineIcon.setVisibility(View.VISIBLE);
} else if (state.equals("offline")) {
holder.onlineIcon.setVisibility(View.INVISIBLE);
}
} else {
holder.userStatus.setText("offline");
}
if (dataSnapshot.hasChild("image")) {
userImage = dataSnapshot.child("image").getValue().toString();
profileName = dataSnapshot.child("name").getValue().toString();
profileStatus = dataSnapshot.child("status").getValue().toString();
holder.userName.setText(profileName);
holder.userStatus.setText(profileStatus);
Picasso.get().load(userImage).placeholder(R.drawable.profile_image).into(holder.profileImage);
} else {
profileName = dataSnapshot.child("name").getValue().toString();
profileStatus = dataSnapshot.child("status").getValue().toString();
holder.userName.setText(profileName);
holder.userStatus.setText(profileStatus);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getContext(), ChatActivity.class);
i.putExtra("visit_user_id", userIDs);
i.putExtra("visit_user_name", profileName);
i.putExtra("visit_image", userImage);
startActivity(i);
}
});
}
#NonNull
#Override
public ContactsViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.users_display_layout, viewGroup, false);
ContactsViewHolder viewHolder = new ContactsViewHolder(view);
return viewHolder;
}
};
myContactsList.setAdapter(adapter);
adapter.startListening();
}
public static class ContactsViewHolder extends RecyclerView.ViewHolder {
TextView userName, userStatus;
CircleImageView profileImage;
ImageView onlineIcon;
public ContactsViewHolder(#NonNull View itemView) {
super(itemView);
userName = itemView.findViewById(R.id.user_profile_name);
userStatus = itemView.findViewById(R.id.user_status);
profileImage = itemView.findViewById(R.id.users_profile_image);
onlineIcon = (ImageView) itemView.findViewById(R.id.user_online_status);
}
}

Looks like you only missing the proper import, you can press alt + enter on everything that is in red to import open small dialog and import it.
You can either import this:
import android.view.View.OnClickListener;
Or you can implement the click listener interface and avoid creating new click listener for every view like this:
class yourClass implements View.OnClickListener {
#Override
public void onClick(View v) {
//Views clicks go here
}
}
Edit:
You need to replace your first parameter in your intent and pass context.
Replace this:
Intent mainIntent = new Intent(ContactsFragment.this, MainActivity.class);
with this:
Intent mainIntent = new Intent(context, MainActivity.class);
Note that you will have to pass the context and not just the keyword "context", for example, you can pass your current activity like this:
Intent mainIntent = new Intent(MyActivityThatContainsThisFragment, MainActivity.class);

You must get the context of where it is at this moment in case it is a fragment.
Intent mainIntent = new Intent(**getContext()**, MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();

If you want to set click listener on list item then
import android.view.View.OnClickListener;
public static class ContactsViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
...some other code
ContactsViewHolder(View itemView){
// some code
// setting click listener on complete row
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v){
Intent i = new Intent(v.getContext(),ChatActivity.class);
v.getContext().startActivity(i);
}
EDIT :
For your ChatLink,
Intent require 2 parameter to open activity i.e. Context and Destination class. So try this
class chatLink implements View.OnClickListener {
#Override
public void onClick(View v) {
//Resolve error
// you can also use class of fragment i.e. Fragment.this.getContext()
SendUserToChatActivity(v.getContext());
}
}
private void SendUserToChatActivity(Context ctx) {
Intent mainIntent = new Intent(ctx, MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}

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

BottomNavigation.setVisibility doesn't work

I create an application and use a BottomNavigationView in it and one of the fragments calls the other fragment through the adapter. I am trying to make the BottomNavigationView disappear when this fragment is called, for this I use setVisibility (). But the problem is that it doesn’t disappear, maybe someone can tell me what I’m doing wrong
BottomNavigationView:
public class ProfileFragment extends Fragment {
private ImageView avatar;
private TextView nickname, bio, website;
private FirebaseMethods mFirebaseMethods;
private Context mContext;
private AppBarLayout mAppBarLayout;
private Menu mMenu;
private RecyclerView mRecyclerView;
private FirebaseUser mCurrentUser;
private TextView followers, followings;
private BottomNavigationView mBottomNavigationView;
private String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
private ActivityResultContracts.RequestMultiplePermissions mRequestMultiplePermissions= new ActivityResultContracts.RequestMultiplePermissions();
private DatabaseReference mDatabaseReference;
private DatabaseReference followingRef;
private DatabaseReference followersRef;
private ReadWritePermissions mReadWritePermissions;
private IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
private String mParam1;
private String mParam2;
public ProfileFragment() {
// Required empty public constructor
}
public static ProfileFragment newInstance(String param1, String param2) {
ProfileFragment fragment = new ProfileFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_profile2, container, false);
mContext = container.getContext();
mFirebaseMethods = new FirebaseMethods(mContext);
mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
mBottomNavigationView = getActivity().findViewById(R.id.bottomNavigation);
followingRef = FirebaseDatabase.getInstance().getReference("Following");
followersRef = FirebaseDatabase.getInstance().getReference("Followers");
Toolbar toolbar = view.findViewById(R.id.toolbar);
mAppBarLayout = view.findViewById(R.id.app_bar);
mRecyclerView = view.findViewById(R.id.posts_recycler);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayShowTitleEnabled(false);
setHasOptionsMenu(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().finish();
}
});
loadPosts();
avatar = view.findViewById(R.id.profile_avatar);
nickname = view.findViewById(R.id.profile_nickname);
bio = view.findViewById(R.id.profile_bio);
website = view.findViewById(R.id.profile_website);
followers = view.findViewById(R.id.followers_count);
followings = view.findViewById(R.id.following_count);
setFollowingFollowers();
followers.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FollowersFollowingsFragment fragment = new FollowersFollowingsFragment();
Bundle args = new Bundle();
args.putString("uid", mCurrentUser.getUid());
args.putString("followingsOrFollowers", "followers");
fragment.setArguments(args);
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.frame_container,fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
followings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FollowersFollowingsFragment fragment = new FollowersFollowingsFragment();
Bundle args = new Bundle();
args.putString("uid", mCurrentUser.getUid());
args.putString("followingsOrFollowers", "followers");
fragment.setArguments(args);
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.frame_container,fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
avatar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
mFirebaseMethods.getUserDataProfile(avatar, nickname, bio);
return view;
}
private void loadPosts()
{
mReadWritePermissions = new ReadWritePermissions(getActivity().getLifecycle(), getActivity().getActivityResultRegistry());
getLifecycle().addObserver(mReadWritePermissions);
mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
mDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Posts");
mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
FirebaseRecyclerOptions<Posts> options
= new FirebaseRecyclerOptions.Builder<Posts>()
.setQuery(mDatabaseReference.orderByChild("uid").equalTo(mCurrentUser.getUid()), Posts.class)
.build();
mReadWritePermissions = new ReadWritePermissions(getActivity().getLifecycle(), getActivity().getActivityResultRegistry());
getLifecycle().addObserver(mReadWritePermissions);
PostAdapter adapter = new PostAdapter(options, mContext, mReadWritePermissions);
mRecyclerView.setAdapter(adapter);
adapter.startListening();
}
private void setFollowingFollowers()
{
mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
followersRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
followers.setText(Integer.toString((int)snapshot.child(mCurrentUser.getUid()).getChildrenCount()));
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
followingRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
followings.setText(Integer.toString((int)snapshot.child(mCurrentUser.getUid()).getChildrenCount()));
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onResume() {
super.onResume();
}
}
Use setVisibility(View.GONE) instead.
I had the same problem, for some reason it doesn't work, but in the docs they also use View.GONE.
EDIT: Use the method shown in the docs to hide/show BottomNavigationView depending on the Fragment.
navController.addOnDestinationChangedListener(new NavController.OnDestinationChangedListener() {
#Override
public void onDestinationChanged(#NonNull NavController controller,
#NonNull NavDestination destination, #Nullable Bundle arguments) {
if(destination.getId() == R.id.full_screen_destination) {
toolbar.setVisibility(View.GONE);
bottomNavigationView.setVisibility(View.GONE);
} else {
toolbar.setVisibility(View.VISIBLE);
bottomNavigationView.setVisibility(View.VISIBLE);
}
}
});
Use Navigation component like in this example.
I fixed this by using DataBinding and ObservableField for the visibility, I don't why it didn't work through the normal onDestinationChangedListener on the NavController, it just bluntly ignored that command, everything else in that block worked fine but not the visibility.
So an ObservableField in the databinding did the trick
android:visibility="#{hideBottomNav ? View.GONE : View.VISIBLE}"
And set the value to the observable field in the onDestinationChangedListener to your desired outcome
if(destination.id == R.id.navigation_your_notes){
hideBottomNav.set(true)
} else hideBottomNav.set(false)

SharedPreferences erased from xml after killing the app or rebooting the device

i have a problem and my problem is : when i kill the app or shutting down the device , all the information was erased and i can find it , first of all and what i want to do in the first place is: i want to check if this is the first time of the user to use this app or not , if that is the first time then save what he chosen in the sharedPreference xml and if not , then retrieve was chosen and show it , sorry for my bad english , it's not my mother tongue
this is the main activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quran);
readers= (CardView)findViewById(R.id.readers);
readers_name=(TextView)findViewById(R.id.readers_name);
rewaya=(TextView)findViewById(R.id.rewaya);
count=(TextView)findViewById(R.id.count);
Intent i = getIntent();
String txtData = i.getStringExtra("reciters_name");
String txtData1 = i.getStringExtra("reciters_rewaya");
String txtData2 = i.getStringExtra("reciters_count");
shareRef=getSharedPreferences("myPref", MODE_PRIVATE);
SharedPreferences.Editor myedit = shareRef.edit();
boolean firstRun = shareRef.getBoolean("firstRun", true);
if(firstRun) {
myedit.clear();
myedit.putString("reciters", txtData);
myedit.putBoolean("firstRun", false);
myedit.putString("rewaya", txtData1);
myedit.putString("count", txtData2);
myedit.commit();
readers_name.setText(txtData);
rewaya.setText(txtData1);
count.setText(txtData2);
}else {
readers_name.setText(shareRef.getString("reciters", ""));
rewaya.setText(shareRef.getString("rewaya", ""));
count.setText(shareRef.getString("count", ""));
}
fav_suras=(RecyclerView)findViewById(R.id.fav_suras);
fav_suras.setLayoutManager(new LinearLayoutManager(this));
suras=(RecyclerView)findViewById(R.id.suras);
suras.setHasFixedSize(true);
suras.setLayoutManager(new LinearLayoutManager(this));
suras.setAdapter(Mquraan_adapter);
//mSuras_api = new ArrayList<>();
getRetrofit();
readers.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent (quran.this, Readers.class);
startActivity(intent);
}
});
}
public void getRetrofit() {
RequestInterface requestInterface = PostClient.getApiClient().create(RequestInterface.class);
Call<FomCombine> call = requestInterface.getPosts();
call.enqueue(new Callback <FomCombine>() {
#Override
public void onResponse(Call<FomCombine> call, retrofit2.Response <FomCombine> response) {
Toast.makeText(quran.this, "success", Toast.LENGTH_SHORT).show();
mSuras_api = response.body().getfom_combine();
Mquraan_adapter= new quran_adapter(quran.this, (ArrayList<suras_api>) mSuras_api);
suras.setAdapter(Mquraan_adapter);
Mquraan_adapter.notifyDataSetChanged();
}
#Override
public void onFailure(Call<FomCombine> call, Throwable t) {
Log.d("Tag", t.getMessage());
}
});
}}
this is the adapter
private Context mContext ;
private ArrayList<Reciters_api> mReciters_api;
public Reciters_adapter(Context context, ArrayList<Reciters_api> mmReciters_api) {
mContext=context;
mReciters_api=mmReciters_api;
}
#NonNull
#Override
public Reciters_adapter.ReadersViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.single_row,parent,false);
return new ReadersViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ReadersViewHolder holder, int position) {
Reciters_api reciters = mReciters_api.get(position);
String ID_number = reciters.getId1();
String Name =reciters.getName1();
String Rewaya = reciters.getRewaya();
String count =reciters.getCount();
holder.readers_names.setText(Name);
holder.countt.setText(count);
holder.rewayya.setText(Rewaya);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent Reciters = new Intent(context, quran.class);
Reciters.putExtra("reciters_name", Name);
Reciters.putExtra("reciters_rewaya", Rewaya);
Reciters.putExtra("reciters_count", count);
context.startActivity(Reciters);
}
});
}
#Override
public int getItemCount() {
return mReciters_api.size();
}
public class ReadersViewHolder extends RecyclerView.ViewHolder{
public TextView readers_names ,rewayya ,countt;
public ReadersViewHolder(#NonNull View itemView) {
super(itemView);
readers_names=itemView.findViewById(R.id.readers_names);
rewayya=itemView.findViewById(R.id.rewayya);
countt=itemView.findViewById(R.id.countt);
}
}
}

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)

How to Delete the Firebase database Key from Recycle view based on position

I'm building an app as college project for Blood Donation where user can register using Firebase authentication Email and Password and can post request for Blood which is then added to Firebase DataBase which is shown in Recycle view inside an app
I'was able to complete that part.
Now I want to add button which will be visible in the recycle view with option to delete the request if He wish in case he received call from donor or if he no longer in need. But this button should only be visible to user who has posted for request and will remain hidden for other help post inside recycle adapter.
and when he click the button it should delete the particular Data from Firebase Database also.
To summarize.
1. I need button visible only to user who has posted the help request which will delete the post if he wish to
On click event of that Button, will also delete the particular post from Firebase Database
I'm using Firebase authentication sing in of Email and Password.
Here is the Firebase Database Structure
Here is the Code where user wants to upload the Help request and is added
to firebase Data as well
public class EnquiryActivity extends AppCompatActivity {
//UI
Button btnRequest;
EditText edtName,edtBlood,edtPlace,edtMobile,edtEmail;
//DB
DatabaseReference mHelper;
FirebaseAuth mAuth;
//progress
ProgressDialog mProgress;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_enquiry);
//initialisation
edtBlood=(EditText)findViewById(R.id.enq_blood);
edtMobile=(EditText)findViewById(R.id.enq_mobile);
edtEmail=(EditText)findViewById(R.id.enq_email);
edtName=(EditText)findViewById(R.id.enq_name);
edtPlace=(EditText)findViewById(R.id.enq_place);
btnRequest=(Button)findViewById(R.id.button2);
//firebase
mHelper= FirebaseDatabase.getInstance().getReference();
final String mCurrentUser=FirebaseAuth.getInstance().getCurrentUser().getUid().toString();
mAuth=FirebaseAuth.getInstance();
//progress
mProgress=new ProgressDialog(this);
mProgress.setTitle("Loading");
mProgress.setMessage("Please wait..");
btnRequest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mProgress.show();
String blood=edtBlood.getText().toString();
String name=edtName.getText().toString();
String mobile=edtMobile.getText().toString();
String email=edtMobile.getText().toString();
String place=edtPlace.getText().toString();
String temp=blood.toUpperCase();
if(!TextUtils.isEmpty(blood)||!TextUtils.isEmpty(name)||!TextUtils.isEmpty(mobile)||
!TextUtils.isEmpty(place)){
HashMap<String, String> userMap = new HashMap<>();
userMap.put("name", name);
userMap.put("blood_group","Blood Group:- " + blood);
userMap.put("email", email);
userMap.put("mobile", mobile);
userMap.put("place","Location:- " + place);
mHelper.child("Help").child(mCurrentUser).setValue(userMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
mProgress.dismiss();
Toast.makeText(getApplicationContext(), "Registered Successfully..!", Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
});
}else{
Toast.makeText(getApplicationContext(),"Please enter the details in all fields",Toast.LENGTH_LONG).show();
}
}
});
}
}
Here is the Code where list of help post is show including user who has posted of his/her own
* A simple {#link Fragment} subclass.
*/
public class NeedHelpFragment extends Fragment {
FloatingActionButton floatingActionButton;
private View mMainView;
private RecyclerView mHelpList;
private DatabaseReference mUsersDatabase;
private DatabaseReference mUsers;
private FirebaseAuth mAuth;
private String mCurrent_user_id;
public NeedHelpFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mMainView = inflater.inflate(R.layout.fragment_need_help, container, false);
floatingActionButton = (FloatingActionButton) mMainView.findViewById(R.id.float_add);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getActivity(), EnquiryActivity.class));
}
});
//init
mHelpList = (RecyclerView) mMainView.findViewById(R.id.need_recyclerview);
mAuth = FirebaseAuth.getInstance();
mUsersDatabase = FirebaseDatabase.getInstance().getReference().child("Help");
mUsers = FirebaseDatabase.getInstance().getReference().child("Users");
mCurrent_user_id = mAuth.getCurrentUser().getUid();
//
mHelpList.setHasFixedSize(true);
LinearLayoutManager linearVertical = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
mHelpList.setLayoutManager(linearVertical);
DividerItemDecoration mDividerItemDecoration = new DividerItemDecoration(
mHelpList.getContext(),
linearVertical.getOrientation()
);
mHelpList.addItemDecoration(mDividerItemDecoration);
return mMainView;
}
#Override
public void onStart() {
super.onStart();
FirebaseRecyclerAdapter<Help, HelpViewHolder> friendsRecyclerViewAdapter = new FirebaseRecyclerAdapter<Help, HelpViewHolder>(
Help.class,
R.layout.help_single_layout,
HelpViewHolder.class,
mUsersDatabase) {
#Override
protected void populateViewHolder(final HelpViewHolder helpViewHolder, Help help, int i) {
helpViewHolder.setDate(help.getDate());
final String list_user_id = getRef(i).getKey();
mUsersDatabase.child(list_user_id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final String userName = dataSnapshot.child("name").getValue().toString();
String blood = dataSnapshot.child("blood_group").getValue().toString();
final String phone = dataSnapshot.child("mobile").getValue().toString();
final String email = dataSnapshot.child("email").getValue().toString();
String address = dataSnapshot.child("place").getValue().toString();
helpViewHolder.setName(userName);
helpViewHolder.setBlood(blood);
helpViewHolder.setAddress(address);
helpViewHolder.setPhone(phone);
helpViewHolder.setEmail(email);
helpViewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CharSequence options[] = new CharSequence[]{"Email", "Call"};
final AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Select Options");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Click Event for each item.
if (i == 0) {
}
if (i == 1) {
String uri = phone;
if (ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
}
}
}
});
builder.show();
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
};
mHelpList.setAdapter(friendsRecyclerViewAdapter);
}
// viewholder class..
public static class HelpViewHolder extends RecyclerView.ViewHolder {
View mView;
public HelpViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setBlood(String blood){
TextView userStatusView = (TextView) mView.findViewById(R.id.help_blood);
userStatusView.setText(blood.toUpperCase());
}
public void setName(String name){
TextView userNameView = (TextView) mView.findViewById(R.id.help_name);
userNameView.setText(name.toUpperCase());
}
public void setPhone(String phone){
TextView userNameView = (TextView) mView.findViewById(R.id.help_mobile);
userNameView.setText(phone);
}
public void setEmail(String name){
TextView userNameView = (TextView) mView.findViewById(R.id.help_email);
userNameView.setText(name.toUpperCase());
}
public void setAddress(String address) {
TextView userNameView = (TextView) mView.findViewById(R.id.help_place);
address.toUpperCase();
userNameView.setText(address.toUpperCase());
}
public void setDate(String date){
}
}
}
Any help is well appreciated
Thanks in advance.
Add delete button in your help_single_layout . And add a new key posted in firebase database to check whether this user posted or not . On that basis , you can define visibiltiy of Delete button.

Categories