In showdata method witch load FirebaseUser info I have null value for uInfo , I run the app and signed in with User_02 , debugging show that :
ds.getChild(userId ) reach to the right user who signed in and loaded with right key , but when try to get value from UserInformations.class gives me NullPointerException ,so what the mistake in the coade ?
I not that ds have key and value for User_01 . is that normal ?
public class AddToDatabase extends AppCompatActivity {
private static final String TAG = "AddToDatabase";
private ListView userInfolist ;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
String userId;
UserInformations uInfo =new UserInformations();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_to_database);
userInfolist = (ListView) findViewById(R.id.userInfolist);
mAuth = FirebaseAuth.getInstance();
FirebaseDatabase mFirebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference myRef = mFirebaseDatabase.getReference();
FirebaseUser user = mAuth.getCurrentUser();
userId = user.getUid();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
toastMassege(" You are successfly signed in with " + user.getEmail());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
toastMassege(" You are successfly signed out ");
}
}
};
// Read from the database
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
showData(dataSnapshot);
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
}
});
}
private void showData(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()){
uInfo.setName(ds.child(userId).getValue(UserInformations.class).getName()); // set the name
uInfo.setEmail(ds.child(userId).getValue(UserInformations.class).getEmail()); // set the Email
uInfo.setPhone_num(ds.child(userId).getValue(UserInformations.class).getPhone_num()); // set the PhonNum
ArrayList<String> arrayList =new ArrayList<>();
arrayList.add(uInfo.getName());
arrayList.add(uInfo.getEmail());
arrayList.add(uInfo.getPhone_num());
ArrayAdapter<String> adapter =new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,arrayList);
userInfolist.setAdapter(adapter);
}
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
private void toastMassege(String massege) {
Toast.makeText(this, massege, Toast.LENGTH_SHORT).show();
}
}
UserInformation.java
class UserInformations {
private String Email,Name,Phone_num ;
UserInformations() {
}
String getEmail() {
return Email;
}
void setEmail(String email) {
this.Email = email;
}
public String getName() {
return Name;
}
public void setName(String name) {
this.Name = name;
}
String getPhone_num() {
return Phone_num;
}
void setPhone_num(String phone_num) {
this.Phone_num = phone_num;
}
}
First, change your variables in UserInformations from private to public.
class UserInformations {
public String Email,Name,Phone_num ;
}
Second, you have to change your Firebase path from Phone number to Phone_num. Why? Well, that's because you are declaring String Phone_num inside the UserInformation.
Your current JSON:
{
"uid001": {
"Email": "user01#gmail.com",
"Name": "user01",
"Phone number": "0123456789"
},
"uid002": {
"Email": "user02#gmail.com",
"Name": "user02",
"Phone number": "0123456789"
},
}
Changed to below JSON:
{
"uid001": {
"Email": "user01#gmail.com",
"Name": "user01",
"Phone_num": "0123456789"
},
"uid002": {
"Email": "user02#gmail.com",
"Name": "user02",
"Phone_num": "0123456789"
},
}
When you used for(DataSnapshot ds : dataSnapshot.getChildren()) the ds already have the data of the child which is the user node no need for child(userId) do it directly :
uInfo.setName(ds.child("name").getValue());
uInfo.setEmail(ds.child("email").getValue());
uInfo.setPhone_num(ds.child("phone_num").getValue());
Related
Here is my data structure.
"Posts" : {
"-MpVVpVIqmn0Iu78hDRp" : {
"description" : "",
"picture" : "",
"postKey" : "",
"reports" : 0,
"timeStamp" : 1638001760487,
"title" : "",
"userId" : "",
"userPhoto" : ""
},
"-MpVcioadtvRBRaa0n96" : {
"description" : "",
"picture" : "",
"postKey" : "",
"reports" : 0,
"timeStamp" : 1638003830234,
"title" : "",
"userId" : "",
"userPhoto" : ""
},
I want to access the "reports" part. So I use
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
rootRef.child("Posts").child("reports").setValue(1);
But It creates reports value 1 right below Posts not below "-MpVVpVIqmn0Iu78hDRp" this.
I want to increment the report. But I don't know how can I approach to reports node.
Here is my full code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post_detail);
imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
et = (EditText)findViewById(R.id.post_detail_comment);
// let's set the statue bar to transparent
// ini Views
RvComment = findViewById(R.id.rv_comment);
imgPost =findViewById(R.id.post_detail_img);
imgUserPost = findViewById(R.id.post_detail_user_img);
imgCurrentUser = findViewById(R.id.post_detail_currentuser_img);
txtPostTitle = findViewById(R.id.post_detail_title);
txtPostDesc = findViewById(R.id.post_detail_desc);
txtPostDateName = findViewById(R.id.post_detail_date_name);
editTextComment = findViewById(R.id.post_detail_comment);
btnAddComment = findViewById(R.id.post_detail_add_comment_btn);
btnDeletePost = findViewById(R.id.button_delete);
btnnoti = findViewById(R.id.button_noti);
btncommentnoti = findViewById(R.id.comment_noti);
firebaseAuth = FirebaseAuth.getInstance();
firebaseUser = firebaseAuth.getCurrentUser();
firebaseDatabase = FirebaseDatabase.getInstance();
// add post delete button
mDatabase= FirebaseDatabase.getInstance().getReference();
myUid = FirebaseAuth.getInstance().getCurrentUser().getUid();
//게시글 신고기능
btnnoti.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
rootRef.child("Posts").child("reports").setValue(1);
}
});
btnDeletePost.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//여기 수정 주의 UId.equals(myUid)
if (true){
Toast.makeText(PostDetailActivity.this,"삭제중...",Toast.LENGTH_SHORT).show();
beginDelete();
onBackPressed();
}
}
});
// add Comment button click listener
btnAddComment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
btnAddComment.setVisibility(View.INVISIBLE);
DatabaseReference commentReference = firebaseDatabase.getReference(COMMENT_KEY).child(PostKey).push();
String comment_content = editTextComment.getText().toString();
String uid = firebaseUser.getUid();
String uname = firebaseUser.getDisplayName();
if (firebaseUser.getPhotoUrl()!=null){
String uimg = firebaseUser.getPhotoUrl().toString();
Comment comment = new Comment(comment_content,uid,uimg,uname);
commentReference.setValue(comment).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
showMessage("댓글이 등록되었습니다.");
editTextComment.setText("");
btnAddComment.setVisibility(View.VISIBLE);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
showMessage("fail to add comment : "+e.getMessage());
}
});
}
else{
String usphoto =Integer.toString(R.drawable.userphoto);
Comment comment = new Comment(comment_content,uid,usphoto,uname);
commentReference.setValue(comment).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
showMessage("comment added");
editTextComment.setText("");
btnAddComment.setVisibility(View.VISIBLE);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
showMessage("fail to add comment : "+e.getMessage());
}
});
}
}
});
// now we need to bind all data into those views
// first we need to get post data
// we need to send post detail data to this activity first ...
// now we can get post data
// 게시글 사진 백지 케이스
postImage = getIntent().getExtras().getString("postImage") ;
if(postImage!=null){
Glide.with(this).load(postImage).into(imgPost);
}
else{
Glide.with(this).load(R.drawable.whitepaper).into(imgPost);
}
String postTitle = getIntent().getExtras().getString("title");
txtPostTitle.setText(postTitle);
String userpostImage = getIntent().getExtras().getString("userPhoto");
if (userpostImage!=null){
Glide.with(this).load(userpostImage).into(imgUserPost);
}
else {
Glide.with(this).load(R.drawable.userphoto).into(imgUserPost);
}
String postDescription = getIntent().getExtras().getString("description");
txtPostDesc.setText(postDescription);
// set comment user image
if (firebaseUser.getPhotoUrl()!=null){
Glide.with(this).load(firebaseUser.getPhotoUrl()).into(imgCurrentUser);
}
else{
Glide.with(this).load(R.drawable.userphoto).into(imgCurrentUser);
}
// get post key
PostKey = getIntent().getExtras().getString("postKey");
String date = timestampToString(getIntent().getExtras().getLong("postDate"));
txtPostDateName.setText(date);
// get post uid
UId = getIntent().getExtras().getString("userId");
// ini Recyclerview Comment
iniRvComment();
}
private void beginDelete() {
//서버 관리용 개발자 옵션
if (myUid.equals("k1kn0JF5idhrMzuw46GarEIBgPw2")) {
long tlong = System.currentTimeMillis(); long ttime;
ttime = tlong - 3*24*60*60*1000;
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
Query queryByTimestamp = db.child("Posts").orderByChild("timeStamp").endAt(ttime);
queryByTimestamp.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
for (DataSnapshot ds : task.getResult().getChildren()) {
ds.getRef().removeValue();
Toast.makeText(PostDetailActivity.this,"게시글이 삭제되었습니다.",Toast.LENGTH_SHORT).show();
}
} else {
Log.d("TAG", task.getException().getMessage());
Toast.makeText(PostDetailActivity.this,"게시글이 삭제되지않았습니다.",Toast.LENGTH_SHORT).show();
}
}
});
}
else if (UId.equals(myUid)) {
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
Query queryByTimestamp = db.child("Posts").orderByChild("postKey").equalTo(PostKey);
queryByTimestamp.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
for (DataSnapshot ds : task.getResult().getChildren()) {
ds.getRef().removeValue();
Toast.makeText(PostDetailActivity.this, "게시글이 삭제되었습니다.", Toast.LENGTH_SHORT).show();
}
} else {
Log.d("TAG", task.getException().getMessage());
Toast.makeText(PostDetailActivity.this, "게시글이 삭제되지않았습니다.", Toast.LENGTH_SHORT).show();
}
}
});
}
else{
Toast.makeText(PostDetailActivity.this,"다른 사용자의 게시글입니다.",Toast.LENGTH_SHORT).show();
}
}
public void linearOnClick(View v) {
imm.hideSoftInputFromWindow(et.getWindowToken(), 0);
}
private void iniRvComment() {
RvComment.setLayoutManager(new LinearLayoutManager(this));
DatabaseReference commentRef = firebaseDatabase.getReference(COMMENT_KEY).child(PostKey);
commentRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
listComment = new ArrayList<>();
for (DataSnapshot snap:dataSnapshot.getChildren()) {
Comment comment = snap.getValue(Comment.class);
listComment.add(comment) ;
}
commentAdapter = new CommentAdapter(getApplicationContext(),listComment);
RvComment.setAdapter(commentAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void showMessage(String message) {
Toast.makeText(this,message,Toast.LENGTH_LONG).show();
}
private String timestampToString(long time) {
Calendar calendar = Calendar.getInstance(Locale.ENGLISH);
calendar.setTimeInMillis(time);
String date = DateFormat.format("yyyy-MM-dd",calendar).toString();
return date;
}
}
This is the part of my question
btnnoti.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
rootRef.child("Posts").child("reports").setValue(1);
}
});
I also tried orderbychild but I think it is not the right code.
This code:
rootRef.child("Posts").child("reports").setValue(1);
You're telling the database to set the value of /Posts/reports to 1, which is precisely what it then does.
If you want increment the current value of a node, you can use the atomic increment operation:
rootRef.child("Posts").child("reports").setValue(ServerValue.increment(1));
If you want to increment the reports property of a specific node under Posts, you will need to know the key of that node. For example:
rootRef.child("Posts/-MpVVpVIqmn0Iu78hDRp/reports").setValue(ServerValue.increment(1));
If you don't know the key of the node to increment, but do know some other value that uniquely (enough) identifies the node(s) to update, you can use a query to find the keys.
For example, to update all nodes with a specific postKey:
Query query = rootRef.child("Posts").orderByChild("postKey").equalTo("thePostKeyValue");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
postSnapshot.getReference().child("reports").setValue(ServerValue.increment(1));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
}
I have an activity where i want to send a custom message to a sub-group in my database when a button is clicked. I tried to check for a user_id and send the message to those user id's, My problem is that when i click the button(status) it only sends that message to one person.
This is my Activity:
public class messageActivity extends AppCompatActivity {
private Button status;
private DatabaseReference mRootRef;
private String mCurrentUserId;
private String userName;
private String user_id;
private String message;
private FirebaseAuth mAuth;
private DatabaseReference mUserRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
FirebaseApp.initializeApp(this);
mRootRef = FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
gettingIntent();
status = (Button)findViewById(R.id.rescue);
status.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
addUpdateMessage();
addTeamUpdateChat();
Toast.makeText(getApplicationContext(), "Team Update message was successfully sent",Toast.LENGTH_LONG).show();
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Status");
toolbar.setTitleTextColor(android.graphics.Color.WHITE);
if (mAuth.getCurrentUser() != null) {
mUserRef = FirebaseDatabase.getInstance().getReference().child("Users").child(mAuth.getCurrentUser().getUid());
mUserRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
userName = dataSnapshot.child("name").getValue().toString();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void checkUser() {
if (mCurrentUserId == null) {
sendToStart();
}else{
Toast.makeText(getApplicationContext(), "Logged in",Toast.LENGTH_SHORT).show();
}
}
private void gettingIntent() {
Intent intent =getIntent();
user_id = intent.getStringExtra("user_id");
}
private void addTeamUpdateChat() {
String current_user_ref="Team_Updates/"+mCurrentUserId+"/"+user_id;
String reciever_user_ref= "Team_Updates/"+user_id+"/"+mCurrentUserId;
DatabaseReference team_push_key = mRootRef.child("Emergency_Messages").child(mCurrentUserId).child(user_id).push();
String push_key = team_push_key.getKey();
Map messageMap = new HashMap();
messageMap.put("userName", userName + " Is now a new Member of the team.");
messageMap.put("type","text");
messageMap.put("from",mCurrentUserId);
messageMap.put("seen",false);
messageMap.put("time", ServerValue.TIMESTAMP);
Map messageUserMap = new HashMap();
messageUserMap.put(current_user_ref+ "/"+push_key,messageMap);
messageUserMap.put(reciever_user_ref+ "/"+push_key,messageMap);
mRootRef.updateChildren(messageUserMap, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if(databaseError!=null){
Log.d("TAG",databaseError.getMessage().toString());
}
}
});
}
private void addUpdateMessage() {
mRootRef.child("Team_Updates_Chat").child(mCurrentUserId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(!dataSnapshot.hasChild(user_id)){
Map chatAddMap = new HashMap();
chatAddMap.put("seen",false);
chatAddMap.put("timestamp", ServerValue.TIMESTAMP);
Map chatUserMap = new HashMap();
chatUserMap.put("Team_Updates_Chat/"+mCurrentUserId+"/"+user_id, chatAddMap);
chatUserMap.put("Team_Updates_Chat/"+user_id+"/"+mCurrentUserId, chatAddMap);
mRootRef.updateChildren(chatUserMap, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if(databaseError!= null){
Toast.makeText(MenuActivity.this, "Error: "+databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
if(currentUser == null){
sendToStart();
} else{
mCurrentUserId = mAuth.getCurrentUser().getUid();
}
}
#Override
protected void onStop() {
super.onStop();
}
private void sendToStart() {
Intent startIntent = new Intent(messageActivity.this, Home.class);
startActivity(startIntent);
finish();
}
}
I'm Still learning Programming in Android Studio, Is there Any suggestions on how i should approach this?
You are sending a message only to single user because you are getting only a single user. To send a message to multiple users, you need to loop to get all those users and then send the message to all of them.
In showdata method witch load FirebaseUser info when I run the app and signed in with any user , arrayList in the method is always loaded with User_03 info ,
debugging show that:
DataSnapshot ds is loaded with right value of signed in user ( right key and info ) .
uInfo ( the object which carry signed in user info) loaded with right data from database .
uInfo.setName(ds.getValue(UserInformations.class).getName()); = undefined .
I think there is something wrong in arryList size .
the attached screen shot I take it when arrive to breakpoint in line : toastMassege("it's Done") .
public class AddToDatabase extends AppCompatActivity {
private static final String TAG = "AddToDatabase";
private ListView userInfolist ;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
String userId;
UserInformations uInfo =new UserInformations();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_to_database);
userInfolist = (ListView) findViewById(R.id.userInfolist);
mAuth = FirebaseAuth.getInstance();
FirebaseDatabase mFirebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference myRef = mFirebaseDatabase.getReference();
FirebaseUser user = mAuth.getCurrentUser();
userId = user.getUid();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
toastMassege(" You are successfly signed in with " +
user.getEmail());
} else {
Log.d(TAG, "onAuthStateChanged:signed_out");
toastMassege(" You are successfly signed out ");
}
}
};
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
showData(dataSnapshot);
}
#Override
public void onCancelled(DatabaseError error) {
}
});
}
private void showData(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()){
uInfo.setName(ds.getValue(UserInformations.class).getName());
uInfo.setEmail(ds.getValue(UserInformations.class).getEmail());
uInfo.setPhone_num(ds.getValue(UserInformations.class).getPhone_num());
ArrayList<String> arrayList=new ArrayList<>();
int listSize = arrayList.size();
arrayList.add(uInfo.getName());
arrayList.add(uInfo.getEmail());
arrayList.add(uInfo.getPhone_num());
ArrayAdapter<String> adapter =new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,arrayList);
userInfolist.setAdapter(adapter);
toastMassege("its Done ");
}
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
private void toastMassege(String massege) {
Toast.makeText(this, massege, Toast.LENGTH_SHORT).show();
}
}
this is class UserInformations
class UserInformations {
public String email,name,phone_num ;
UserInformations() {
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone_num() {
return phone_num;
}
public void setPhone_num(String phone_num) {
this.phone_num = phone_num;
}
}
This is happening because you are have declared the ArrayList<String> arrayList=new ArrayList<>(); inside the for loop. This means that you are creating a new instance of ArrayList class every time you iterate.
In order to solve this, just move the decration outside for loop like this:
private void showData(DataSnapshot dataSnapshot) {
ArrayList<String> arrayList=new ArrayList<>(); //Moved outside
for(DataSnapshot ds : dataSnapshot.getChildren()){
uInfo.setName(ds.getValue(UserInformations.class).getName());
uInfo.setEmail(ds.getValue(UserInformations.class).getEmail());
uInfo.setPhone_num(ds.getValue(UserInformations.class).getPhone_num());
int listSize = arrayList.size();
arrayList.add(uInfo.getName());
arrayList.add(uInfo.getEmail());
arrayList.add(uInfo.getPhone_num());
ArrayAdapter<String> adapter =new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,arrayList);
userInfolist.setAdapter(adapter);
toastMassege("its Done ");
}
}
I receive FirebaseUser Id & email how signed in correctly as shown in debug screenshot , but DataSnapshot ds is always loaded with user_01 info , I tried hard to solve this problem and found Similar questions on the site but couldn't help . so can anyone help to solve this ?
public class AddToDatabase extends AppCompatActivity {
private static final String TAG = "AddToDatabase";
private ListView userInfolist;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
String userId;
UserInformations uInfo = new UserInformations();
DatabaseReference myRef;
FirebaseDatabase mFirebaseDatabase;
FirebaseUser user;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_to_database);
userInfolist = (ListView) findViewById(R.id.userInfolist);
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = mFirebaseDatabase.getReference();
user = mAuth.getCurrentUser();
userId = user.getUid();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
toastMassege(" You are successfly signed in with " + user.getEmail());
} else {
Log.d(TAG, "onAuthStateChanged:signed_out");
toastMassege(" You are successfly signed out ");
}
}
};
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
showData(dataSnapshot);
}
#Override
public void onCancelled(DatabaseError error) {
}
});
}
Boolean signedstate = true;
private void showData(DataSnapshot dataSnapshot) {
ArrayList<String> arrayList = new ArrayList<>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
if (signedstate) {
uInfo.setName(ds.getValue(UserInformations.class).getName());
uInfo.setEmail(ds.getValue(UserInformations.class).getEmail());
uInfo.setPhone_num(ds.getValue(UserInformations.class).getPhone_num());
arrayList.add(uInfo.getName());
arrayList.add(uInfo.getEmail());
arrayList.add(uInfo.getPhone_num());
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, arrayList);
userInfolist.setAdapter(adapter);
toastMassege("its Done ");
signedstate = false;
}
}
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
private void toastMassege(String massege) {
Toast.makeText(this, massege, Toast.LENGTH_SHORT).show();
}
}
this is class UserInformations :
class UserInformations {
public String email,name,phone_num ;
UserInformations() {
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone_num() {
return phone_num;
}
public void setPhone_num(String phone_num) {
this.phone_num = phone_num;
}
}
Your problem is that you are creating the adapter inside the for loop. In order to solve your problm, you need to move this line:
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, arrayList);
outside the for loop because you are creating a new instance of ArrayAdapter every time you iterate. Please use the following code:
private void showData(DataSnapshot dataSnapshot) {
ArrayList<String> arrayList = new ArrayList<>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
if (signedstate) {
uInfo.setName(ds.getValue(UserInformations.class).getName());
uInfo.setEmail(ds.getValue(UserInformations.class).getEmail());
uInfo.setPhone_num(ds.getValue(UserInformations.class).getPhone_num());
arrayList.add(uInfo.getName());
arrayList.add(uInfo.getEmail());
arrayList.add(uInfo.getPhone_num());
signedstate = false;
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, arrayList);
userInfolist.setAdapter(adapter);
toastMassege("its Done ");
}
I have a class to read data from my database but it always returns null.
Here's the java file
public class UserActivity extends AppCompatActivity {
TextView textView;
private FirebaseDatabase mFirebaseDatabase;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private DatabaseReference myRef;
private String userID;
private String TAG = "hifiwi";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user);
textView = (TextView) findViewById(R.id.textView);
//////////////////////////////////////////////////////////////
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = mFirebaseDatabase.getReference();
FirebaseUser user = mAuth.getCurrentUser();
userID = user.getUid();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = mAuth.getCurrentUser();
if (user != null) {
Toast.makeText(UserActivity.this, "Signed in with " + user.getEmail(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(UserActivity.this, "Successfully signed out...", Toast.LENGTH_SHORT).show();
}
}
};
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
showData(dataSnapshot);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
///////////////////////////////////////////////////////////////
}
private void showData(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
UserInformation uInfo = new UserInformation();
uInfo.setEmail(ds.child(userID).getValue(UserInformation.class).getEmail());
uInfo.setName(ds.child(userID).getValue(UserInformation.class).getName());
uInfo.setPassword(ds.child(userID).getValue(UserInformation.class).getPassword());
uInfo.setPhoneno(ds.child(userID).getValue(UserInformation.class).getPhoneno());
Log.i(TAG, " " + uInfo.getEmail()); //Always returning null
Log.i(TAG, " " + uInfo.getName()); //Always returning null
Log.i(TAG, " " + uInfo.getPassword()); //Always returning null
Log.i(TAG, " " + uInfo.getPhoneno()); //Always returning null
}
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
protected void onStop() {
super.onStop();
mAuth.removeAuthStateListener(mAuthListener);
}
}
The log statements always return null.
This is my database structure under t2-login(the project name).
{
"Users" : {
"8dQ8unnqQXa69nkxUFKrcgiTM3S2" : {
"emailuser" : "sam#gmail.com",
"mobileUser" : "1234567899",
"nameuser" : "sam",
"passworduser" : "sammypp"
},
"DIMBAk4CHZdWGbxN9kPESwIrw9b2" : {
"emailuser" : "hsjsjsjjsjsj#mdm.mdmdmdmndn",
"mobileUser" : "9999999999",
"nameuser" : "hshs",
"passworduser" : "ppppppl"
},
"YJhf16ZyfWUn1Dou3BPcIkSSmVm1" : {
"emailuser" : "test2#gmail.com",
"mobileUser" : "1234567892",
"nameuser" : "test2",
"passworduser" : "test2pp"
},
"yQEFEe5x06hvSZP18Mmb6OfNqnB2" : {
"emailuser" : "test1#gmail.com",
"mobileUser" : "1234567891",
"nameuser" : "test1",
"passworduser" : "test1pp"
}
}
}
The UserInformation.class
package com.rishav.t2;
/**
* Created by rishav on 6/27/2017.
*/
public class UserInformation {
private String email;
private String name;
private String phoneno;
private String password;
public UserInformation() {
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoneno() {
return phoneno;
}
public void setPhoneno(String phoneno) {
this.phoneno = phoneno;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Set myRef to: myRef = FirebaseDatabase.getInstance().getReference("Users").child(user.getUid());
Also change this:
private void showData(DataSnapshot dataSnapshot) {
UserInformation uInfo = ds.getValue(UserInformation.class);
Log.i(TAG, " " + uInfo.getEmail()); //Always returning null
Log.i(TAG, " " + uInfo.getName()); //Always returning null
Log.i(TAG, " " + uInfo.getPassword()); //Always returning null
Log.i(TAG, " " + uInfo.getPhoneno()); //Always returning null
}
Have UserInformation class variables match the key names that exist in the firebase database:
public class UserInformation {
public String emailuser;
public String nameuser;
public String mobileUser;
public String passworduser;
public UserInformation() {
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoneno() {
return phoneno;
}
public void setPhoneno(String phoneno) {
this.phoneno = phoneno;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Have you checked the rule of your firebase project setting
Firebase rules provides a way to identify user role while performing read and write operations. These rules will acts a security layer on the server before perform any CRUD operation. By default the rules allows user to perform read & write operation only after authentication.
The below rules allow authenticated users only to read or write data.
{
"rules": {
".read": "auth != null",
".write": "auth != null"
}
}
Below rules allows everyone to read & write data without authentication.
{
"rules": {
".read": true,
".write": true
}
}
You can also use these rules to validate data before inserting into database. For example below rules validates the name to be less than 50 chars and email to be valid using email regular expression.
{
"rules": {
".read": true,
".write": true,
"users": {
"$user": {
"name": {
".validate": "newData.isString() && newData.val().length < 50"
},
"email": {
".validate": "newData.isString() && newData.val().matches(/^[A-Z0-9._%+-]+#[A-Z0-9.-]+\\.[A-Z]{2,4}$/i)"
}
}
}
}
}
For detailed tutorial check this link
try this
myRef.child("Users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
showData(dataSnapshot);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Try this way
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("users");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
userList = new ArrayList<User>();
dataSnapshot.getChildrenCount();
//List<User> list= new ArrayList<User>();
for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
User user = childDataSnapshot.getValue(User.class);
userList.add(user);
}
Log.e("hello","childDataSnapshot"+ userList.size());
adapter.update(userList);
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w("MY", "Failed to read value.", error.toException());
}
});