Firebase Database Exception [duplicate] - android

This question already has an answer here:
android save object in firebase
(1 answer)
Closed 5 years ago.
Here is the class where i intend to read a Location type data item from firebase database and store it in a Location type Object. I even tried to store the datasnapshot in an object of the class that had a Location type argument in the constructor, i got the same error saying :
" com.google.firebase.database.DatabaseException: Class android.location.Location is missing a constructor with no arguments"
package com.example.aadi.sarthi_;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
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.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class ActiveNotifications extends Fragment{
public static final String NOTIFICATION_MSG = "NOTIFICATION MSG";
public RecyclerView recyclerView;
String user_mac;
public List<notifyListRowItem> result;
public UserAdapter userAdapter;
private DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
private DatabaseReference eventRef = reference.child("Events");
// Create a Intent send by the notification
public static Intent makeNotificationIntent(Context context, String msg) {
Intent intent = new Intent( context, ActiveNotifications.class );
intent.putExtra( NOTIFICATION_MSG, msg );
return intent;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_active_notifications, container, false);
getMac();
result = new ArrayList<>();
recyclerView = (RecyclerView) view.findViewById(R.id.notification_list);
recyclerView.setHasFixedSize(true);
LinearLayoutManager rlm = new LinearLayoutManager(getActivity());
rlm.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(rlm);
/*
createNotifyListRowItem();*/
userAdapter = new UserAdapter(result);
recyclerView.setAdapter(userAdapter);
updateList();
return view;
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()){
case 0:
break;
case 1:
break;
}
return super.onContextItemSelected(item);
}
public void updateList(){
final DatabaseReference locationRef = reference.child(String.valueOf(user_mac)).child("location");
final Location userLoc = null;
final Location eventLoc = null;
locationRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
Location location = dataSnapshot.getValue(Location.class);
userLoc.set(location);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
eventRef.limitToFirst(2).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
eventRef.push().child("location");
Location location = dataSnapshot.getValue(Location.class);
eventLoc.set(location);
if(eventLoc.distanceTo(userLoc)<=1000) {
result.add(dataSnapshot.getValue(notifyListRowItem.class));
userAdapter.notifyDataSetChanged();
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
Log.w("asd", "In onChildChanged");
notifyListRowItem notifyListRowItem = dataSnapshot.getValue(notifyListRowItem.class);
int index = getItemIndex(notifyListRowItem);
result.set(index,notifyListRowItem);
userAdapter.notifyItemChanged(index);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
Log.w("In ", "OnchildRemoved");
notifyListRowItem model = dataSnapshot.getValue(notifyListRowItem.class);
int index = getItemIndex(model);
result.remove(index);
userAdapter.notifyItemRemoved(index);
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
Log.w("IN", "onChildMoved");
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w("IN", "onChildCancelled");
return;
}
});
}
private int getItemIndex(notifyListRowItem item){
int index = -1;
for (int i=0;i<result.size();i++){
if(result.get(i).key.equals(item.key)){
index = i;
break;
}
}
return index;
}
protected void getMac(){
GettingMac gettingMac = new GettingMac(getActivity());
user_mac = gettingMac.Mac();
}
}

You need to have an empty constructor for your Location class.
public Location () {}

You should need to add a constructor of your Location Class.
public Location() {
}

Related

How can I display last message time of firebase at the top in recyclerView in AndroidStudio [duplicate]

This question already has answers here:
Android - Client-side sorting with FirebaseRecyclerAdapter
(1 answer)
FirebaseRecyclerPagingAdapter - sort list by date
(1 answer)
Cannot retrieve data in ascending order
(2 answers)
Firebase Data Desc Sorting in Android
(19 answers)
How to arrange firebase database data in ascending or descending order?
(2 answers)
Closed 8 months ago.
As now i am working on a chat application, here i have a problem that how can i display my last recent chat on the top of the recyclerview in ChatlistFragment,
for example if i had recently sent my last message to any user they have to displayed at the top of my recyclerview, here is my code
package com.micoder.whatsappclone;
import android.content.Intent;
import android.net.Uri;
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.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.github.clans.fab.FloatingActionButton;
import com.github.clans.fab.FloatingActionMenu;
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 com.squareup.picasso.Picasso;
import de.hdodenhof.circleimageview.CircleImageView;
public class ChatsFragment extends Fragment {
private View PrivateChatsView;
private RecyclerView chatsList;
private DatabaseReference ChatsRef, UsersRef;
private FirebaseAuth mAuth;
private String currentUserID;
FloatingActionMenu fabMenu;
FloatingActionButton fabSettings, fabShare, fabContactDev;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
PrivateChatsView = inflater.inflate(R.layout.fragment_chats, container, false);
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
ChatsRef = FirebaseDatabase.getInstance().getReference().child("Messages").child(currentUserID);
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
chatsList = (RecyclerView) PrivateChatsView.findViewById(R.id.chats_list);
chatsList.setLayoutManager(new LinearLayoutManager(getContext()));
fabOptions();
return PrivateChatsView;
}
#Override
public void onStart() {
super.onStart();
FirebaseRecyclerOptions<Contacts> options =
new FirebaseRecyclerOptions.Builder<Contacts>()
.setQuery(ChatsRef, Contacts.class)
.build();
FirebaseRecyclerAdapter<Contacts, ChatsViewHolder> adapter =
new FirebaseRecyclerAdapter<Contacts, ChatsViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull ChatsViewHolder holder, int position, #NonNull Contacts model) {
final String usersIDs = getRef(position).getKey();
final String[] retImage = {"default_image"};
UsersRef.child(usersIDs).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.child("userState").hasChild("state")) {
String state = dataSnapshot.child("userState").child("state").getValue().toString();
if (state.equals("online")) {
holder.onlineIcon.setVisibility(View.VISIBLE);
}
else if (state.equals("offline")) {
holder.onlineIcon.setVisibility(View.INVISIBLE);
}
}
else {
holder.onlineIcon.setVisibility(View.INVISIBLE);
}
if (dataSnapshot.exists()) {
if (dataSnapshot.hasChild("image")) {
retImage[0] = dataSnapshot.child("image").getValue().toString();
Picasso.get().load(retImage[0]).placeholder(R.drawable.profile_image).into(holder.profileImage);
}
final String retName = dataSnapshot.child("name").getValue().toString();
holder.userName.setText(retName);
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.userStatus.setText("online");
}
else if (state.equals("offline")) {
holder.userStatus.setText("Last Seen: " + date + " " + time);
}
}
else {
holder.userStatus.setText("offline");
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent chatIntent = new Intent(getContext(), ChatActivity.class);
chatIntent.putExtra("visit_user_id", usersIDs);
chatIntent.putExtra("visit_user_name", retName);
chatIntent.putExtra("visit_image", retImage[0]);
startActivity(chatIntent);
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#NonNull
#Override
public ChatsViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.users_display_chats_layout, viewGroup, false);
return new ChatsViewHolder(view);
}
};
chatsList.setAdapter(adapter);
adapter.startListening();
}
public static class ChatsViewHolder extends RecyclerView.ViewHolder {
CircleImageView profileImage;
TextView userName, userStatus;
ImageView onlineIcon;
public ChatsViewHolder(#NonNull View itemView) {
super(itemView);
profileImage = itemView.findViewById(R.id.users_profile_image);
userName = itemView.findViewById(R.id.user_profile_name);
userStatus = itemView.findViewById(R.id.user_status);
onlineIcon = itemView.findViewById(R.id.user_online_status);
}
}
public void fabOptions() {
//FAB
fabMenu=PrivateChatsView.findViewById(R.id.fabMenu);
fabSettings=PrivateChatsView.findViewById(R.id.fabSettings);
fabContactDev=PrivateChatsView.findViewById(R.id.fabContactDev);
fabShare=PrivateChatsView.findViewById(R.id.fabShare);
fabShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "My application name");
String shareMessage= "\nLet me recommend you this application\n\n";
shareMessage = shareMessage + "https://play.google.com/store/apps/developer?id=MI_CODER"+"\n\n";
shareIntent.putExtra(Intent.EXTRA_TEXT, shareMessage);
startActivity(Intent.createChooser(shareIntent, "choose one"));
} catch(Exception e) {
//e.toString();
}
fabMenu.close(true);
}
});
fabSettings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "Settings", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getActivity(),SettingsActivity.class));
fabMenu.close(true);
}
});
fabContactDev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(),"Loading...",Toast.LENGTH_SHORT).show();
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://micoder-dev.github.io/Resume-Page/"));
startActivity(browserIntent);
fabMenu.close(true);
}
});
}
}
if you need to refer my complete source code you can get here => https://github.com/Micoder-dev/ChatApp-FE-UI.git
I think this will help you to make it easier to get a solution.

Firebase error after published to play store [duplicate]

This question already has answers here:
Firebase No properties to serialize found on class
(12 answers)
Firebase release apk not loading data
(3 answers)
Firebase AndroidChat release build error
(3 answers)
Closed 2 years ago.
On my android studio debug theres nothing problem, but when i publish the app to playstore my app was close after splashscreen. my apps using firebase, and i have to added SHA-1 from playstore to my firebase project. but still cant crash :
this error i got from play console :
com.google.firebase.database.DatabaseException:
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper$BeanMapper.<init> (CustomClassMapper.java:11)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.loadOrCreateBeanMapperForClass (CustomClassMapper.java)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertBean (CustomClassMapper.java:4)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass (CustomClassMapper.java:4)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToCustomClass (CustomClassMapper.java:8)
at com.google.firebase.database.DataSnapshot.getValue (DataSnapshot.java:8)
at com.kepulcorporation.kepul.HomeFragment$10.onDataChange (HomeFragment.java:8)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent (ValueEventRegistration.java:2)
at com.google.firebase.database.core.view.DataEvent.fire (DataEvent.java)
at com.google.firebase.database.core.view.EventRaiser$1.run (EventRaiser.java:6)
at android.os.Handler.handleCallback (Handler.java:751)
at android.os.Handler.dispatchMessage (Handler.java:95)
at android.os.Looper.loop (Looper.java:154)
at android.app.ActivityThread.main (ActivityThread.java:6121)
at java.lang.reflect.Method.invoke (Method.java)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:889)
at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:779)
this is my main activity :
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.widget.NestedScrollView;
import androidx.fragment.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.Registry;
import com.bumptech.glide.annotation.GlideModule;
import com.bumptech.glide.module.AppGlideModule;
import com.firebase.ui.storage.images.FirebaseImageLoader;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialog;
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 com.google.firebase.messaging.FirebaseMessaging;
import com.google.firebase.storage.StorageReference;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private ActionBar actionBar;
private NestedScrollView nested_scroll_view;
private BottomSheetBehavior mBehavior;
private BottomSheetDialog mBottomSheetDialog;
private View bottom_sheet;
private HorizontalScrollView horizontalScrollView;
private Fragment fragment;
private Fragment fragmenthome;
private SessionManager sessionManager;
RelativeLayout toolbar;
LinearLayout content;
NestedScrollView scrolllayout;
ImageView home_icon, transaksi_icon, bantuan_icon, akun_icon;
TextView home_text, transaksi_text, bantuan_text, akun_text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
content = findViewById(R.id.list_category_item_dashboard);
scrolllayout = findViewById(R.id.nested_scroll_view);
//Set Theme
Tools.setSystemBarColor(this, R.color.colorPrimary);
sessionManager = new SessionManager(this);
sessionManager.checkLogin(this);
home_icon = findViewById(R.id.home_icon);
transaksi_icon = findViewById(R.id.transaksi_icon);
bantuan_icon = findViewById(R.id.bantuan_icon);
akun_icon = findViewById(R.id.akun_icon);
home_text = findViewById(R.id.home_text);
transaksi_text = findViewById(R.id.transaksi_text);
bantuan_text = findViewById(R.id.bantuan_text);
akun_text = findViewById(R.id.akun_text);
FirebaseMessaging.getInstance().getToken()
.addOnCompleteListener(new OnCompleteListener<String>() {
#Override
public void onComplete(#NonNull Task<String> task) {
if (!task.isSuccessful()) {
// Toast.makeText(MainActivity.this, "Fetching FCM registration token failed", Toast.LENGTH_SHORT).show();
return;
}
// Get new FCM registration token
String token = task.getResult();
if(sessionManager.isLoggin())
{
save_fcm(token);
}
}
});
initComponent();
}
public void save_fcm(String token){
HashMap<String, String> user;
sessionManager = new SessionManager(MainActivity.this);
user = sessionManager.getUserDetail();
String email = user.get("EMAIL");
String convertemail = email.replaceAll("\\.", "_");
FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference tableuser = database.getReference("Users");
tableuser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String email = user.get("EMAIL");
String convertemail = email.replaceAll("\\.", "_");
Users users = snapshot.child(convertemail).getValue(Users.class);
Map<String, Object> updates = new HashMap<String,Object>();
updates.put("address", users.getAddress());
updates.put("email", email);
updates.put("name", users.getName());
updates.put("password", users.getPassword());
updates.put("phone", users.getPhone());
updates.put("photo_profile_path", users.getPhoto_profile_path());
updates.put("role_id", users.getRole_id());
updates.put("point", users.getPoint());
updates.put("token", token);
updates.put("promosipush", users.getPromosipush());
updates.put("promosiemail", users.getPromosiemail());
updates.put("statuspush", users.getStatuspush());
updates.put("statusemail", users.getStatusemail());
tableuser.child(convertemail).setValue(updates);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void initComponent() {
nested_scroll_view = (NestedScrollView) findViewById(R.id.nested_scroll_view);
fragment = new HomeFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, fragment,
fragment.getClass().getSimpleName()).commit();
home_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.colorPrimary));
home_text.setTextColor(this.getResources().getColor(R.color.colorPrimary));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
} else {
Toast.makeText(getApplicationContext(), item.getTitle(), Toast.LENGTH_SHORT).show();
}
return super.onOptionsItemSelected(item);
}
public void toHome(View view) {
ViewAnimation.fadeOutIn(nested_scroll_view);
if (sessionManager.isLoggin()){
fragment = new HomeFragment();
}
else {
fragment = new HomeFragment();
}
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, fragment,
fragment.getClass().getSimpleName()).commit();
home_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.colorPrimary));
home_text.setTextColor(this.getResources().getColor(R.color.colorPrimary));
transaksi_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
transaksi_text.setTextColor(this.getResources().getColor(R.color.text));
bantuan_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
bantuan_text.setTextColor(this.getResources().getColor(R.color.text));
akun_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
akun_text.setTextColor(this.getResources().getColor(R.color.text));
}
public void toTransaksi(View view) {
ViewAnimation.fadeOutIn(nested_scroll_view);
if (sessionManager.isLoggin()){
fragment = new TransaksiloginFragment();
}
else {
fragment = new TransaksiFragment();
}
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, fragment,
fragment.getClass().getSimpleName()).commit();
home_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
home_text.setTextColor(this.getResources().getColor(R.color.text));
transaksi_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.colorPrimary));
transaksi_text.setTextColor(this.getResources().getColor(R.color.colorPrimary));
bantuan_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
bantuan_text.setTextColor(this.getResources().getColor(R.color.text));
akun_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
akun_text.setTextColor(this.getResources().getColor(R.color.text));
}
public void toBantuan(View view){
ViewAnimation.fadeOutIn(nested_scroll_view);
if (sessionManager.isLoggin()){
fragment = new BantuanFragment();
}
else {
fragment = new BantuanFragment();
}
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, fragment,
fragment.getClass().getSimpleName()).commit();
home_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
home_text.setTextColor(this.getResources().getColor(R.color.text));
transaksi_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
transaksi_text.setTextColor(this.getResources().getColor(R.color.text));
bantuan_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.colorPrimary));
bantuan_text.setTextColor(this.getResources().getColor(R.color.colorPrimary));
akun_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
akun_text.setTextColor(this.getResources().getColor(R.color.text));
}
public void toAkun(View view){
ViewAnimation.fadeOutIn(nested_scroll_view);
if (sessionManager.isLoggin()){
fragment = new AkunLoginFragment();
}
else {
fragment = new AkunFragment();
}
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, fragment,
fragment.getClass().getSimpleName()).commit();
home_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
home_text.setTextColor(this.getResources().getColor(R.color.text));
transaksi_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
transaksi_text.setTextColor(this.getResources().getColor(R.color.text));
bantuan_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
bantuan_text.setTextColor(this.getResources().getColor(R.color.text));
akun_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.colorPrimary));
akun_text.setTextColor(this.getResources().getColor(R.color.colorPrimary));
}
public void toSell(View view) {
ViewAnimation.fadeOutIn(nested_scroll_view);
if (sessionManager.isLoggin()){
startActivity(new Intent(MainActivity.this, JualsampahActivity.class));
}
else {
fragment = new JualFragment();
}
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, fragment,
fragment.getClass().getSimpleName()).commit();
home_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
home_text.setTextColor(this.getResources().getColor(R.color.text));
transaksi_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
transaksi_text.setTextColor(this.getResources().getColor(R.color.text));
bantuan_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
bantuan_text.setTextColor(this.getResources().getColor(R.color.text));
akun_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
akun_text.setTextColor(this.getResources().getColor(R.color.text));
}
}
and this my HomeFragment :
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.media.Image;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.github.islamkhsh.CardSliderViewPager;
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 org.w3c.dom.Text;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;
import ru.tinkoff.scrollingpagerindicator.ScrollingPagerIndicator;
public class HomeFragment extends Fragment {
CardSliderViewPager cardSliderViewPager;
private List<Category>listData;
private List<Produk>listData1;
private List<SliderData>sliderData;
private RecyclerView rv;
private CategoryAdapter adapter;
private ProdukAdapter adapter1;
private SliderAdapter sliderAdapter;
private RecyclerView recyclerView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View root = inflater.inflate(R.layout.fragment_home, container, false);
cardSliderViewPager = root.findViewById(R.id.viewPager);
recyclerView = root.findViewById(R.id.product_recyclerview);
rv = root.findViewById(R.id.category_recyclerview);
rv.setHasFixedSize(true);
rv.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
listData=new ArrayList<>();
listData1 = new ArrayList<>();
sliderData = new ArrayList<>();
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference table = database.getReference("Category");
table.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(isAdded())
{
listData.clear();
for (DataSnapshot npsnapshot : snapshot.getChildren()){
Category l = npsnapshot.getValue(Category.class);
listData.add(l);
}
adapter=new CategoryAdapter(listData);
rv.setAdapter(adapter);
ScrollingPagerIndicator recyclerIndicator = root.findViewById(R.id.indicator2);
recyclerIndicator.attachToRecyclerView(rv);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
final SessionManager sessionManager = new SessionManager(getActivity());
HashMap<String, String> user = sessionManager.getUserDetail();
String email = user.get("EMAIL");
if(!sessionManager.isLoggin())
{
LinearLayout not_login = root.findViewById(R.id.not_login);
LinearLayout login = root.findViewById(R.id.login);
not_login.setVisibility(View.VISIBLE);
login.setVisibility(View.GONE);
}
else {
LinearLayout not_login = root.findViewById(R.id.not_login);
LinearLayout login = root.findViewById(R.id.login);
not_login.setVisibility(View.GONE);
login.setVisibility(View.VISIBLE);
FirebaseDatabase databaseuser = FirebaseDatabase.getInstance();
DatabaseReference tableuseruser = databaseuser.getReference("Users");
tableuseruser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(isAdded())
{
String convertemail = email.toString().replaceAll("\\.", "_").toString();
Users users = snapshot.child(convertemail).getValue(Users.class);
TextView point = root.findViewById(R.id.profile_point);
TextView name = root.findViewById(R.id.profile_name);
CircleImageView circleImageView = root.findViewById(R.id.profile_image);
name.setText(user.get("NAME"));
point.setText(users.getPoint().toString() + " Point");
if (user.get("PHOTO_PROFILE_PATH").equals(""))
{
Glide.with(getContext()).load("https://cdn.business2community.com/wp-content/uploads/2017/08/blank-profile-picture-973460_640.png").into(circleImageView);
}
else {
Glide.with(getContext()).load(user.get("PHOTO_PROFILE_PATH")).into(circleImageView);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
getbanner();
FirebaseDatabase databasepro = FirebaseDatabase.getInstance();
DatabaseReference tablepro = databasepro.getReference("Product");
tablepro.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(isAdded())
{
listData1.clear();
for (DataSnapshot npsnapshot : snapshot.getChildren()){
Produk l = npsnapshot.getValue(Produk.class);
listData1.add(l);
}
adapter1 = new ProdukAdapter((ArrayList<Produk>) listData1);
recyclerView.setAdapter(adapter1);
recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2));
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
LinearLayout jual = root.findViewById(R.id.btn_jual);
LinearLayout sedekah = root.findViewById(R.id.btn_sedekah);
LinearLayout baitullah = root.findViewById(R.id.btn_baitullah);
ImageView notif = root.findViewById(R.id.notif);
ReddotNotif reddotNotif = new ReddotNotif(getContext());
if(reddotNotif.isRedDot())
{
notif.setImageResource(R.drawable.ic_notify);
}
else {
notif.setImageResource(R.drawable.ic_notif);
}
notif.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
reddotNotif.logout();
startActivity(new Intent(getActivity(), HistorynotificationActivity.class));
}
});
baitullah.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(sessionManager.isLoggin())
{
startActivity(new Intent(getActivity(), MenujubaitullahActivity.class));
}
else {
Intent intent = new Intent(getActivity(), MustloginActivity.class);
intent.putExtra("type", "baitullah");
startActivity(intent);
}
}
});
jual.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(sessionManager.isLoggin())
{
startActivity(new Intent(getActivity(), JualsampahActivity.class));
}
else {
Intent intent = new Intent(getActivity(), MustloginActivity.class);
intent.putExtra("type", "jual");
startActivity(intent);
}
}
});
sedekah.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Boolean login = false;
if(sessionManager.isLoggin())
{
startActivity(new Intent(getActivity(), SedekahsampahActivity.class));
}
else {
Intent intent = new Intent(getActivity(), MustloginActivity.class);
intent.putExtra("type", "sedekah");
startActivity(intent);
}
}
});
Button login = root.findViewById(R.id.login_button);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getActivity(), LoginActivity.class));
}
});
TextView FAQ = root.findViewById(R.id.faq);
String FAQTEXT = "Untuk informasi lebih lanjut, kunjungi halaman FAQ. <font color=#0098FF>di sini </font> ";
FAQ.setText(Html.fromHtml(FAQTEXT));
FAQ.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getActivity(), FaqActivity.class));
}
});
return root;
}
private void getbanner() {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference table = database.getReference("Banner");
table.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(isAdded())
{
sliderData.clear();
for (DataSnapshot npsnapshot : snapshot.getChildren()){
SliderData l = npsnapshot.getValue(SliderData.class);
sliderData.add(l);
}
sliderAdapter = new SliderAdapter((ArrayList<SliderData>) sliderData);
cardSliderViewPager.setAdapter(sliderAdapter);
cardSliderViewPager.setSmallScaleFactor(0.9f);
cardSliderViewPager.setSmallAlphaFactor(0.5f);
cardSliderViewPager.setAutoSlideTime(5);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
this my Category class :
public class Category {
private String id;
private String name;
private String picture_path;
public Category(){
}
public Category(String id, String name, String picture_path) {
this.id = id;
this.name = name;
this.picture_path = picture_path;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPicture_path() {
return picture_path;
}
public void setPicture_path(String picture_path) {
this.picture_path = picture_path;
}
}
and this category at database :
category database
can you help me please, I've been looking for a week where it went wrong, but still can't find it.

How to get the specific key in realtime database?

I am currently having a trouble on deleting a specific data from my firebase. So basically I have recyclerview wherein my datas are displayed and I have a button in each data display there and that's EDIT button. Whenever I try to click the EDIT button it should intent me to another activity with the same data displayed in the recyclerview and there's a another button displayed there and that's DELETE button. But whenever I try to click the delete button, it deletes all the data from the child. I only need to DELETE the selected ID/Data that is passing when intent occurs.
Edit.
EditResearch.java
package com.example.citeresearchrepository.AdminPackage;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.citeresearchrepository.Model.ResearchRepository;
import com.example.citeresearchrepository.R;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
public class EditResearchActivity extends AppCompatActivity {
EditText editfilehandler_et,editrepo_title,editrepo_description,editrepo_currentdate;
Button editrepo_savebtn;
ImageView backbtn_editresearch;
DatabaseReference databaseReference;
FirebaseDatabase firebaseDatabase;
StorageReference storageReference;
String researchtitle,researchdate,researchname,researchdescription;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_research);
editfilehandler_et = findViewById(R.id.editfilehandler_et);
editrepo_title = findViewById(R.id.editrepo_title);
editrepo_description = findViewById(R.id.editrepo_description);
editrepo_currentdate = findViewById(R.id.editrepo_currentdate);
editrepo_savebtn = findViewById(R.id.editrepo_savebtn);
backbtn_editresearch = findViewById(R.id.backbtn_editresearch);
Intent intent = getIntent();
researchtitle = intent.getStringExtra("researchtitle");
researchdate = intent.getStringExtra("researchdate");
researchname = intent.getStringExtra("researchname");
researchdescription = intent.getStringExtra("researchdescription");
databaseReference = FirebaseDatabase.getInstance().getReference("ResearchRepository");
storageReference = FirebaseStorage.getInstance().getReference();
editfilehandler_et.setText(researchname);
editrepo_title.setText(researchtitle);
editrepo_currentdate.setText(researchdate);
editrepo_description.setText(researchdescription);
editrepo_savebtn.setEnabled(false);
editfilehandler_et.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectPDF();
}
});
/* Update Files */
backbtn_editresearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), AdminResearchRepoActivity.class));
}
});
}
private void selectPDF(){
Intent intent = new Intent();
intent.setType("application/pdf");
intent.setAction(intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "PDF FILE SELECTED"), 12);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==12 && resultCode == RESULT_OK && data!=null && data.getData()!=null){
editrepo_savebtn.setEnabled(true);
editfilehandler_et.setText(data.getDataString().substring(data.getDataString().lastIndexOf("/") + 1));
editrepo_savebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deletePreviousImage();
uploadResearch(data.getData());
}
});
}
}
private void deleteSelectedRow(){
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference("ResearchRepository");
databaseReference.removeValue();
}
private void uploadResearch(Uri data) {
final String filecapture = editfilehandler_et.getText().toString();
final String researchtitle = editrepo_title.getText().toString();
final String researchdescription = editrepo_description.getText().toString();
final String researchtimeline = editrepo_currentdate.getText().toString();
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("File Uploading...");
progressDialog.show();
StorageReference reference = storageReference.child("ResearchRepository" +System.currentTimeMillis() + ".pdf");
reference.putFile(data).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl();
while(!uriTask.isComplete());
Uri uri = uriTask.getResult();
ResearchRepository researchRepository = new ResearchRepository(filecapture,researchtitle,researchdescription,researchtimeline,uri.toString());
databaseReference.child(databaseReference.push().getKey()).setValue(researchRepository);
Toast.makeText(EditResearchActivity.this, "File Uploaded", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
editfilehandler_et.setText("");
editrepo_title.setText("");
editrepo_currentdate.setText("");
editrepo_description.setText("");
startActivity(new Intent(getApplicationContext(), AdminResearchRepoActivity.class));
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot snapshot) {
double progress = (100*snapshot.getBytesTransferred())/snapshot.getTotalByteCount();
progressDialog.setMessage("File Uploading..."+(int)progress+"%");
}
});
}
private void deletePreviousImage(){
StorageReference reference = FirebaseStorage.getInstance().getReference().child(researchtitle);
reference.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(EditResearchActivity.this, "Previous File Deleted", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(EditResearchActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
AdminResearchRepoActivity.java
package com.example.citeresearchrepository.AdminPackage;
import androidx.annotation.NonNull;
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.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.citeresearchrepository.AdminAdapter.AdminRepoAdapter;
import com.example.citeresearchrepository.Model.ResearchRepository;
import com.example.citeresearchrepository.R;
import com.example.citeresearchrepository.ViewHolder.AdminResearchRepositoryViewHolder;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
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 AdminResearchRepoActivity extends AppCompatActivity {
ImageView adminrepo_backbtn;
RecyclerView reporecycler;
FloatingActionButton addresearch_btn;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
AdminRepoAdapter adminRepoAdapter;
ArrayList<ResearchRepository> researchRepositoryArrayList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_research_repo);
// Buttons
adminrepo_backbtn = findViewById(R.id.backbtn_adminrepo);
addresearch_btn = findViewById(R.id.addresearch_btn);
addresearch_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), AddResearchActivity.class));
}
});
adminrepo_backbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), WelcomeAdminActivity.class));
}
});
// Recycler
reporecycler = findViewById(R.id.reporecycler);
reporecycler.setLayoutManager(new LinearLayoutManager(this));
// Firebase Connection
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = FirebaseDatabase.getInstance().getReference().child("ResearchRepository");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
researchRepositoryArrayList = new ArrayList<ResearchRepository>();
for (DataSnapshot dataSnapshot: snapshot.getChildren()){
ResearchRepository researchRepository = dataSnapshot.getValue(ResearchRepository.class);
researchRepositoryArrayList.add(researchRepository);
}
adminRepoAdapter = new AdminRepoAdapter(AdminResearchRepoActivity.this,researchRepositoryArrayList);
reporecycler.setAdapter(adminRepoAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(AdminResearchRepoActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
AdminRepoAdapter.java
package com.example.citeresearchrepository.AdminAdapter;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.citeresearchrepository.AdminPackage.EditResearchActivity;
import com.example.citeresearchrepository.Model.ResearchRepository;
import com.example.citeresearchrepository.R;
import java.lang.reflect.Array;
import java.util.ArrayList;
public class AdminRepoAdapter extends RecyclerView.Adapter<AdminRepoAdapter.AdminViewHolder> {
Context context;
ArrayList<ResearchRepository> researchRepositories;
public AdminRepoAdapter(Context c, ArrayList<ResearchRepository> repositories){
context = c;
researchRepositories = repositories;
}
#NonNull
#Override
public AdminViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new AdminViewHolder(LayoutInflater.from(context).inflate(R.layout.admineditrepo_row,parent,false));
}
#Override
public void onBindViewHolder(#NonNull AdminViewHolder holder, final int position) {
holder.researchtitle_view.setText(researchRepositories.get(position).getResearchtitle());
holder.researchdate_view.setText(researchRepositories.get(position).getResearchtimeline());
holder.researchname_view.setText(researchRepositories.get(position).getFilecapture());
holder.researchdescription_view.setText(researchRepositories.get(position).getResearchdescription());
holder.btnpdf_edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, EditResearchActivity.class);
intent.putExtra("researchtitle",researchRepositories.get(position).getResearchtitle());
intent.putExtra("researchdate",researchRepositories.get(position).getResearchtimeline());
intent.putExtra("researchname",researchRepositories.get(position).getFilecapture());
intent.putExtra("researchdescription",researchRepositories.get(position).getResearchdescription());
v.getContext().startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return researchRepositories.size();
}
class AdminViewHolder extends RecyclerView.ViewHolder{
public TextView researchtitle_view,researchdate_view,researchname_view,researchdescription_view,researchtitle_url;
public Button btnpdf_edit;
public AdminViewHolder (#NonNull View itemView) {
super(itemView);
researchtitle_view = itemView.findViewById(R.id.researchtitle_view);
researchdate_view = itemView.findViewById(R.id.researchdate_view);
researchname_view = itemView.findViewById(R.id.researchname_view);
researchdescription_view = itemView.findViewById(R.id.researchdescription_view);
researchtitle_url = itemView.findViewById(R.id.researchtitle_view);
btnpdf_edit = itemView.findViewById(R.id.btnpdf_edit);
}
}
}
ResearchRepository.class
package com.example.citeresearchrepository.Model;
public class ResearchRepository {
public String filecapture;
public String researchtitle;
public String researchdescription;
public String researchtimeline;
public String url;
public ResearchRepository() {
}
public ResearchRepository(String filecapture, String researchtitle, String researchdescription, String researchtimeline, String url) {
this.filecapture = filecapture;
this.researchtitle = researchtitle;
this.researchdescription = researchdescription;
this.researchtimeline = researchtimeline;
this.url = url;
}
public String getFilecapture() {
return filecapture;
}
public void setFilecapture(String filecapture) {
this.filecapture = filecapture;
}
public String getResearchtitle() {
return researchtitle;
}
public void setResearchtitle(String researchtitle) {
this.researchtitle = researchtitle;
}
public String getResearchdescription() {
return researchdescription;
}
public void setResearchdescription(String researchdescription) {
this.researchdescription = researchdescription;
}
public String getResearchtimeline() {
return researchtimeline;
}
public void setResearchtimeline(String researchtimeline) {
this.researchtimeline = researchtimeline;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
Here's my realtime-database : https://i.stack.imgur.com/lML0i.png
I just wanna delete the red box.
From what I see you are getting an instance to only the ResearchRepository node instead of the specific child node that you want to delete. You need to keep track of the unique IDs you are pushing on to the ResearchRepository node and pass it in the intent as well;
Add the code to pass the unique ID of the ResearchRepository child you want to delete.
Then do this in your new activity where the delete code is present.
String childToDelete; //retrieve the value from the intent
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("ResearchRepository").child(childToDelete);
databaseReference.removeValue();
This should do it if that is your purpose.
Edit 1:-
I got your point. Please follow the approach I will be showing now and it will work for you.
Edit your class as shown below:-
AdminRepoAdapter.java
public class AdminRepoAdapter extends RecyclerView.Adapter<AdminRepoAdapter.AdminViewHolder> {
Context context;
Map<String,ResearchRepository> researchRepositories;
ArrayList<ResearchRepository> researchRepositoriesHolder;
public AdminRepoAdapter(Context c, Map<String,ResearchRepository> repositories){
context = c;
researchRepositories = repositories;
researchRepositoriesHolder = new ArrayList<>(researchRepositories.values());
}
#NonNull
#Override
public AdminViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new AdminViewHolder(LayoutInflater.from(context).inflate(R.layout.admineditrepo_row,parent,false));
}
#Override
public void onBindViewHolder(#NonNull AdminViewHolder holder, final int position) {
holder.researchtitle_view.setText(researchRepositoriesHolder.get(position).getResearchtitle());
holder.researchdate_view.setText(researchRepositoriesHolder.get(position).getResearchtimeline());
holder.researchname_view.setText(researchRepositoriesHOlder.get(position).getFilecapture());
holder.researchdescription_view.setText(researchRepositoriesHolder.get(position).getResearchdescription());
holder.btnpdf_edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Map.Entry<String,ResearchRepository> entry = null; //Just for initialization
for (Map.Entry<String,ResearchRepository> var : researchRepositories.entrySet()) {
if(var.getValue() == researchRepositoriesHolder.get(position)){
entry = var;
break;
}
}
Intent intent = new Intent(context, EditResearchActivity.class);
intent.putExtra("researchtitle",entry.getValue().getResearchtitle());
intent.putExtra("researchdate",entry.getValue().getResearchtimeline());
intent.putExtra("researchname",entry.getValue().getFilecapture());
intent.putExtra("researchdescription",entry.getValue().getResearchdescription());
intent.putExtra("childNodeKey",entry.getKey());
v.getContext().startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return researchRepositoriesHolder.size();
}
class AdminViewHolder extends RecyclerView.ViewHolder{
public TextView researchtitle_view,researchdate_view,researchname_view,researchdescription_view,researchtitle_url;
public Button btnpdf_edit;
public AdminViewHolder (#NonNull View itemView) {
super(itemView);
researchtitle_view = itemView.findViewById(R.id.researchtitle_view);
researchdate_view = itemView.findViewById(R.id.researchdate_view);
researchname_view = itemView.findViewById(R.id.researchname_view);
researchdescription_view = itemView.findViewById(R.id.researchdescription_view);
researchtitle_url = itemView.findViewById(R.id.researchtitle_view);
btnpdf_edit = itemView.findViewById(R.id.btnpdf_edit);
}
}
}
AdminResearchRepoActivity.java
public class AdminResearchRepoActivity extends AppCompatActivity {
ImageView adminrepo_backbtn;
RecyclerView reporecycler;
FloatingActionButton addresearch_btn;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
AdminRepoAdapter adminRepoAdapter;
Map<String, ResearchRepository> researchRepositoryMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_research_repo);
// Buttons
adminrepo_backbtn = findViewById(R.id.backbtn_adminrepo);
addresearch_btn = findViewById(R.id.addresearch_btn);
addresearch_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), AddResearchActivity.class));
}
});
adminrepo_backbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), WelcomeAdminActivity.class));
}
});
// Recycler
reporecycler = findViewById(R.id.reporecycler);
reporecycler.setLayoutManager(new LinearLayoutManager(this));
// Firebase Connection
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = FirebaseDatabase.getInstance().getReference().child("ResearchRepository");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
researchRepositoryMap = (Map)snapshot.getValue()
adminRepoAdapter = new AdminRepoAdapter(AdminResearchRepoActivity.this,researchRepositoryMap);
reporecycler.setAdapter(adminRepoAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(AdminResearchRepoActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
In this way when you pass a Intent from your AdminRepoAdapter to EditResearchActivity you will have the key stored as 'childNodeKey' in your intent.
You can then follow the procedure I mentioned before the edit to delete using the key you got from here.

Whenever adding data into firebase real time database it print with all previous data

Facing an error.
I am making a chat application with firebase. where i am sending and printing the data from Firebase Realtime Database. the issue is that whenever i am adding or sending a data into the Firebase Realtime Database, its not only printing the currently added data but also printing the whole data from node Chats again and again wherever any data added into the Firebase Realtime Database.
how can i fix this?
Whats my think to solve the error?
I think removing of event listener which are being attached on call of
getMessage(); can fix the error.
This is my ChatActivity
package com.socialcodia.sherewatan;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
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.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
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.Query;
import com.google.firebase.database.ValueEventListener;
import com.socialcodia.sherewatan.adapter.ChatAdapter;
import com.socialcodia.sherewatan.model.ChatModel;
import com.socialcodia.sherewatan.storage.Constants;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class ChatActivity extends AppCompatActivity {
Toolbar toolbar;
private EditText inputMessage;
private ImageButton btnSendMessage;
private TextView toolbarUserName, toolbarUserStatus;
private ImageView toolbarUserImage;
//Firebase
FirebaseAuth firebaseAuth;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
DatabaseReference chatDatabaseReference;
FirebaseUser firebaseUser;
RecyclerView chatRecyclerView;
Intent intent;
String toUid;
String myUid;
List<ChatModel> chatList;
ChatAdapter chatAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
//init Chat Recycler View
chatRecyclerView = findViewById(R.id.chatRecyclerView);
//set layout manager at chatRecyclerview
LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
chatRecyclerView.setLayoutManager(layoutManager);
//Firebase Init
firebaseAuth = FirebaseAuth.getInstance();
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference("Users");
chatDatabaseReference = firebaseDatabase.getReference("Chats");
firebaseUser =firebaseAuth.getCurrentUser();
//Init
inputMessage = findViewById(R.id.inputMessage);
btnSendMessage = findViewById(R.id.btnSendMessage);
toolbarUserName = findViewById(R.id.toolbarUserName);
toolbarUserStatus = findViewById(R.id.toolbarUserStatus);
toolbarUserImage = findViewById(R.id.toolbarUserImage);
toolbar = findViewById(R.id.chat_toolbar);
setSupportActionBar(toolbar);
intent = getIntent();
//Data From intent
toUid = intent.getStringExtra("uid");
//Click listener on btn send message
btnSendMessage.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
ValidateAndSendMessage();
}
});
getMessage();
}
private void ValidateAndSendMessage()
{
String message = inputMessage.getText().toString().trim();
if (message.isEmpty())
{
Toast.makeText(this, "Can't send empty message", Toast.LENGTH_SHORT).show();
}
else
{
sendMessage(message);
}
}
private void sendMessage(String message)
{
HashMap<String, Object> map = new HashMap<>();
map.put("msg",message);
map.put(Constants.TIMESTAMP,System.currentTimeMillis()/1000);
map.put("fromUid",myUid);
map.put("toUid",toUid);
DatabaseReference chatRef = firebaseDatabase.getReference("Chats");
chatRef.push().setValue(map);
inputMessage.setText("");
}
private void getMessage()
{
chatList = new ArrayList<>();
final DatabaseReference chatRef = firebaseDatabase.getReference("Chats");
chatRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren())
{
ChatModel chatModel = ds.getValue(ChatModel.class);
if (chatModel.getFromUid().equals(myUid) && chatModel.getToUid().equals(toUid) ||
chatModel.getFromUid().equals(toUid) && chatModel.getToUid().equals(myUid))
{
chatList.add(chatModel);
}
chatAdapter = new ChatAdapter(chatList,getApplicationContext());
chatAdapter.notifyDataSetChanged();
chatRecyclerView.setAdapter(chatAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
This is my ChatAdapter.class
package com.socialcodia.sherewatan.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.socialcodia.sherewatan.R;
import com.socialcodia.sherewatan.model.ChatModel;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
public class ChatAdapter extends RecyclerView.Adapter<ChatAdapter.ChatViewHolder> {
List<ChatModel> modelClassList;
Context context;
private static final int MSG_TYPE_RIGHT = 0;
private static final int MSG_TYPE_LEFT = 1;
FirebaseUser firebaseUser;
public ChatAdapter(List<ChatModel> modelClassList, Context context) {
this.modelClassList = modelClassList;
this.context = context;
}
#NonNull
#Override
public ChatViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if (viewType==MSG_TYPE_RIGHT)
{
View view = LayoutInflater.from(context).inflate(R.layout.chat_right,parent,false);
ChatViewHolder viewHolder = new ChatViewHolder(view);
return viewHolder;
}
else
{
View view = LayoutInflater.from(context).inflate(R.layout.chat_left,parent,false);
ChatViewHolder viewHolder = new ChatViewHolder(view);
return viewHolder;
}
}
#Override
public void onBindViewHolder(#NonNull ChatViewHolder holder, int position) {
String msg = modelClassList.get(position).getMsg();
Long timestamp = modelClassList.get(position).getTimestamp();
holder.tvChatMessage.setText(msg);
holder.tvChatTime.setText(getTime(timestamp));
}
private String getTime(Long timestamp) {
Long ts = timestamp*1000;
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:a");
String time = sdf.format(new Date(ts));
return time;
}
#Override
public int getItemCount() {
return modelClassList.size();
}
#Override
public int getItemViewType(int position) {
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if (modelClassList.get(position).getFromUid().equals(firebaseUser.getUid()))
{
return MSG_TYPE_RIGHT;
}
else
{
return MSG_TYPE_LEFT;
}
}
public class ChatViewHolder extends RecyclerView.ViewHolder
{
private TextView tvChatMessage, tvChatTime;
public ChatViewHolder(#NonNull View itemView) {
super(itemView);
tvChatMessage = itemView.findViewById(R.id.tvChatMessage);
tvChatTime = itemView.findViewById(R.id.tvChatTime);
}
}
}
This is my ChatModel.class
package com.socialcodia.sherewatan.model;
public class ChatModel {
public String fromUid, toUid, msg;
Long timestamp;
public ChatModel() {
}
public ChatModel(String fromUid, String toUid, String msg, Long timestamp) {
this.fromUid = fromUid;
this.toUid = toUid;
this.msg = msg;
this.timestamp = timestamp;
}
public String getFromUid() {
return fromUid;
}
public void setFromUid(String fromUid) {
this.fromUid = fromUid;
}
public String getToUid() {
return toUid;
}
public void setToUid(String toUid) {
this.toUid = toUid;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Long getTimestamp() {
return timestamp;
}
public void setTimestamp(Long timestamp) {
this.timestamp = timestamp;
}
}
You forgot to clear the modelClassList.
private void getMessage()
{
chatList = new ArrayList<>();
final DatabaseReference chatRef = firebaseDatabase.getReference("Chats");
chatRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
chatList.clear(); // Clear list
for (DataSnapshot ds : dataSnapshot.getChildren())
{
ChatModel chatModel = ds.getValue(ChatModel.class);
if (chatModel.getFromUid().equals(myUid) && chatModel.getToUid().equals(toUid) ||
chatModel.getFromUid().equals(toUid) && chatModel.getToUid().equals(myUid))
{
chatList.add(chatModel);
}
chatAdapter = new ChatAdapter(chatList,getApplicationContext());
chatAdapter.notifyDataSetChanged();
chatRecyclerView.setAdapter(chatAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
That will clear the list as well fix your problem.
Declare HashMap or ArrayList globally and write this code map.clear() or arrayList.clear() at the very beginning of the method from which you are retreiving your data. Hopefully the problem will be solved.

Firebase list child in listview

I'm new to Firebase, and I need to show a child info on a listview. It adds the data, but it does not show on listview and the app crashes. No error is shown on log, but on firebase crash I have this error:
Exception com.google.firebase.database.DatabaseException: Failed to convert value of type java.util.HashMap to String
com.google.android.gms.internal.zzamy.zzcg ()
com.google.android.gms.internal.zzamy.zzb ()
com.google.android.gms.internal.zzamy.zza ()
com.google.firebase.database.DataSnapshot.getValue ()
br.com.imobapp.CorretorFragment$1.onChildAdded (CorretorFragment.java:58)
com.google.android.gms.internal.zzaip.zza ()
com.google.android.gms.internal.zzakp.zzcxi ()
com.google.android.gms.internal.zzaks$1.run ()
android.os.Handler.handleCallback (Handler.java:739)
android.os.Handler.dispatchMessage (Handler.java:95)
android.os.Looper.loop (Looper.java:145)
android.app.ActivityThread.main (ActivityThread.java:5832)
My data is like this (Sorry, can't post pics since my account is new, only the link):
https://i.stack.imgur.com/lZHFC.jpg
My model is:
import com.google.firebase.database.IgnoreExtraProperties;
#IgnoreExtraProperties
public class ModelCorretor {
private String CorNome;
private String CorCreci;
public ModelCorretor(){
};
public ModelCorretor(String CorNome, String CorCreci){
this.CorNome = CorNome;
this.CorCreci = CorCreci;
};
public String getCorNome() {
return CorNome;
}
public void setCorNome(String corNome) {
CorNome = corNome;
}
public String getCorCreci() {
return CorCreci;
}
public void setCorCreci(String corCreci) {
CorCreci = corCreci;
}
}
And my fragment for showing it on listview:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
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.google.firebase.database.FirebaseDatabase;
import java.util.ArrayList;
import static android.content.ContentValues.TAG;
public class CorretorFragment extends Fragment implements View.OnClickListener {
public CorretorFragment() {
// Required empty public constructor
}
ImageButton btAddCor, btSearchCor;
ListView lvCorretor;
DatabaseReference dref;
ArrayList<String> list = new ArrayList<>();
ArrayAdapter<String> adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_corretor, container, false);
btAddCor =(ImageButton)view.findViewById(R.id.btAddCor);
btAddCor.setOnClickListener(this);
btSearchCor =(ImageButton)view.findViewById(R.id.btSearchCor);
btSearchCor.setOnClickListener(this);
lvCorretor = (ListView)view.findViewById(R.id.lvCorretor);
adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_dropdown_item_1line, list);
lvCorretor.setAdapter(adapter);
dref = FirebaseDatabase.getInstance().getReference().child("Corretores");
dref.addChildEventListener(new ChildEventListener() {
#Override
// Read from the database
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String value = dataSnapshot.getValue(String.class);
list.add(value);
adapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
String value = dataSnapshot.getValue(String.class);
list.remove(value);
adapter.notifyDataSetChanged();
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
return view;
}
#Override
public void onClick(View view){
MainActivity activity = (MainActivity)getActivity();
switch(view.getId()){
case R.id.btAddCor:
activity.chamaAddCor();
break;
case R.id.btSearchCor:
activity.chamaSearchCor();
break;
default: throw new RuntimeException("unreachable");
}
}
}
If any more code is needed or if I did something wrong in the question, please let me know.
I have an idea that I have to set a child for it to show, like I did in FirebaseDatabase.getInstance().getReference().child("Corretores"); but I tried a lot and have no clue how to do it on the onChildAdded.
The issue is here:
String value = dataSnapshot.getValue(String.class);
You shouldn't be getting a String object, you should be getting the model for the object you want. You have a model for your Corretor, so you do:
ModelCorretor value = dataSnapshot.getValue(ModelCorretor.class);
getValue returns a hashmap and you are assigning it to a string, which is why you are getting that error. Firebase is great in that it will build that object for you by just inserting the ModelCorretor as a parameter in the getValue method.

Categories

Resources