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
Related
hi i am building a app where, i show videos from firebase to videoview which is in recyclerview in gridlayout form, means at each fragment there are two videos shown, i want to add on clicklisten to them as when someone click on it, a new activity opens and at that activity, the same video is shown in fullscreen (vertically). i used putextra to transfer my data, but i am getting error, "uristring",
bellow is my code
Adapter code
package com.example.godhelpme.Adapter;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.RecyclerView;
import com.example.godhelpme.Fragments.HomeFragment;
import com.example.godhelpme.FullScreen;
import com.example.godhelpme.LoginActivity;
import com.example.godhelpme.MainActivity;
import com.example.godhelpme.Model.Post;
import com.example.godhelpme.Model.User;
import com.example.godhelpme.R;
import com.example.godhelpme.StartActivity;
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.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.List;
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder>{
private Context mContext;
private List<Post> mPosts;
private FirebaseUser firebaseUser;
public PostAdapter(Context mContext, List<Post> mPosts) {
this.mContext = mContext;
this.mPosts = mPosts;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.upload_item, parent,false);
return new PostAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
Post post = mPosts.get(position);
try {
String link = post.getVideourl();
MediaController mediaController = new MediaController(mContext);
mediaController.setAnchorView(holder.video1);
Uri video = Uri.parse(link);
holder.video1.setMediaController(mediaController);
holder.video1.setVideoURI(video);
holder.video1.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
try {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = new MediaPlayer();
}
mediaPlayer.setVolume(0f, 0f);
mediaPlayer.setLooping(false);
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
mediaController.setVisibility(View.GONE);
}
});
holder.video1.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.start(); }
});
holder.id.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent in = new Intent(view.getContext(),FullScreen.class);
in.putExtra(" videourl", post.getVideourl());
in.putExtra("publisher", post.getPublisher());
in.putExtra("postid", post.getPostid());
view.getContext().startActivity(in);
}
});
}catch (Exception e){
Toast.makeText(mContext,e.getMessage(), Toast.LENGTH_SHORT).show();
}
FirebaseDatabase.getInstance().getReference().child("Users").child(post.getPublisher())
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
User user = snapshot.getValue(User.class);
holder.id.setText(user.getUsername());
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
public int getItemCount() {
return mPosts.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public VideoView video1;
public TextView id;
public ViewHolder(#NonNull View itemView) {
super(itemView);
video1 = itemView.findViewById(R.id.video1);
id = itemView.findViewById(R.id.id);
}
}
}
THAT ACTIVITY CODE WHERE I WANT TO SHOW
package com.example.godhelpme;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
import com.example.godhelpme.Model.Post;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
public class FullScreen extends AppCompatActivity {
VideoView videoFull;
TextView idFull;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_full_screen);
videoFull = findViewById(R.id.videoFull);
idFull = findViewById(R.id.idFull);
Intent in = getIntent();
try{
String ttr = in.getStringExtra("videourl");
MediaController mediaController = new MediaController(this);
mediaController.setAnchorView(videoFull);
Uri video1 = Uri.parse(ttr);
videoFull.setMediaController(mediaController);
videoFull.setVideoURI(video1);
}catch (Exception e){
Toast.makeText(this,e.getMessage(), Toast.LENGTH_SHORT).show();
}
videoFull.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.start(); }
});
idFull.setText(in.getStringExtra("publisher"));
}
}
PLEASE HELP GUYS PLEASE
It took me three days to figure out what's the problem in my code. After knowing my mistake i am feeling very ashamed as well as happy that i figured, it out.
the mistake is in the adapter code,
in.putExtra(" videourl", post.getVideourl());
String ttr = in.getStringExtra("videourl");
the difference between above two code line is the, in first line there is space before the videourl and in the second line there is no space before videourl, and that's a problem. :-)
Cart Activity(Here I want to show this hashmap data in Recycler View...Any Help will be Highly Appreciated)
package com.example.silkenscoops;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Pair;
import java.util.HashMap;
public class CartActivity extends AppCompatActivity {
private HashMap<String, Pair<String,String>> cartMap=new HashMap<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cart_view);
cartMap= (HashMap<String, Pair<String, String>>) getIntent().getSerializableExtra("h");
}
}
My Adapter class
package com.example.silkenscoops;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Pair;
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 com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import java.util.HashMap;
public class MainAdapter extends FirebaseRecyclerAdapter<Items, MainAdapter.myViewHolder> {
private HashMap<String, Pair<String,String>> cartMap=new HashMap<>();
public MainAdapter(#NonNull FirebaseRecyclerOptions<Items> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull myViewHolder holder, int position, #NonNull Items model) {
holder.Price.setText(model.getPrice());
holder.Product.setText(model.getProduct());
holder.Stock.setText(model.getStock());
holder.increment.setVisibility(View.GONE);
holder.decrement.setVisibility(View.GONE);
holder.add.setOnClickListener(new View.OnClickListener() {
int count=0;
#Override
public void onClick(View v) {
holder.increment.setVisibility(View.VISIBLE);
holder.decrement.setVisibility(View.VISIBLE);
if(count<Integer.parseInt(model.getStock())) {
count++;
holder.add.setText(String.valueOf(count));
cartMap.put(model.getProduct(),new Pair<String,String>(String.valueOf(count),model.getPrice()));
}
holder.decrement.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(count>0) {
count--;
holder.add.setText(String.valueOf(count));
cartMap.put(model.getProduct(),new Pair<String,String>(String.valueOf(count),model.getPrice()));
}
if(count<=0){
holder.add.setText("ADD");
holder.increment.setVisibility(View.GONE);
holder.decrement.setVisibility(View.GONE);
cartMap.remove(model.getProduct());
}
}
});
}
});
}
#NonNull
#Override
public myViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.display,parent,false);
return new MainAdapter.myViewHolder(view);
}
class myViewHolder extends RecyclerView.ViewHolder{
TextView Product, Price, Stock,add;
ImageView decrement,increment;
public myViewHolder(#NonNull View itemView) {
super(itemView);
Price=itemView.findViewById(R.id.Price);
Product=itemView.findViewById(R.id.Product);
Stock=itemView.findViewById(R.id.Stock);
add=itemView.findViewById(R.id.add);
increment=itemView.findViewById(R.id.increment);
decrement=itemView.findViewById(R.id.decrement);
}
}
public HashMap<String, Pair<String, String>> getCartMap() {
return cartMap;
}
}
My MainActivity(Actually it is the menu list..)
package com.example.silkenscoops;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.util.Pair;
import android.view.View;
import android.widget.ImageView;;
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 java.util.HashMap;
public class MainItems extends AppCompatActivity {
private RecyclerView recyclerView;
private ImageView cart_btn;
MainAdapter adapter;
DatabaseReference databasereference;
private HashMap<String, Pair<String,String>> cartMap=new HashMap<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_display);
getSupportActionBar().hide();
cart_btn=findViewById(R.id.cart_btn);
databasereference = FirebaseDatabase.getInstance().getReference();
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
//This is the right Query that should be passed to the setQuery() method
//The fields should stay as in the Items class (I capital)
Query query = FirebaseDatabase.getInstance().getReference().child("Cups");
FirebaseRecyclerOptions<Items> options = new FirebaseRecyclerOptions.Builder<Items>()
.setQuery(query, Items.class)
.build();
adapter = new MainAdapter(options);
recyclerView.setAdapter(adapter);
cart_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cartMap=adapter.getCartMap();
Intent intent = new Intent(MainItems.this, CartActivity.class);
intent.putExtra("list", cartMap);
startActivity(intent);
}
});
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
}
There is no error , but how am I supposed to pass my hashmap from ActivityMain to Cart Activity and show it in recycler View...I have no idea now and after working and thinking for 10-15 days I'm asking here..Please help me..
Thanks
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?
???????????????????????
????????????????????
??????????????????????
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.
In my application, I am attempting to create a live feed (such as the Instagram feed, or the Facebook feed) consisting of posts that contain an Image, a caption, the username of the user, and the like count of the image. I have created a fragment that takes a picture, adds a caption, and converts it to a string from a Bitmap. I can successful post these Posts(object) to firebase database, but getting the values of each post from the database and adding them to an arraylist is not working
CameraFragment(adds post values to database for each post)
package com.example.a10012032.dreamapplicationv2.Main;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.a10012032.dreamapplicationv2.R;
import com.example.a10012032.dreamapplicationv2.UserAuth.Login;
import com.example.a10012032.dreamapplicationv2.UserAuth.Profile;
import com.example.a10012032.dreamapplicationv2.UserAuth.signUp;
import com.google.firebase.auth.FirebaseAuth;
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.io.ByteArrayOutputStream;
import static android.app.Activity.RESULT_OK;
public class cameraFragment extends Fragment {
private static final String Tab = "cameraFragment";
private static final int CAMERA_REQUEST_CODE = 102;
private Button take;
private ImageView holder;
private EditText editText;
private TextView caption;
private Button post;
Bitmap bitmap;
FirebaseAuth mAuth;
DatabaseReference mDatabaseRef;
DatabaseReference mUserData;
String keyUser;
String UsernameStr;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.camera_fragment, container, false);
keyUser = signUp.USER_KEY;
UsernameStr= Login.usernameValue;
bitmap = null;
mAuth = FirebaseAuth.getInstance();
mDatabaseRef = FirebaseDatabase.getInstance().getReference().child("Posts");
mUserData = FirebaseDatabase.getInstance().getReference().child("Users").child(keyUser);
take = view.findViewById(R.id.btnCapture);
post = view.findViewById(R.id.post);
holder = view.findViewById(R.id.imageView2);
editText = view.findViewById(R.id.editText2);
editText.setVisibility(View.INVISIBLE);
caption = view.findViewById(R.id.cap);
caption.setVisibility(View.INVISIBLE);
post.setVisibility(View.INVISIBLE);
take.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
takePictureFromCamera();
}
});
post.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String caption = editText.getText().toString();
DatabaseReference mChildDatabase = mDatabaseRef.child("Posts").push();
mChildDatabase.child("imageString").setValue(bitmapToString(bitmap)); //converts bitmap to string
mChildDatabase.child("likeCount").setValue(0);
Log.d("TAGUSERNAME", UsernameStr+" is null");
mChildDatabase.child("Username").setValue(UsernameStr);
mChildDatabase.child("Message").setValue(caption);
holder.setImageResource(0);
editText.setVisibility(View.INVISIBLE);
post.setVisibility(View.INVISIBLE);
}
});
return view;
}
public void takePictureFromCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_REQUEST_CODE);
}
public String bitmapToString(Bitmap bm){
ByteArrayOutputStream bYtE = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, bYtE);
bm.recycle();
byte[] byteArray = bYtE.toByteArray();
return Base64.encodeToString(byteArray, Base64.DEFAULT);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {
bitmap = (Bitmap) data.getExtras().get("data");
holder.setImageBitmap(bitmap);
editText.setVisibility(View.VISIBLE);
caption.setVisibility(View.VISIBLE);
post.setVisibility(View.VISIBLE);
editText.setText("");
}
}
}
FeedFragment(trying to get each post and adding it to the ListView CustomAdapter)
package com.example.a10012032.dreamapplicationv2.Main;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.example.a10012032.dreamapplicationv2.UserAuth.Login;
import com.example.a10012032.dreamapplicationv2.UserAuth.Profile;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.example.a10012032.dreamapplicationv2.R;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class feedFragment extends Fragment {
private static final String Tab = "feedFragment";
ListView list;
DatabaseReference mDatabaseRef, mUserCheckData, mGodPlease;
ArrayList<Post> array;
CustomAdapter customAdapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.feed_fragment,container,false);
mDatabaseRef = FirebaseDatabase.getInstance().getReference().child("Posts").child("Posts");
array=new ArrayList<>();
Bitmap bm = BitmapFactory.decodeResource(getResources(),R.drawable.prof);
array.add(new Post(bitmapToString(bm),"Caption","Username"));
mDatabaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()){
mUserCheckData=mDatabaseRef.child(ds.getKey());
array.add(new Post(mUserCheckData.child("imageString").toString(),mUserCheckData.child("Message").toString(),mUserCheckData.child("Username").toString()));
Log.d("TAGPLS",mUserCheckData.child("Username").toString());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
customAdapter=new CustomAdapter(getActivity(),R.layout.item,array);
list = view.findViewById(R.id.id_listView);
list.setAdapter(customAdapter);
customAdapter.notifyDataSetChanged();
return view;
}
/* public ArrayList<Post> retrieve(){
mDatabaseRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
fetchData(dataSnapshot);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
fetchData(dataSnapshot);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return array;
}
private void fetchData(DataSnapshot dataSnapshot)
{
array.clear();
for (DataSnapshot ds : dataSnapshot.getChildren())
{
Post newPost=ds.getValue(Post.class);
array.add(newPost);
}
}
*/
public class CustomAdapter extends ArrayAdapter<Post> {
Context context;
List<Post> list;
public CustomAdapter(#NonNull Context context, #LayoutRes int resource, #NonNull List<Post> objects) {
super(context, resource, objects);
this.context=context;
list=objects;
}
#NonNull
#Override
public View getView(int i, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater layoutInflater=(LayoutInflater)context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View adapterView = layoutInflater.inflate(R.layout.item,null);
TextView userN = adapterView.findViewById(R.id.profMainTxt);
ImageView postI = adapterView.findViewById(R.id.imagePost);
TextView capt = adapterView.findViewById(R.id.captionTxt);
Log.d("TAGHI",array.get(i).getUsername()+" is null");
userN.setText(array.get(i).getUsername());
postI.setImageBitmap(stringToBitMap(array.get(i).getBitmapString()));
capt.setText(array.get(i).getCaption());
notifyDataSetChanged();
return adapterView;
}
}
public Bitmap stringToBitMap(String encodedString){
try {
byte [] encodeByte= Base64.decode(encodedString,Base64.DEFAULT);
return BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
} catch(Exception e) {
e.getMessage();
return null;
}
}
public String bitmapToString(Bitmap bm){
ByteArrayOutputStream bYtE = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, bYtE);
bm.recycle();
byte[] byteArray = bYtE.toByteArray();
return Base64.encodeToString(byteArray, Base64.DEFAULT);
}
}
All the commented out parts were attempts at fixing my error
Lastly, My firebase directory
To solve this, just move the following lines of code:
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()){
mUserCheckData=mDatabaseRef.child(ds.getKey());
array.add(new Post(mUserCheckData.child("imageString").toString(),mUserCheckData.child("Message").toString(),mUserCheckData.child("Username").toString()));
Log.d("TAGPLS",mUserCheckData.child("imageString").toString());
}
customAdapter=new CustomAdapter(getActivity(),R.layout.item,array);
list = view.findViewById(R.id.id_listView);
list.setAdapter(customAdapter);
customAdapter.notifyDataSetChanged();
}
inside onDataChange() method right after the for loop ends.
For more information, please see my answer from this post.
Edit: According to your edited post, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference postsRef = rootRef.child("Posts").child("Posts");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String message = ds.child("Message").getValue(String.class);
Log.d("TAG", message);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
postsRef.addListenerForSingleValueEvent(valueEventListener);
It will print all the messages.