How to get Int value from an Adapter to Activity in android - java

I want to get an int value from my adapter class to my activity but I am getting nothing while using this code:
Here is my adapter:
package com.capi.ccecommerceapp.Adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.capi.ccecommerceapp.Model.Cart;
import com.capi.ccecommerceapp.R;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.List;
public class CartAdapter extends RecyclerView.Adapter<CartAdapter.ViewHolder>
{
private Context context;
private List<Cart> cartList;
private String productImage;
public int overTotalPrice = 0;
public CartAdapter(Context context, List<Cart> cartList ) {
this.context = context;
this.cartList = cartList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.cart_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int position) {
holder.cartName.setText(cartList.get(position).getProductName());
holder.cartPrice.setText(cartList.get(position).getProductPrice());
holder.cart_qty.setText(String.valueOf(cartList.get(position).getProductQuantity()));
int oneTypeProductTPrice = ((Integer.parseInt(cartList.get(position).getProductPrice()))) * cartList.get(position).getProductQuantity();
overTotalPrice = overTotalPrice + oneTypeProductTPrice;
/*FirebaseAuth auth = FirebaseAuth.getInstance();
FirebaseUser user = auth.getCurrentUser();*/
/* holder.cartPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (cartQty<10)
{
cartQty++;
}
}
});
holder.cartMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (cartQty>1)
{
cartQty--;
}
}
});
holder.cart_qty.setText(cartQty);
holder.deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
cartList.remove(cartList.get(position));
}
});*/
/* holder.wishlistBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (holder.wishlistBtn.getTag().equals("add"))
{
holder.wishlistBtn.setImageResource(R.drawable.ic_love_fill);
holder.wishlistBtn.setTag("added");
}
else
{
holder.wishlistBtn.setImageResource(R.drawable.love);
holder.wishlistBtn.setTag("add");
}
}
});*/
DatabaseReference reference = FirebaseDatabase.getInstance().getReference()
.child("Products")
.child(cartList.get(position).getProductId())
.child("productImage");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot)
{
if (snapshot.exists()) {
productImage = snapshot.getValue(String.class);
Glide.with(context).load(productImage).into(holder.cartImage);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
public int getItemCount() {
return cartList.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
ImageView cartImage;
TextView cartName;
TextView cartPrice;
ImageView wishlistBtn;
ImageView deleteBtn;
ImageView cartPlus;
ImageView cartMinus;
TextView cart_qty;
public ViewHolder(#NonNull View itemView) {
super(itemView);
cartImage = itemView.findViewById(R.id.cart_image);
cartName = itemView.findViewById(R.id.cart_name);
cartPrice = itemView.findViewById(R.id.cart_price);
wishlistBtn = itemView.findViewById(R.id.add_to_wishlist);
deleteBtn = itemView.findViewById(R.id.delete_cart);
cartPlus = itemView.findViewById(R.id.cart_add);
cartMinus = itemView.findViewById(R.id.cart_minus);
cart_qty = itemView.findViewById(R.id.cart_quantity);
}
}
}
and here is my activity code where I want to set it in textView:
package com.capi.ccecommerceapp.Fragment;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.capi.ccecommerceapp.Adapter.CartAdapter;
import com.capi.ccecommerceapp.address.ShiptoActivity;
import com.capi.ccecommerceapp.Model.Cart;
import com.capi.ccecommerceapp.R;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class CartFragment extends Fragment
{
private RecyclerView cartRecyclerView;
private List<Cart> cartList;
private CartAdapter cartAdapter;
private Button next;
private FirebaseAuth auth;
private FirebaseUser user;
private TextView subtotal;
private TextView items;
private TextView shipping;
private TextView totalPrice;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_cart, container, false);
cartRecyclerView = view.findViewById(R.id.cartRecycler);
next = view.findViewById(R.id.checkout_btn);
auth = FirebaseAuth.getInstance();
user = auth.getCurrentUser();
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getContext(), ShiptoActivity.class));
}
});
subtotal = view.findViewById(R.id.subtotal_price);
items = view.findViewById(R.id.items);
shipping = view.findViewById(R.id.shipping_price);
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
cartRecyclerView.setLayoutManager(layoutManager);
cartList = new ArrayList<>();
cartAdapter = new CartAdapter(getContext(), cartList);
cartRecyclerView.setAdapter(cartAdapter);
loadCart();
return view;
}
private void loadCart()
{
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Cart")
.child(user.getUid());
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren())
{
Cart cart = dataSnapshot.getValue(Cart.class);
cartList.add(cart);
}
cartAdapter.notifyDataSetChanged();
subtotal.setText("$" + cartAdapter.overTotalPrice);
items.setText("Items("+cartAdapter.getItemCount()+")");
int shippingPrice = (cartAdapter.overTotalPrice / 20);
shipping.setText("$" + shippingPrice);
/*int totalPriceFinal = shippingPrice + cartAdapter.getOverTotalPrice();
totalPrice.setText("$" + totalPriceFinal);*/
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
I want to get this int:public int overTotalPrice = 0;
And I am getting it as:subtotal.setText("$"+cartAdapter.overTotalPrice);
Anyone have a solution?
???????????????????????
????????????????????
??????????????????????

Related

Why is it the skipping layout in RecyclerView?

I keep getting E/RecyclerView: No adapter attached; skipping layout. I have try onStop() and onStart() methods. I try to reorganize the way the method are structure still no luck. I have follow the instructions on https://firebaseopensource.com/projects/firebase/firebaseui-android/database/readme/ yet, I can't figure it out.
package mrcof.code.senior_tech_support_app;
import android.content.Context;
import android.media.Image;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import static mrcof.code.senior_tech_support_app.R.id.result_list;
public class TV extends AppCompatActivity {
private EditText mSearchField;
private ImageButton mSearchBtn;
private RecyclerView mResultList;
private DatabaseReference mUserDatabase;
private FirebaseRecyclerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_tv);
mUserDatabase = FirebaseDatabase.getInstance().getReference("TV"); // TV in Database
mSearchField = (EditText) findViewById(R.id.search_field);
mSearchBtn = (ImageButton) findViewById(R.id.search_btn);
mSearchBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String searchText = mSearchField.getText().toString();
firebaseUserSearch(searchText); //Our own firebase usersearch
}
});
}
private void firebaseUserSearch(String searchText) {
Toast.makeText(TV.this, "Started Search", Toast.LENGTH_LONG).show();
Query firebaseSearchQuery = mUserDatabase.orderByChild("Brand").startAt(searchText).endAt(searchText + "\uf8ff");
/*Query firebaseSearchQuery = FirebaseDatabase.getInstance()
.getReference()
.child("Brand")
.limitToLast(6).startAt(searchText).endAt(searchText + "\uf8ff");*/
FirebaseRecyclerOptions<Users> options = new FirebaseRecyclerOptions.Builder<Users>().setQuery(firebaseSearchQuery, Users.class).build();
adapter = new FirebaseRecyclerAdapter<Users, UsersViewHolder>(options) {
#NonNull
#Override
public UsersViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_layout, parent, false);
return new UsersViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull UsersViewHolder holder, int position, #NonNull Users model) {
holder.setDetails(getApplicationContext(), model.getBrand(), model.getImage());
}
};
mResultList = (RecyclerView) findViewById(result_list);
mResultList.setHasFixedSize(true);
mResultList.setLayoutManager(new LinearLayoutManager(this));
mResultList.setAdapter(adapter);
}
// View Holder Class
public static class UsersViewHolder extends RecyclerView.ViewHolder {
View mView;
public UsersViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setDetails(Context ctx, String brandd, String brandImage){
TextView brand = (TextView) mView.findViewById(R.id.name_text);
ImageView brand_image = (ImageView) mView.findViewById(R.id.brandd_image);
brand.setText(brandd);
Glide.with(ctx).load(brandImage).into(brand_image);
}
}
}
package mrcof.code.senior_tech_support_app;
import android.annotation.SuppressLint;
import android.content.Context;
import android.media.Image;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import static mrcof.code.senior_tech_support_app.R.id.result_list;
public class TV extends AppCompatActivity {
private EditText mSearchField;
private ImageButton mSearchBtn;
private RecyclerView recyclerView;
private DatabaseReference databaseReference;
private FirebaseRecyclerAdapter adapter;
private FirebaseDatabase database;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_tv);
//databaseReference = FirebaseDatabase.getInstance().getReference("TV"); // TV in Database
mSearchField = (EditText) findViewById(R.id.search_field);
mSearchBtn = (ImageButton) findViewById(R.id.search_btn);
recyclerView = (RecyclerView) findViewById(result_list);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
databaseReference = FirebaseDatabase.getInstance().getReference("TV"); // TV in Database
mSearchBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String searchText = mSearchField.getText().toString();
firebaseSearch(searchText);
}
});
}
private void firebaseSearch(String searched){
String query = searched;
Query firebaseSearchQuery = databaseReference.orderByChild("brand").startAt(query).endAt( query + "\uf8ff");
FirebaseRecyclerOptions<Users> options = new FirebaseRecyclerOptions.Builder<Users>().setQuery(firebaseSearchQuery, Users.class).setLifecycleOwner(this).build();
FirebaseRecyclerAdapter<Users, ViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Users, ViewHolder>(options) {
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_layout, parent, false);
return new ViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull ViewHolder holder, int position, #NonNull Users model) {
holder.setDetails(getApplicationContext(), model.getBrand(), model.getImage());
}
};
firebaseRecyclerAdapter.startListening();
recyclerView.setAdapter(firebaseRecyclerAdapter);
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerOptions<Users> options = new FirebaseRecyclerOptions.Builder<Users>().setQuery(databaseReference, Users.class).setLifecycleOwner(this).build();
FirebaseRecyclerAdapter<Users, ViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Users, ViewHolder>(options) {
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_layout, parent, false);
return new ViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull ViewHolder holder, int position, #NonNull Users model) {
holder.setDetails(getApplicationContext(), model.getBrand(), model.getImage());
}
};
firebaseRecyclerAdapter.startListening();
recyclerView.setAdapter(firebaseRecyclerAdapter);
}
public static class ViewHolder extends RecyclerView.ViewHolder {
View mView;
public ViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setDetails(Context ctx, String brandd, String brandImage){
TextView brand = (TextView) mView.findViewById(R.id.brand_name);
ImageView brand_img = (ImageView) mView.findViewById(R.id.brand_image);
brand.setText(brandd);
Glide.with(ctx).load(brandImage).into(brand_img);
}
}
}

Can't convert object of type java.lang.String to type com.example.acubeitsolution.Client_Review_getter_setter

Below is the Complete code :
Please tell me the solution
I am getting this error while retrieving data from Firebase realtime database
Activity is crashing after a while automatically:
Getting error at this line:-
Client_Review_getter_setter CRArr=dataSnapshot1.getValue(Client_Review_getter_setter.class);
`This is my Fragment code :-`
package com.example.acubeitsolution;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class ChatFragment extends Fragment {
DatabaseReference databaseReference;
RecyclerView recyclerView;
ArrayList<Client_Review_getter_setter> list;
Client_Review_AdapterClass adapter;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.activity_chat_fragment,container,false);
recyclerView=(RecyclerView)view.findViewById(R.id.chat_fragment_recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
list=new ArrayList<Client_Review_getter_setter>();
if(checkConnection() == true) {
databaseReference = FirebaseDatabase.getInstance().getReference().child("ClientReview");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot dataSnapshot1 : dataSnapshot.getChildren())
{
Client_Review_getter_setter CRArr=dataSnapshot1.getValue(Client_Review_getter_setter.class);
list.add(CRArr);
}
adapter = new Client_Review_AdapterClass(getActivity(),list);
recyclerView.setAdapter(adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
databaseError.getDetails();
Toast.makeText(getActivity(), databaseError.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
else
{
Toast.makeText(getActivity(),"No internet connection\n\nTrun on wifi / mobile data",Toast.LENGTH_LONG).show();
}
return view;
}
public boolean checkConnection()
{
ConnectivityManager connectivityManager=(ConnectivityManager)getActivity()
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo active_Network=connectivityManager.getActiveNetworkInfo();
if(null != active_Network)
{
return true;
}
else
{
return false;
}
}
}
This is my Getter Setter class :-
package com.example.acubeitsolution;
public class Client_Review_getter_setter {
private String CompanyName;
private String CompanyReview;
private String CompanyLogo;
public Client_Review_getter_setter(String companyName, String companyReview, String companyLogo) {
CompanyName = companyName;
CompanyReview = companyReview;
CompanyLogo = companyLogo;
}
public Client_Review_getter_setter() {
}
public String getCompanyName() {
return CompanyName;
}
public void setCompanyName(String companyName) {
CompanyName = companyName;
}
public String getCompanyReview() {
return CompanyReview;
}
public void setCompanyReview(String companyReview) {
CompanyReview = companyReview;
}
public String getCompanyLogo() {
return CompanyLogo;
}
public void setCompanyLogo(String companyLogo) {
CompanyLogo = companyLogo;
}
}
`This is my Adapter class :-`
package com.example.acubeitsolution;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class Client_Review_AdapterClass extends RecyclerView.Adapter<Client_Review_AdapterClass.MyViewHolder> {
Context context;
ArrayList<Client_Review_getter_setter> ClientReviewArr;
public Client_Review_AdapterClass(Context c, ArrayList<Client_Review_getter_setter> CRArr) {
context=c;
ClientReviewArr=CRArr;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new MyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.client_review_cardview,parent,false));
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.CompanyName.setText(ClientReviewArr.get(position).getCompanyName());
holder.CompanyReview.setText(ClientReviewArr.get(position).getCompanyReview());
Picasso.get().load(ClientReviewArr.get(position).getCompanyLogo()).into(holder.CompanyLogo);
}
#Override
public int getItemCount() {
return ClientReviewArr.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView CompanyName, CompanyReview;
ImageView CompanyLogo;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
CompanyName = (TextView) itemView.findViewById(R.id.client_review_cardview_company_name);
CompanyReview = (TextView) itemView.findViewById(R.id.client_review_cardview_company_review_description);
CompanyLogo = (ImageView) itemView.findViewById(R.id.client_review_cardview_companylogo_imageview);
}
}
}
```
Change this:
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot dataSnapshot1 : dataSnapshot.getChildren())
{
Client_Review_getter_setter CRArr=dataSnapshot1.getValue(Client_Review_getter_setter.class);
list.add(CRArr);
}
adapter = new Client_Review_AdapterClass(getActivity(),list);
recyclerView.setAdapter(adapter);
}
into this:
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Client_Review_getter_setter CRArr=dataSnapshot.getValue(Client_Review_getter_setter.class);
list.add(CRArr);
adapter = new Client_Review_AdapterClass(getActivity(),list);
recyclerView.setAdapter(adapter);
}
Remove the for loop, since when you are iterating you are retrieving the valus of type String and not of the modal class that you created.

How to set up notifications with sound/vibration and button logo change?

I am trying to set up notification, but I can't add what I want: I would like the notification coming with sound/vibration, changing also the notification button logo.
Can anyone help me to setup notification? I am trying but it's not working.
The code below is working fine: no error. All notifications are shown, but with no sound / vibration.
package com.example.mfree.Fragment;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.mfree.Adapter.NotificationAdapter;
import com.example.mfree.Model.Notification;
import com.example.mfree.R;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* A simple {#link Fragment} subclass.
*/
public class NotificationFragment extends Fragment {
private RecyclerView recyclerView;
NotificationAdapter notificationAdapter;
private List<Notification>notificationList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_notification, container, false);
recyclerView=view.findViewById(R.id.recyler_view);
recyclerView.setHasFixedSize(true);
LinearLayoutManager layoutManager=new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
notificationList=new ArrayList<>();
notificationAdapter=new NotificationAdapter(getContext(),notificationList);
recyclerView.setAdapter(notificationAdapter);
readNotification();
return view;
}
private void readNotification() {
FirebaseUser firebaseUser= FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference= FirebaseDatabase.getInstance().getReference("Notifications").child(firebaseUser.getUid());
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
notificationList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren())
{
Notification notification=snapshot.getValue(Notification.class);
notificationList.add(notification);
}
Collections.reverse(notificationList);
notificationAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
**NotificationAdapter**
package com.example.mfree.Adapter;
import android.content.Context;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.mfree.Fragment.PostDetailsFragment;
import com.example.mfree.Fragment.ProfileFragment;
import com.example.mfree.Model.Notification;
import com.example.mfree.Model.Post;
import com.example.mfree.Model.User;
import com.example.mfree.R;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.List;
public class NotificationAdapter extends RecyclerView.Adapter<NotificationAdapter.ViewHolder>{
private Context mContext;
private List<Notification>mNotification;
public NotificationAdapter(Context mContext, List<Notification> mNotification) {
this.mContext = mContext;
this.mNotification = mNotification;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(mContext).inflate(R.layout.notification_item,parent,false);
return new NotificationAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
final Notification notification=mNotification.get(position);
holder.text.setText(notification.getText());
getUserInfo(holder.image_profile,holder.username,notification.getUserid());
if (notification.isIspost()){
holder.post_image.setVisibility(View.VISIBLE);
getPostImage(holder.post_image,notification.getPostid());
}else {
holder.post_image.setVisibility(View.GONE);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(notification.isIspost()){
SharedPreferences.Editor editor=mContext.getSharedPreferences("PREFS",Context.MODE_PRIVATE).edit();
editor.putString("postid",notification.getPostid());
editor.apply();
((FragmentActivity)mContext).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container
,new PostDetailsFragment()).commit();
}else {
SharedPreferences.Editor editor=mContext.getSharedPreferences("PREFS",Context.MODE_PRIVATE).edit();
editor.putString("profileid",notification.getUserid());
editor.apply();
((FragmentActivity)mContext).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container
,new ProfileFragment()).commit();
}
}
});
}
#Override
public int getItemCount() {
return mNotification.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public ImageView image_profile,post_image;
TextView username,text;
public ViewHolder(#NonNull View itemView) {
super(itemView);
image_profile=itemView.findViewById(R.id.image_profile);
post_image=itemView.findViewById(R.id.image_post);
username=itemView.findViewById(R.id.username);
text=itemView.findViewById(R.id.comment);
}
}
private void getUserInfo (final ImageView imageView, final TextView username, String publisherid){
DatabaseReference reference= FirebaseDatabase.getInstance().getReference("Users").child(publisherid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
try{
User user=dataSnapshot.getValue(User.class);
Glide.with(mContext.getApplicationContext()).load(user.getImageurl()).into(imageView);
username.setText(user.getUsername());
}catch (Exception e)
{
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void getPostImage(final ImageView imageView, String postid){
DatabaseReference reference=FirebaseDatabase.getInstance().getReference("posts").child(postid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
try {
Post post=dataSnapshot.getValue(Post.class);
Glide.with(mContext.getApplicationContext()).load(post.getPostimage()).into(imageView);
}catch (Exception e){
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
If what you are trying to make is an in-app notification system, you can try ringing the sound on your own using RingtoneManager and Ringtone class as :
// to play sound for your custom notification on its arrival
Uri notificationToneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone notificationTone = RingtoneManager.getRingtone(this, notificationToneUri);
notificationTone.play();
//to stop
notificationTone.stop();
See this link for vibration

Store data in 'REALM DATABASE' and show in a recyclerview

I want to store my data in realm database, then retrieve and show it in a recyclerview. All my code is correct in my point of view but it gives me an error about null pointer exception. Despite my efforts I was unable to solve it.
Main Activty Class
package com.deitel.realmrecyclerviewspinnerpriority;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.deitel.realmrecyclerviewspinnerpriority.Adapter.AdapterClass;
import com.deitel.realmrecyclerviewspinnerpriority.Database.RelmHelper;
import com.deitel.realmrecyclerviewspinnerpriority.Modelclass.ModelClass;
import java.util.ArrayList;
import io.realm.Realm;
import io.realm.RealmConfiguration;
import io.realm.RealmResults;
public class MainActivity extends AppCompatActivity {
private static final String TAG="MainActivity";
Realm realm;
EditText text_name;
EditText text_details;
ImageButton btn_ascending,btn_descending;
RecyclerView rv;
Spinner spinner;
TextView text_data;
Button btn_save,btn_view;
ArrayList<String> itemslist;
AdapterClass addapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text_name = findViewById(R.id.text_name);
text_details = findViewById(R.id.text_details);
text_data=findViewById(R.id.text_data);
btn_save=findViewById(R.id.btn_show);
btn_view=findViewById(R.id.btn_view);
btn_save = findViewById(R.id.btn_show);
rv = findViewById(R.id.recyclerview);
btn_ascending=findViewById(R.id.btn_ascending);
btn_descending=findViewById(R.id.btn_descneding);
rv.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
final RelmHelper helper=new RelmHelper(realm);
itemslist=helper.retrievedata();
addapter = new AdapterClass(MainActivity.this,itemslist);
rv.setAdapter(addapter);
spinner = findViewById(R.id.spinner);
final ArrayList<Integer> arrayList = new ArrayList<>();
arrayList.add(1);
arrayList.add(2);
arrayList.add(3);
arrayList.add(4);
arrayList.add(5);
arrayList.add(6);
arrayList.add(7);
arrayList.add(8);
arrayList.add(9);
arrayList.add(10);
arrayList.add(11);
arrayList.add(12);
arrayList.add(13);
final ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(this, android.R.layout.simple_spinner_item, arrayList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ModelClass md=new ModelClass();
md.setName(text_name.getText().toString());
md.setDetails(text_details.getText().toString());
/*save data*/
RelmHelper helper=new RelmHelper(realm);
helper.savedata(md);
}
});
}
}
```
MY REALM HELPER CLASS
```
package com.deitel.realmrecyclerviewspinnerpriority.Database;
import android.view.Display;
import com.deitel.realmrecyclerviewspinnerpriority.Modelclass.ModelClass;
import java.util.ArrayList;
import io.realm.Realm;
import io.realm.RealmResults;
public class RelmHelper {
Realm realm;
public RelmHelper(Realm realm) {
this.realm = realm;
}
public void savedata(final ModelClass modelClass){
realm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
ModelClass md=realm.copyToRealm(modelClass);
}
});
}
public ArrayList<String> retrievedata(){
ArrayList<String> modelclassdata=new ArrayList<>();
RealmResults<ModelClass> modelClass=realm.where(ModelClass.class).findAll();
for (ModelClass MD:modelClass){
modelclassdata.add(MD.getName());
modelclassdata.add(MD.getDetails());
// modelclassdata.add(MD.getPriority());
}
return modelclassdata;
}
}
```
Model Class
```
package com.deitel.realmrecyclerviewspinnerpriority.Modelclass;
import io.realm.RealmObject;
public class ModelClass extends RealmObject {
private String name;
private String details;
// private int priority;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
// public int getPriority() {
// return priority;
// }
//
// public void setPriority(int priority) {
// this.priority = priority;
// }
}
```
Adapter Class
```[![enter image description here][1]][1]
package com.deitel.realmrecyclerviewspinnerpriority.Adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.deitel.realmrecyclerviewspinnerpriority.Modelclass.ModelClass;
import com.deitel.realmrecyclerviewspinnerpriority.R;
import java.util.ArrayList;
import java.util.List;
public class AdapterClass extends RecyclerView.Adapter<AdapterClass.Viewholder> {
ArrayList<String> modelClassList;
Context context;
public AdapterClass(#NonNull Context context,ArrayList<String> modelClassList){
this.modelClassList=modelClassList;
this.context=context;
}
#NonNull
#Override
public AdapterClass.Viewholder onCreateViewHolder(#NonNull ViewGroup viewGroup, int viewType) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.custom_cardview_layout, viewGroup, false);
Viewholder holder = new Viewholder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull AdapterClass.Viewholder holder, final int position) {
holder.textView_name.setText("Name :" + modelClassList.get(position));
holder.textView_details.setText("Details : " + modelClassList.get(position));
// holder.textView_priority.setText("Priority : " + modelClassList.get(position));
// holder.btn_delete.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// modelClassList.remove(position);
// notifyItemRemoved(position);
// notifyItemRangeChanged(position,modelClassList.size());
// notifyDataSetChanged();
// }
// });
}
#Override
public int getItemCount() {
return modelClassList.size();
}
public class Viewholder extends RecyclerView.ViewHolder {
TextView textView_name;
TextView textView_details;
TextView textView_priority;
ImageButton btn_delete;
public Viewholder(#NonNull View view) {
super(view);
textView_name = view.findViewById(R.id.textview_name);
textView_details = view.findViewById(R.id.textview_details);
textView_priority = view.findViewById(R.id.textview_priotity);
btn_delete=view.findViewById(R.id.btn_delete);
}
}
}

RecyclerView is not displaying any data from the firestore

I have list of Categories of Subjects in my firestore database and i want it to be displayed in my app ( which i thought can be done by recyclerView).But my RecyclerView is not populating any data.You can see my code below:
Question_list.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import com.google.firebase.firestore.DocumentChange;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Nullable;
public class Question_list extends AppCompatActivity {
private static final String TAG ="Firelog" ;
private RecyclerView mMainList;
private FirebaseFirestore mFirestore;
private CategoryAdapter categoryAdapter;
private List<Categories> list_category;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question_list);
mMainList = (RecyclerView)findViewById(R.id.main_list_id);
//mMainList.setHasFixedSize(true);
mMainList.setLayoutManager(new LinearLayoutManager(this));
mMainList.setAdapter(categoryAdapter);
mFirestore = FirebaseFirestore.getInstance();
categoryAdapter = new CategoryAdapter(list_category);
list_category = new ArrayList<>();
mFirestore.collection("Questions").addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot queryDocumentSnapshots, #Nullable FirebaseFirestoreException e) {
if(e!=null){
Log.d(TAG, "Error: "+ e.getMessage());
}
for(DocumentChange doc: queryDocumentSnapshots.getDocumentChanges()){
if(doc.getType() == DocumentChange.Type.MODIFIED){
//String document = doc.getDocument().getString("Category");
Categories categories = doc.getDocument().toObject(Categories.class);
list_category.add(categories);
Log.d(TAG, "Category: "+ categories);
categoryAdapter.notifyDataSetChanged();
}
}
}
});
}
}
CategoryAdapter.java
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
public class CategoryAdapter extends
RecyclerView.Adapter<CategoryAdapter.ViewHolder> {
public List<Categories> list_categorie;
public CategoryAdapter(List<Categories> list_categorie){
this.list_categorie = list_categorie;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.category_list,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.mCategoryText.setText(list_categorie.get(position).getCategory());
}
#Override
public int getItemCount() {
return list_categorie.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
View mview;
public TextView mCategoryText;
public ViewHolder(View itemView) {
super(itemView);
mview = itemView;
mCategoryText = (TextView)mview.findViewById(R.id.category_text_id);
}
}
}
Categories.java
public class Categories {
String category;
public Categories(){}
public Categories(String category) {
this.category = category;
}
public String getCategory() {
return category;
}
}
Above are my all java classes. I haven't uploaded my XML file as i think the problem is in the java class.
categoryAdapter = new CategoryAdapter(list_category);
list_category = new ArrayList<>();
list_category should be initialized before passing it to the adapter
list_category = new ArrayList<>();
categoryAdapter = new CategoryAdapter(list_category);

Categories