I'm getting error on getUid()
final String user_id = mAuth.getCurrentUser().getUid();
and this my activity code :
public class MainActivity extends AppCompatActivity {
private RecyclerView postList;
private DatabaseReference mDatabase;
private DatabaseReference mDatabaseUsers;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() == null){
Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(loginIntent);
}
}
};
mDatabase = FirebaseDatabase.getInstance().getReference().child("Blog");
mDatabaseUsers = FirebaseDatabase.getInstance().getReference().child("Users");
mDatabase.keepSynced(true);
mDatabaseUsers.keepSynced(true);
postList = (RecyclerView) findViewById(R.id.post_list);
postList.setHasFixedSize(true);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
postList.setLayoutManager(layoutManager);
}
#Override
protected void onStart() {
super.onStart();
CheckUserExist();
mAuth.addAuthStateListener(mAuthListener);
FirebaseRecyclerAdapter<Blog, BlogViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Blog, BlogViewHolder>(
Blog.class,
R.layout.post_row,
BlogViewHolder.class,
mDatabase
) {
#Override
protected void populateViewHolder(BlogViewHolder viewHolder, Blog model, int position) {
viewHolder.setTitle(model.getTitle());
viewHolder.setDesc(model.getDescription());
viewHolder.setImage(getApplicationContext(), model.getImage());
}
};
postList.setAdapter(firebaseRecyclerAdapter);
}
private void CheckUserExist() {
final String user_id = mAuth.getCurrentUser().getUid();
mDatabaseUsers.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!dataSnapshot.hasChild(user_id)){
Intent SetupIntent = new Intent(MainActivity.this, SetupActivity.class);
SetupIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(SetupIntent);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public static class BlogViewHolder extends RecyclerView.ViewHolder{
View mView;
public BlogViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setTitle(String title){
TextView post_title = (TextView) mView.findViewById(R.id.post_title);
post_title.setText(title);
}
public void setDesc(String desc){
TextView post_desc = (TextView) mView.findViewById(R.id.post_desc);
post_desc.setText(desc);
}
public void setImage(final Context ctx, final String image){
final ImageView post_image = (ImageView) mView.findViewById(R.id.post_img);
// Picasso.with(ctx).load(image).into(post_image);
Picasso.with(ctx).load(image).networkPolicy(NetworkPolicy.OFFLINE).into(post_image, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
Picasso.with(ctx).load(image).into(post_image);
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_add){
startActivity(new Intent(MainActivity.this, PostActivity.class));
}
if (item.getItemId() == R.id.action_logout){
logout();
}
return super.onOptionsItemSelected(item);
}
private void logout() {
mAuth.signOut();
}
}
The problem happens when you try to call mAuth.getCurrentUser().getUid(). Apparently there is no current user at the time, so that call fails.
Instead use:
private void CheckUserExist() {
if (mAuth.getCurrentUser() != null) {
final String user_id = mAuth.getCurrentUser().getUid();
mDatabaseUsers.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!dataSnapshot.hasChild(user_id)){
Intent SetupIntent = new Intent(MainActivity.this, SetupActivity.class);
SetupIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(SetupIntent);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
In general, you'll want to use an auth state listener for this, similar to the one you already have in onCreate.
In fact, it seems to me that both could easily be folded into a single listener: one that starts the login activity if the user isn't signed in and optionally registers the user with the database if they are.
The code for that:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDatabase = FirebaseDatabase.getInstance().getReference().child("Blog");
mDatabaseUsers = FirebaseDatabase.getInstance().getReference().child("Users");
mDatabase.keepSynced(true);
mDatabaseUsers.keepSynced(true);
postList = (RecyclerView) findViewById(R.id.post_list);
postList.setHasFixedSize(true);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
postList.setLayoutManager(layoutManager);
}
#Override
protected void onStart() {
super.onStart();
CheckUserExist();
FirebaseAuth.getInstance().addAuthStateListener(new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user == null){
// The user is not signed in, start login flow
Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(loginIntent);
}
else {
// The user is signed in, register them in database
String user_id = user.getUid();
mDatabaseUsers.child(user_id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!dataSnapshot.exists()){
Intent SetupIntent = new Intent(MainActivity.this, SetupActivity.class);
SetupIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(SetupIntent);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore onCancelled
}
});
}
}
});
FirebaseRecyclerAdapter<Blog, BlogViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Blog, BlogViewHolder>(
Blog.class,
R.layout.post_row,
BlogViewHolder.class,
mDatabase
) {
#Override
protected void populateViewHolder(BlogViewHolder viewHolder, Blog model, int position) {
viewHolder.setTitle(model.getTitle());
viewHolder.setDesc(model.getDescription());
viewHolder.setImage(getApplicationContext(), model.getImage());
}
};
postList.setAdapter(firebaseRecyclerAdapter);
}
I also fixed the way you check if the user already exists in the database. Retrieving all users to then client-side check if one of the keys exists is a waste of bandwidth that will become especially evident as your number of users grows. The code I wrote checks precisely whether this user's UID already exists in the database, which is the minimum data you can check.
It is because you are not initializing mauth.
remove onstart method and copy the code to oncreate. oncreate will be
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() == null){
Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(loginIntent);
}
}
};
mDatabase = FirebaseDatabase.getInstance().getReference().child("Blog");
mDatabaseUsers = FirebaseDatabase.getInstance().getReference().child("Users");
mDatabase.keepSynced(true);
mDatabaseUsers.keepSynced(true);
postList = (RecyclerView) findViewById(R.id.post_list);
postList.setHasFixedSize(true);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
postList.setLayoutManager(layoutManager);
CheckUserExist();
mAuth.addAuthStateListener(mAuthListener);
FirebaseRecyclerAdapter<Blog, BlogViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Blog, BlogViewHolder>(
Blog.class,
R.layout.post_row,
BlogViewHolder.class,
mDatabase
) {
#Override
protected void populateViewHolder(BlogViewHolder viewHolder, Blog model, int position) {
viewHolder.setTitle(model.getTitle());
viewHolder.setDesc(model.getDescription());
viewHolder.setImage(getApplicationContext(), model.getImage());
}
};
postList.setAdapter(firebaseRecyclerAdapter);
}
Related
I am trying to fix a bug in an app I am developing with the help of some tutorials, and in these videos people share my error and they found the answer using "isAdded()", but the problem for me is that I am using API level 29, and in the official website says that this was deprecated in level 28. I dont want to change my project target to API level 28 because that could make it crash, so anyone know how I could solve this?
It should look this way, isAdded is highlighted in red.
public class MessageActivity extends AppCompatActivity {
CircleImageView profile_image;
TextView username;
FirebaseUser fuser;
DatabaseReference reference;
ImageButton button_send;
EditText text_sent;
MessageAdapter messageAdapter;
List<Chat> mchat;
RecyclerView recyclerView;
Intent intent;
ValueEventListener seenListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MessageActivity.this, MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
//finish();
}
});
recyclerView = findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
linearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayoutManager);
profile_image = findViewById(R.id.profile_image);
username = findViewById(R.id.username);
button_send = findViewById(R.id.button_send);
text_sent = findViewById(R.id.text_sent);
intent = getIntent();
final String userid = intent.getStringExtra("userid");
fuser = FirebaseAuth.getInstance().getCurrentUser();
button_send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String msg = text_sent.getText().toString();
if (!msg.equals("")) {
sendMessage(fuser.getUid(), userid, msg);
}
else {
Toast.makeText(MessageActivity.this, "You can´t send empty messages", Toast.LENGTH_SHORT).show();
}
text_sent.setText("");
}
});
reference = FirebaseDatabase.getInstance().getReference("Users").child(userid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (isAdded()) { //HERE
User user = dataSnapshot.getValue(User.class);
username.setText(user.getUsername());
if (user.getImageURL().equals("default")) {
profile_image.setImageResource(R.mipmap.ic_launcher);
}
else {
Glide.with(getApplicationContext()).load(user.getImageURL()).into(profile_image);
}
readMessages(fuser.getUid(), userid, user.getImageURL());
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
seenMessage(userid);
}
private void seenMessage(final String userid) {
reference = FirebaseDatabase.getInstance().getReference("Chats");
seenListener = reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Chat chat = snapshot.getValue(Chat.class);
if (chat.getReceiver().equals(fuser.getUid()) && chat.getSender().equals(userid)) {
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("isseen", true);
snapshot.getRef().updateChildren(hashMap);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void sendMessage(String sender, String receiver, String message){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
final String userid = intent.getStringExtra("userid");
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("sender", sender);
hashMap.put("receiver", receiver);
hashMap.put("message", message);
hashMap.put("isseen", false);
reference.child("Chats").push().setValue(hashMap);
final DatabaseReference chatRef = FirebaseDatabase.getInstance().getReference("Chatlist")
.child(fuser.getUid())
.child(userid);
chatRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (!dataSnapshot.exists()) {
chatRef.child("id").setValue(userid);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void readMessages(final String myid, final String userid, final String imageurl) {
mchat = new ArrayList<>();
reference = FirebaseDatabase.getInstance().getReference("Chats");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mchat.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Chat chat = snapshot.getValue(Chat.class);
if (chat.getReceiver().equals(myid) && chat.getSender().equals(userid) ||
chat.getReceiver().equals(userid) && chat.getSender().equals(myid)) {
mchat.add(chat);
}
messageAdapter = new MessageAdapter(MessageActivity.this, mchat, imageurl);
recyclerView.setAdapter(messageAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void status(String status) {
reference = FirebaseDatabase.getInstance().getReference("Users").child(fuser.getUid());
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("status", status);
reference.updateChildren(hashMap);
}
#Override
protected void onResume() {
super.onResume();
status("online");
}
#Override
protected void onPause() {
super.onPause();
reference.removeEventListener(seenListener);
status("offline");
}
}
Edit: You can remove isAdded() condition because you're using an Activity and not a Fragment.
Original answer:
android.app.Fragment class was deprecated in API 28.
Instead use this androidx.fragment.app.Fragment class from AndroidX.
Declare this dependency in your build.gradle file and use androidx.fragment.app.Fragment import in your fragment class instead of android.app.Fragment
I'm trying to delete the selected item in my RecyclerView, but when I click on my delete Button it just deletes the last item added. And after I delete the last item added I can not delete anymore. What am I missing?
MainActivity
public class MainWishActivity extends AppCompatActivity {
private NavigationView navigationView;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle actionBarDrawerToggle;
private RecyclerView wishList;
private androidx.appcompat.widget.Toolbar mToolbar;
private ImageButton ibaddnewwishlist;
private CircleImageView NavProfileImage;
private TextView NavProfileFirstName, NavProfileLastName;
private FirebaseAuth mAuth;
private DatabaseReference UsersRef, WishListRef;
String currentUserID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_wish);
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
UsersRef = FirebaseDatabase.getInstance().getReference().child("Brukere");
WishListRef = FirebaseDatabase.getInstance().getReference().child("Ønskelister").child(currentUserID);
mToolbar = (Toolbar) findViewById(R.id.main_page_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle(" Dine Ønskelister");
drawerLayout = (DrawerLayout)findViewById(R.id.drawable_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(MainWishActivity.this, drawerLayout, R.string.drawer_open, R.string.drawer_close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
ibaddnewwishlist = (ImageButton)findViewById(R.id.ib_addnewwishlist);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
navigationView = (NavigationView)findViewById(R.id.navigation_view);
wishList = (RecyclerView)findViewById(R.id.rv_wishlist);
wishList.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
wishList.setLayoutManager(linearLayoutManager);
View navView = navigationView.inflateHeaderView(R.layout.navigation_header);
NavProfileImage = (CircleImageView)navView.findViewById(R.id.civ_navprofilepicture);
NavProfileFirstName = (TextView)navView.findViewById(R.id.tv_headerfirstname);
NavProfileLastName = (TextView) navView.findViewById(R.id.tv_headerlastname);
UsersRef.child(currentUserID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
if (dataSnapshot.hasChild("fornavn")){
String firstname = dataSnapshot.child("fornavn").getValue().toString();
NavProfileFirstName.setText(firstname);
}
if (dataSnapshot.hasChild("etternavn")) {
String lastname = dataSnapshot.child("etternavn").getValue().toString();
NavProfileLastName.setText(lastname);
}
if (dataSnapshot.hasChild("profilbilde")){
String image = dataSnapshot.child("profilbilde").getValue().toString();
Picasso.with(MainWishActivity.this).load(image).placeholder(R.drawable.profile).into(NavProfileImage);
}
else{
Toast.makeText(MainWishActivity.this, "Profil navn finnes ikke...", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
UserMenuSelector(item);
return false;
}
});
ibaddnewwishlist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SendUserToWishListActivity();
}
});
DisplayUsersWishLists();
}
private void DisplayUsersWishLists() {
FirebaseRecyclerAdapter<WishListClass, WishListViewHolder > firebaseRecyclerAdapter =
new FirebaseRecyclerAdapter<WishListClass, WishListViewHolder>
(
WishListClass.class,
R.layout.wish_list_single_layout,
WishListViewHolder.class,
WishListRef
) {
#Override
protected void populateViewHolder(WishListViewHolder viewHolder, WishListClass model, final int position) {
final String Key = getRef(position).getKey();
viewHolder.setFornavn(model.getFornavn());
viewHolder.setDate(model.getDate());
viewHolder.setTitle(model.getTitle());
viewHolder.setProfilbilde(getApplicationContext(), model.getProfilbilde());
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent profileIntent = new Intent(MainWishActivity.this, UserWishItemActivity.class);
profileIntent.putExtra("Key", Key);
startActivity(profileIntent);
}
});
}
};
wishList.setAdapter(firebaseRecyclerAdapter);
}
public static class WishListViewHolder extends RecyclerView.ViewHolder{
View mView;
public WishListViewHolder(#NonNull View itemView) {
super(itemView);
mView = itemView;
}
public void setFornavn (String fornavn){
TextView wishlist_name = (TextView) mView.findViewById(R.id.tv_firstnamelist);
wishlist_name.setText(fornavn);
}
public void setProfilbilde (Context ctx, String profilbilde){
CircleImageView image = (CircleImageView) mView.findViewById(R.id.civ_profilepicturelist);
Picasso.with(ctx).load(profilbilde).into(image);
}
public void setDate (String date){
TextView wishlist_date = (TextView) mView.findViewById(R.id.tv_publisheddatelist);
wishlist_date.setText(" " + date);
}
public void setTitle (String title){
TextView wishlist_title = (TextView) mView.findViewById(R.id.tv_wishlisttitle);
wishlist_title.setText(title);
}
}
private void SendUserToWishListActivity(){
Intent addNewPostIntent = new Intent(MainWishActivity.this, AddWishListActivity.class);
startActivity(addNewPostIntent);
}
#Override
protected void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser == null){
SendUserToLoginActivity();
}
else
{
CheckUserExistence();
}
}
private void CheckUserExistence(){
final String current_user_id = mAuth.getCurrentUser().getUid();
UsersRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (!dataSnapshot.hasChild(current_user_id)){
SendUserToUserInfoAcitivity();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void SendUserToUserInfoAcitivity(){
Intent setupIntent = new Intent(MainWishActivity.this, UserInfoActivity.class);
setupIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(setupIntent);
finish();
}
private void SendUserToLoginActivity() {
Intent loginIntent = new Intent(MainWishActivity.this, LoginActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(loginIntent);
finish();
}
private void SendUserToFindFriendsActivity(){
Intent findfriendsIntent = new Intent(MainWishActivity.this, FindFriendsActivity.class);
findfriendsIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(findfriendsIntent);
finish();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (actionBarDrawerToggle.onOptionsItemSelected(item))
{
return true;
}
return super.onOptionsItemSelected(item);
}
private void UserMenuSelector (MenuItem item){
switch (item.getItemId()){
case R.id.navbtn_addwishlist:
SendUserToWishListActivity();
break;
case R.id.navbtn_profile:
Toast.makeText(this, "Profil", Toast.LENGTH_SHORT).show();
break;
case R.id.navbtn_home:
Toast.makeText(this, "Hjem", Toast.LENGTH_SHORT).show();
break;
case R.id.navbtn_friends:
Toast.makeText(this, "Venner", Toast.LENGTH_SHORT).show();
break;
case R.id.navbtn_findfriends:
SendUserToFindFriendsActivity();
break;
case R.id.navbtn_settings:
Toast.makeText(this, "Instillinger", Toast.LENGTH_SHORT).show();
break;
case R.id.navbtn_logout:
mAuth.signOut();
SendUserToLoginActivity();
break;
}
}
SecondActivity
public class UserWishItemActivity extends AppCompatActivity {
private TextView tvwishlisttitle;
private EditText etwishitem;
private Button btnaddwishitem;
private RecyclerView wishListitems;
private String currentUserID, databaseUserID;
private String Key, postRandomName;
private DatabaseReference WishListUsersClickRef, UsersRef, WishItemsRef, wishListRef,WishItemsRef1;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_add_wish_item);
Key = getIntent().getExtras().get("Key").toString();
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
UsersRef = FirebaseDatabase.getInstance().getReference().child("Brukere");
WishItemsRef = FirebaseDatabase.getInstance().getReference().child("Ønsker");
wishListRef = FirebaseDatabase.getInstance().getReference().child("Ønskelister").child(currentUserID).child(Key);
tvwishlisttitle = (TextView)findViewById(R.id.tv_userwishlisttitle);
etwishitem = (EditText)findViewById(R.id.et_wishitem);
btnaddwishitem = (Button)findViewById(R.id.btn_addwishitem);
btnaddwishitem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CreateWishlist();
}
});
wishListitems = (RecyclerView)findViewById(R.id.rv_wishlistitems);
wishListitems.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
wishListitems.setLayoutManager(linearLayoutManager);
WishListUsersClickRef = FirebaseDatabase.getInstance().getReference("Ønskelister").child(currentUserID).child(Key);
WishListUsersClickRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
String title = dataSnapshot.child("title").getValue().toString();
databaseUserID = dataSnapshot.child("uid").getValue().toString();
tvwishlisttitle.setText(title);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
DisplayWishListItems();
}
private void DisplayWishListItems() {
FirebaseRecyclerAdapter<WishItemClass, WishListItemsViewHolder > firebaseRecyclerAdapter =
new FirebaseRecyclerAdapter<WishItemClass, WishListItemsViewHolder>
(
WishItemClass.class,
R.layout.wish_list_item_layout,
WishListItemsViewHolder.class,
WishItemsRef.child(Key)
) {
#Override
protected void populateViewHolder(final WishListItemsViewHolder viewHolder, final WishItemClass model, final int position) {
viewHolder.setWishitemname(model.getWishitemname());
viewHolder.m1View.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(UserWishItemActivity.this);
LayoutInflater inflater = getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.endreslettjobb_dialog, null);
dialogBuilder.setView(dialogView);
dialogBuilder.setTitle(model.getWishitemname());
final AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();
final Button btndelete = (Button)dialogView.findViewById(R.id.btn_delete);
btndelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
WishItemsRef.removeValue();
}
});
return false;
}
});
}
};
wishListitems.setAdapter(firebaseRecyclerAdapter);
}
public static class WishListItemsViewHolder extends RecyclerView.ViewHolder{
View m1View;
public WishListItemsViewHolder(#NonNull View itemView) {
super(itemView);
m1View = itemView;
}
public void setWishitemname (String wishitemname){
TextView wishitem_name = (TextView) m1View.findViewById(R.id.tv_wishitemname);
wishitem_name.setText(wishitemname);
}
public void setUid (String uid){
}
}
private void CreateWishlist() {
postRandomName = String.valueOf(new Date().getTime());
final String wishlist = etwishitem.getText().toString().trim();
etwishitem.setText("");
wishListRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
HashMap postMap = new HashMap();
postMap.put("uid", currentUserID);
postMap.put("wishitemname", wishlist);
WishItemsRef.child(Key).child(postRandomName).updateChildren(postMap)
.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
AddItemActivity
private Spinner spwishlisttitle;
private Button btnsavewishlist;
private DatabaseReference UsersRef, wishListRef;
private FirebaseAuth mAuth;
private String saveCurrentDate, currentUserID, postRandomName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_wish_list);
UsersRef = FirebaseDatabase.getInstance().getReference().child("Brukere");
wishListRef = FirebaseDatabase.getInstance().getReference().child("Ønskelister");
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
spwishlisttitle = (Spinner) findViewById(R.id.sp_wishlisttitle);
btnsavewishlist = (Button) findViewById(R.id.btn_savewishlist);
btnsavewishlist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CreateWishlist();
}
});
}
private void CreateWishlist() {
Calendar calFordDate = Calendar.getInstance();
SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
saveCurrentDate = currentDate.format(calFordDate.getTime());
postRandomName = String.valueOf(new Date().getTime());
final String wishlist = spwishlisttitle.getSelectedItem().toString().trim();
UsersRef.child(currentUserID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
String userFirstname = dataSnapshot.child("fornavn").getValue().toString();
String userProfileImage = dataSnapshot.child("profilbilde").getValue().toString();
HashMap postMap = new HashMap();
postMap.put("uid", currentUserID);
postMap.put("date", saveCurrentDate);
postMap.put("title", wishlist);
postMap.put("profilbilde", userProfileImage);
postMap.put("fornavn", userFirstname);
wishListRef.child(currentUserID).child(currentUserID + postRandomName).updateChildren(postMap)
.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
SendUserToMainActivity();
Toast.makeText(AddWishListActivity.this, "Ønskeliste opprettet", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(AddWishListActivity.this, "Error ocurred", Toast.LENGTH_SHORT).show();
}
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void SendUserToMainActivity() {
Intent mainIntent = new Intent(AddWishListActivity.this, MainWishActivity.class);
startActivity(mainIntent);
}
}
I have edited my question with my code.
Hope this is helpful.
I am developing a blogging app for android and I am using firebase for the backend. The app is working fine but the when I scroll down to the last post, the app crashes. I have working on finding the solution from a quite a long but couldn't possibly find any.
Here is the activity which is facing the problem
public class UserActivity extends AppCompatActivity {
private RecyclerView mStatusView;
private DatabaseReference mDatabase;
private DatabaseReference mDatabaseUsers;
private DatabaseReference mDatabaseLike;
private FirebaseAuth mFirebaseAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
String userID = "";
private Boolean exit = false;
private Boolean mProcessLike = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_main);
mFirebaseAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() == null) {
Intent loginIntent = new Intent(UserActivity.this, LoginActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(loginIntent);
}
}
};
mDatabase = FirebaseDatabase.getInstance().getReference().child("Status");
mDatabaseUsers = FirebaseDatabase.getInstance().getReference().child("Users");
mDatabaseLike = FirebaseDatabase.getInstance().getReference().child("Likes");
mDatabaseUsers.keepSynced(true);
mDatabaseLike.keepSynced(true);
mDatabase.keepSynced(true);
mStatusView = findViewById(R.id.status_list);
mStatusView.setHasFixedSize(true);
mStatusView.setLayoutManager(new LinearLayoutManager(this));
}
#Override
protected void onStart() {
super.onStart();
checkUserExists();
mFirebaseAuth.addAuthStateListener(mAuthListener);
// Creating a Firebase recycle Adapter
FirebaseRecyclerAdapter<Status, StatusViewHolder> firebaseRecyclerAdapter =
new FirebaseRecyclerAdapter<Status, StatusViewHolder>(
Status.class,
R.layout.status_row,
StatusViewHolder.class,
mDatabase
) {
#Override
protected void populateViewHolder(StatusViewHolder viewHolder, Status model, int position) {
final String postKey = getRef(position).getKey();
viewHolder.setTitle(model.getTitle());
viewHolder.setDescription((model.getDescription()));
viewHolder.setImage(getApplicationContext(), model.getImage());
viewHolder.mNumberOfLikesTextView.setVisibility(View.GONE);
viewHolder.setLikeButton(postKey);
viewHolder.mLikeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mProcessLike = true;
mDatabaseLike.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (mProcessLike) {
if (dataSnapshot.child(postKey).hasChild(mFirebaseAuth.getCurrentUser().getUid())) {
mDatabaseLike.child(postKey).child(mFirebaseAuth.getCurrentUser().getUid()).removeValue();
mProcessLike = false;
Toast.makeText(UserActivity.this, "Like removed", Toast.LENGTH_SHORT).show();
} else {
mDatabaseLike.child(postKey).child(mFirebaseAuth.getCurrentUser().getUid()).setValue("RandomValue");
mProcessLike = false;
Toast.makeText(UserActivity.this, "Liked", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
}
};
mStatusView.setAdapter(firebaseRecyclerAdapter);
}
private void checkUserExists() {
try {
userID = mFirebaseAuth.getCurrentUser().getUid();
} catch (NullPointerException e) {
e.printStackTrace();
}
mDatabaseUsers.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!dataSnapshot.hasChild(userID)) {
Intent registerIntent = new Intent(UserActivity.this,
RegisterActivity.class);
registerIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(registerIntent);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
// Setting up Recycler View
public static class StatusViewHolder extends RecyclerView.ViewHolder {
View mView;
ImageButton mLikeButton;
TextView mNumberOfLikesTextView;
DatabaseReference mDataBaseLike;
FirebaseAuth mAuth;
public StatusViewHolder(View itemView) {
super(itemView);
mView = itemView;
mLikeButton = itemView.findViewById(R.id.like_button);
mNumberOfLikesTextView = itemView.findViewById(R.id.number_of_likes_text_view);
mDataBaseLike = FirebaseDatabase.getInstance().getReference().child("Likes");
mAuth = FirebaseAuth.getInstance();
mDataBaseLike.keepSynced(true);
}
public void setLikeButton(final String postKey) {
mDataBaseLike.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.child(postKey).hasChild(mAuth.getCurrentUser().getUid())) {
mLikeButton.setImageResource(R.drawable.ic_thumb_up_blue_24dp);
} else {
mLikeButton.setImageResource(R.drawable.ic_thumb_up_black_24dp);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
// Setting the title
public void setTitle(String title) {
TextView statusTitle = mView.findViewById(R.id.status_title_textView);
statusTitle.setText(title);
}
public void setDescription(String desc) {
TextView statusDescription = mView.findViewById(R.id.status_description_textView);
statusDescription.setText(desc);
}
public void setImage(Context context, String image) {
ImageView statusImage = mView.findViewById(R.id.status_image);
Picasso.with(context).load(image).into(statusImage);
}
}
}
And here is the log for the problem I'm getting
FATAL EXCEPTION: main
Process: com.example.akash.iametderick, PID: 12384
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.Long to type com.example.akash.iametderick.Status
at com.google.android.gms.internal.zzdzr.zzb(Unknown Source:842)
at com.google.android.gms.internal.zzdzr.zza(Unknown Source:0)
at com.google.firebase.database.DataSnapshot.getValue(Unknown Source:10)
at com.firebase.ui.database.ClassSnapshotParser.parseSnapshot(ClassSnapshotParser.java:22)
at com.firebase.ui.database.ObservableSnapshotArray.getObject(ObservableSnapshotArray.java:160)
at com.firebase.ui.database.CachingObservableSnapshotArray.getObject(CachingObservableSnapshotArray.java:40)
at com.firebase.ui.database.FirebaseRecyclerAdapter.getItem(FirebaseRecyclerAdapter.java:180)
at com.firebase.ui.database.FirebaseRecyclerAdapter.onBindViewHolder(FirebaseRecyclerAdapter.java:217)
at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6482)
at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6515)
at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5458)
at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5724)
at android.support.v7.widget.GapWorker.prefetchPositionWithDeadline(GapWorker.java:285)
at android.support.v7.widget.GapWorker.flushTaskWithDeadline(GapWorker.java:342)
at android.support.v7.widget.GapWorker.flushTasksWithDeadline(GapWorker.java:358)
at android.support.v7.widget.GapWorker.prefetch(GapWorker.java:365)
at android.support.v7.widget.GapWorker.run(GapWorker.java:396)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
I've been trying to solve the problem from quite a long but couldn't find any solution.
This is my status node:
Status {
-L10rFvy6N-t7RiF7FJ6 {
date: ...;
description: ...;
image: ...;
title: ...''
}
date: ...;
description: ...;
image: ...;
title: ...''
}
The issue is with your data saved on firebase.
Your Node Status is a Object and you may have saved its value as long for that particular node in your database.
So check you database and compare it with other node . Specially the node which is having the problem will be in last as you said when I scroll down to the last pos so check your last node
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm doing a blog app, but when I run it, I have this code of crash:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.fgvelectro.f/com.fgvelectro.f.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
I've searched on the net for days, without success. I've saw other threads that talked about that problem, but nothing solved. Here it is my MainActivity:
import com.firebase.ui.database.FirebaseRecyclerAdapter;
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;
public class MainActivity extends AppCompatActivity {
private RecyclerView mBlogList;
private DatabaseReference mDatabase;
private DatabaseReference mDatabaseUsers;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if(firebaseAuth.getCurrentUser() == null){
Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(loginIntent);
}
}
};
mDatabase = FirebaseDatabase.getInstance().getReference().child("Blog");
mDatabaseUsers = FirebaseDatabase.getInstance().getReference().child("Users");
mDatabaseUsers.keepSynced(true);
mDatabase.keepSynced(true);
mBlogList = (RecyclerView) findViewById(R.id.blog_list);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
mBlogList.setHasFixedSize(true);
mBlogList.setLayoutManager(new LinearLayoutManager(this));
}
#Override
protected void onStart() {
super.onStart();
checkUserExist();
mAuth.addAuthStateListener(mAuthListener);
FirebaseRecyclerAdapter<Blog, BlogViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Blog, BlogViewHolder>(
Blog.class,
R.layout.blog_row,
BlogViewHolder.class,
mDatabase
) {
#Override
protected void populateViewHolder(BlogViewHolder viewHolder, Blog model, int position) {
viewHolder.setTitle(model.getTitle());
viewHolder.setDesc(model.getDesc());
viewHolder.setImage(getApplicationContext(), model.getImage());
}
};
mBlogList.setAdapter(firebaseRecyclerAdapter);
}
private void checkUserExist() {
final String user_id = mAuth.getCurrentUser().getUid();
mDatabaseUsers.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(!dataSnapshot.hasChild(user_id)){
Intent setupIntent = new Intent(MainActivity.this, SetupActivity.class);
setupIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(setupIntent);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public static class BlogViewHolder extends RecyclerView.ViewHolder{
View mView;
public BlogViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setTitle(String title){
TextView post_title = (TextView) mView.findViewById(R.id.post_title);
post_title.setText(title);
}
public void setDesc(String desc){
TextView post_desc = (TextView) mView.findViewById(R.id.post_desc);
post_desc.setText(desc);
}
public void setImage(Context ctx, String image){
ImageView post_image = (ImageView) mView.findViewById(R.id.post_image);
Picasso.with(ctx).load(image).into(post_image);
}
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.action_add){
startActivity(new Intent(MainActivity.this, PostActivity.class));
}
if (item.getItemId() == R.id.action_logout){
logout();
}
return super.onOptionsItemSelected(item);
}
private void logout() {
mAuth.signOut();
}
}
I know that is hard (and timewasting) to solve this problem, but if you can help me, thanks, thanks, thanks.
faby
Now my code looks like this:
private void checkUserExist() {
final String user_id = mAuth.getCurrentUser().getUid();
mDatabaseUsers.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(!dataSnapshot.hasChild(user_id)){
Intent setupIntent = new Intent(MainActivity.this, SetupActivity.class);
setupIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(setupIntent);
}
if (FirebaseAuth.getInstance().getCurrentUser() == null) {Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(loginIntent);
}
else{
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
}
}
what should I do? Is it ok?
[new edit]
Hi thanks but nothing worked. Firebase support is helping me now, I'll get you know if something will work
In your app build.gradle, add this to your dependencies
compile 'com.google.firebase:firebase-auth:11.0.4'
and in java file;
import com.google.firebase.auth.FirebaseAuth;
if (FirebaseAuth.getInstance().getCurrentUser() == null) {
//Go to login
}
else{
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
}
I am using firebase database where I am saving data manually and retrieving data in the app and that is working well but I want that when user clicks the listview item that must open another activity and within that must retrieve another table.
Here is below my code
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private ProgressDialog progressDialog;
DatabaseReference mref =
FirebaseDatabase.getInstance().getReference("users");
ListView mlistview;
ArrayList<String> arrayList=new ArrayList<>();
ArrayAdapter<String> arrayAdapter;
private BottomNavigationView.OnNavigationItemSelectedListener
mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
progressDialog.show();
startActivity(new
Intent(profilemain.this,profilemain.class));
return true;
case R.id.navigation_dashboard:
Toast.makeText(profilemain.this,"hi
hello",Toast.LENGTH_SHORT).show();
return true;
case R.id.navigation_notifications:
Toast.makeText(profilemain.this,"hi
hello",Toast.LENGTH_SHORT).show();
return true;
case R.id.navigation_signout:
Toast.makeText(profilemain.this,"You have successfully
Signed out",Toast.LENGTH_SHORT).show();
mAuth.signOut();
return true;
}
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profilemain);
progressDialog.setMessage("loading");
progressDialog.setTitle("database is");
mlistview=(ListView) findViewById(R.id.listview);
Firebase.setAndroidContext(this);
DatabaseReference ref = FirebaseDatabase.getInstance()
.getReference("users");
//mref=new Firebase("https://stark-1dffd.firebaseio.com/users");
arrayAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,arrayList);
mlistview.setAdapter(arrayAdapter);
mref.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String value= dataSnapshot.getValue(String.class);
arrayList.add(value);
arrayAdapter.notifyDataSetChanged();
//
//
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser()==null){
startActivity(new
Intent(profilemain.this,MainActivity.class));
}
}
};
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
add an ItemClickListener on your ListView
mlistview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent in = new Intent(MyActivity.this, DetailActivity.class);
in.putExtra("data", arrayList.get(position);// add the selected String from the ListView
startActivity(in);
}
});
and read the data from the other activity:
String data = getIntent().getStringExtra("data");