How can I set the value from Firebase in EditText? - android

How to set value (name) in EditText?
"users": [
"-KTYWvZG4Qn9ZYTc47O6" : {
"name" : "my name"
}
}
I did it but
package **.****;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.EditText;
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 ****.****.m_Model.Update_user1;
public class Update_a extends AppCompatActivity {
private EditText name111;
private DatabaseReference mFirebaseDatabase;
private FirebaseDatabase mFirebaseInstance;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.Update__activity);
myname111 = (EditText) findViewById(R.id.editext2);
mFirebaseInstance = FirebaseDatabase.getInstance();
mFirebaseDatabase = mFirebaseInstance.getReference("users");
String userId = mFirebaseDatabase.push().getKey();
mFirebaseDatabase.child(userId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Update_user1 model = dataSnapshot.getValue(Update_user1.class);
myname111.setText(model.getname());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Update_user1.class
package **.****.m_Model;
public class Update_user1 {
public String name;
public Update_user1() {
}
public Update_user1(String name) {
this.name = name;
}
public String getname() {
return name;
}
But this not work
E/AndroidRuntime: FATAL EXCEPTION: main Process: *.******, PID:
14980 java.lang.NullPointerException: Attempt to invoke virtual
method java.lang.String ..m_Model.Update_user1.getname() on a
null object reference
at *.********.Update_u$1.onDataChange(Update_u.java:61)

When you run this line:
String userId = mFirebaseDatabase.push().getKey();
You generate a new so-called push ID. Next you attach a listener to a location based on this freshly created push ID.
mFirebaseDatabase.child(userId).addValueEventListener(new ValueEventListener() {
...
Since push IDs are statistically guaranteed to be unique, no value will exist at this location yet.
This means that onDataChange() will fire with an empty DataSnapshot:
public void onDataChange(DataSnapshot dataSnapshot) {
Update_user1 model = dataSnapshot.getValue(Update_user1.class);
myname111.setText(model.getname());
}
Since the DataSnapshot is empty, getValue() will not be able to get a Update_user1 and thus it will return null. And that leads to model.getname() calling getname() on a null object and thus throwing a NullPointerException.
The simplest way to handle the null is:
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Update_user1 model = dataSnapshot.getValue(Update_user1.class);
myname111.setText(model.getname());
}
}

the answer of frank is right as you really want to get the value of id doesn't exist yet and you must make the listener on the key that have the values so you don't have to know the hashkey of it
so you can make as follow
mFirebaseDatabase.getReference("users")
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
Update_user1 model = dataSnapshot.getValue(Update_user1.class);
myname111.setText(model.getname());
}
#Override
public void onCancelled(DatabaseError databaseError) {
// TODO
}
});

Related

What makes NullpointException in my code? [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 3 years ago.
I don't know what make problem that show follower follow list,
it was working but after few days later (maybe there is possbility i touch something...) it didn't working
what makes it error NullPointerException?
This is my Error
2019-06-17 11:53:31.158 8298-8298/com.example.blogapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.blogapp, PID: 8298
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
at com.example.together.Activities.FollowersActivity$5.onDataChange(FollowersActivity.java:157)
at com.google.firebase.database.Query$1.onDataChange(com.google.firebase:firebase-database##17.0.0:184)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database##17.0.0:75)
at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database##17.0.0:63)
at com.google.firebase.database.core.view.
Nothing showing redline ... just null point
This is my btn that i clicked*
followers.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), FollowersActivity.class);
intent.putExtra("id", profileid);
intent.putExtra("title","followers");
startActivity(intent);
}
});
following.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), FollowersActivity.class);
intent.putExtra("id", profileid);
intent.putExtra("title","following");
startActivity(intent);
}
});
This is my FollowersActivity
package com.example.together.Activities;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import com.example.together.Adapter.UserAdapter;
import com.example.together.Model.User;
import com.example.together.R;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class FollowersActivity extends AppCompatActivity {
String id;
String title;
List<String> idList;
RecyclerView recyclerView;
UserAdapter userAdapter;
List<User> userList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_followers);
Intent intent = getIntent();
id = intent.getStringExtra("id");
title = intent.getStringExtra("title");
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
recyclerView = findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
userList = new ArrayList<>();
userAdapter = new UserAdapter(this, userList, false);
recyclerView.setAdapter(userAdapter);
idList = new ArrayList<>();
switch (title){
case "likes":
getLikes();
break;
case "following":
getFollowing();
break;
case "followers":
getFollowers();
break;
}
}
private void getLikes() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Likes")
.child(id);
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
idList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
idList.add(snapshot.getKey());
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void getFollowing(){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Follow")
.child(id).child("following");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
idList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
idList.add(snapshot.getKey());
}
showUsers();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void getFollowers(){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Follow")
.child(id).child("followers");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
idList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
idList.add(snapshot.getKey());
}
showUsers();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void showUsers(){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
userList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
User user = snapshot.getValue(User.class);
for (String id : idList){
if (user.getId().equals(id)){
userList.add(user);
}
}
}
userAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
The user object is null and you are trying to retrieve data from null object
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
userList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
User user = snapshot.getValue(User.class);
// check user exists or not.. here user gets null
if(user!=null){
for (String id : idList){
if (user.getId().equals(id)){
userList.add(user);
}
}}
}
Check a profileid on first activity.
intent.putExtra("id", profileid);
and make sure print a log here is you get a value of profileid

Retrieving data from Firebase database is returning null

My app is saving users in my firebase database, but when I try to read the value of the object it always returns null. The rules of my firebase are all set true and the app is saving the users properly. I don't know why I can't read the data and why it always returns null. This is my MainActivity class:
package com.example.leo_o.testfirebase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class MainActivity extends AppCompatActivity implements
View.OnClickListener {
private Button saveButton;
private EditText nameEditText;
private DatabaseReference mDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDatabase = FirebaseDatabase.getInstance().getReference("users");
saveButton = (Button) findViewById(R.id.saveButton);
nameEditText = (EditText) findViewById(R.id.nameEditText);
}
private void saveUser(String name) {
User user = new User(name);
String userId = mDatabase.push().getKey();
mDatabase.child(userId).setValue(user);
}
public void getData() {
ValueEventListener userListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
String name = user.getName();
if (name == null) {
Toast.makeText(MainActivity.this, "Null value", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
mDatabase.addValueEventListener(userListener);
}
#Override
public void onClick(View view) {
if (view == saveButton) {
String name = nameEditText.getText().toString();
saveUser(name);
getData();
}
}
}
An this is my User class:
package com.example.leo_o.testfirebase;
public class User {
public String name;
public User() {
}
public User(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Does anyone know what is wrong with my code and why it always returns null?
Your mDatabase points to the "users" node in firebase so the value that you are getting in "onDataChange" is a list of users and not a single user.
See how you are setting the value: mDatabase.child(userId).setValue()
You need to do the same if you just want to get the details of a single user. Attach the value event to a userId node.
Alternatively, you can also use a child event listener on mDatabase.

Stuck with this issue of eventlistener with list

Have been trying to solve this problem for so long
I have a list called datalist in which I am storing data from firebase in order to use it in the recyclerview.
But the problem is inside childeventlistener the list is getting updated but before this happens return call is made and it ends up in a null list.
What should be done?
package com.example.dell.hungryapp;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
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 java.util.List;
/**
* Created by Dell on 5/29/2017.
*/
public class itemmodel {
public String item_name;
public int quantity;
public String getItem_name() {
return item_name;
}
public void setItem_name(String item_name) {
this.item_name = item_name;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public static List<itemmodel> getObjectList(){
final List<itemmodel> datalist=new ArrayList<>();
DatabaseReference databaseReference= FirebaseDatabase.getInstance().getReference();
FirebaseUser user= FirebaseAuth.getInstance().getCurrentUser();
databaseReference.child("Users").child(user.getUid()).child("Inventory").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
System.out.println("value is : "+dataSnapshot.getValue());
String id=dataSnapshot.getKey();
Integer qty=dataSnapshot.getValue(Integer.class);
itemmodel item=new itemmodel();
item.setItem_name(id);
item.setQuantity(qty);
datalist.add(item);
System.out.println("before size : "+datalist.size());
}
#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) {
}
});
System.out.println("before size : "+datalist.size());
return datalist;
}
}
Kindly follow this link if you want to retrieve the whole data from inventory. I have used maps in order to retrieve the whole data and stored it in array list
final DatabaseReference myRef = database.getReference().child("users").child(users.getUid).child("Inventory");
Remove the previous markers as the location updates
Hope it solves your problem

Firebase database not retrieving data W/ClassMapper: No setter/field for -KeAi52QSaiuf7p5jEYM found on class

Database
"userinformation": [
"-KeAi52QSaiuf7p5jEYM" : {
"website" : "test1"
"username" : "test1"
}
}
Class myprofile not retrieving data
package **.****;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import android.view.Menu;
import android.view.MenuItem;
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 ****.****.m_Model.useri1;
public class myprofile extends AppCompatActivity {
private TextView myusername111;
private DatabaseReference mFirebaseDatabase;
private FirebaseDatabase mFirebaseInstance;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myprofile__activity);
myusername111 = (TextView) findViewById(R.id.textview22);
mFirebaseInstance = FirebaseDatabase.getInstance();
mFirebaseInstance.getReference("userinformation").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
useri1 model = dataSnapshot.getValue(useri1.class);
myusername111.setText(model.getusername());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
class edit_profile
package package ***.****;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import ***.***.m_Model.useri1;
public class edit_profile extends AppCompatActivity {
private Toolbar toolbar;
private EditText website;
private EditText username;
private Button bsubmit;
private DatabaseReference mFirebaseDatabase;
private FirebaseDatabase mFirebaseInstance;
private android.view.ViewGroup parent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
mFirebaseInstance = FirebaseDatabase.getInstance();
mFirebaseDatabase = mFirebaseInstance.getReference("users");
usernamr = (EditText) findViewById(R.id.usernamr);
website = (EditText) findViewById(R.id.website);
Button bsubmit = (Button) findViewById(R.id.b_submit);
bsubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!isEmpty(website, username) && !isEmpty(website, username)) {
mNewprofile("53", website.getText().toString().trim(), username.getText().toString().trim());
finish();
startActivity(new Intent(getApplicationContext(), myprofile.class));
}
}
} );
}
private void mNewprofile(String s, String username, String website) {
new_profile1 userinformation1 = new new_profile1(website, username);
mFirebaseDatabase.child("userinformation").setValue(userinformation1);
}
class useri1
package **.****.m_Model;
public class useri1 {
public String username;
public String website;
public Update_user1() {
}
public Update_user1(String username,String website) {
this.website = website;
this.username = username;
}
public String getwebsite() {
return website;
}
public String getusername() {
return username;
}
public void setwebsite(String website) {
this.website = website;
}
public void setusermame(String usermame) {
this.usermame = usermame;
}
Error:
W/ClassMapper: No setter/field for -KeAi52QSaiuf7p5jEYM found on class
***.****.m_Model.useri1
You're retrieving the value of userinformation. So the snapshot you get in onDataChange will have this value:
"-KeAi52QSaiuf7p5jEYM" : {
"website" : "test1"
"username" : "test1"
}
A useri1 has a website and a username property. But in the JSON above, there is only a property named -KeAi52QSaiuf7p5jEYM. So the two don't match up, leading to the error you get.
To fix this you should do a few things:
loop over the children in the snapshot
drastically simplify your POJO
The resulting code would be:
mFirebaseInstance.getReference("userinformation").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
MyUser model = dataSnapshot.getValue(MyUser.class);
myusername111.setText(model.username);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});
public class MyUser {
public String username;
public String website;
}
You could also use a class with getter and setter. But in that case make sure that the getters follow Java Bean property rules for the capitalization. So:
public class MyUser {
private String username;
private String website;
public MyUser() {
}
public String getUsername() { return username; }
public void setUsername(string value) { username = value; }
public String getWebsite() { return website; }
public void setWebsite(string value) { website = value; }
}
You should use ChildEventListener instead of ValueEventListener.
Because you are using ValueEventListener Firebase is trying to set a property named -KeAi52QSaiuf7p5jEYM, but it is not a property, it is a key.
The code to add ChildEventListener looks like:
mFirebaseInstance.getReference("userinformation").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousKey) {
Update_user1 user = dataSnapshot.getValue(Update_user1.class);
// ...
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String previousKey) {
// ...
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String previousKey) {
// ...
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
// ...
}
#Override
public void onCancelled(DatabaseError databaseError) {
// ...
}
});

Retrieve null values from Firebase database Android

I'm searching by key in my Firebase database, but it retrieves null and I don't know why.
data.getUrl() or data.getText() both give me null values.
In debugging, before line
test data = dataSnapshot.getValue(test.class);
it shows me that data should've retrieved what I'm looking for, but when that line executes, it gives me null.
Database structure:
{
"images" : {
"partner " : {
"text" : "partner",
"url" : "http://res.cloudinary.com/dg3jylcsw/image/upload/v1483565650/sister_x3lv6j.png"
},
"sister" : {
"text " : "sister",
"url" : "http://res.cloudinary.com/dg3jylcsw/image/upload/v1483565650/sister_x3lv6j.png"
}
}
}
test class :
package com.example.android.testy;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#JsonIgnoreProperties(ignoreUnknown=true)
public class test {
private String text;
private String url;
public test() {
// empty default constructor, necessary for Firebase to be able to deserialize blog posts
}
public String getText() {
return text;
}
public String getUrl() {
return url;
}
}
Mainactivity:
package com.example.android.testy;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.firebase.client.Query;
import com.firebase.client.ValueEventListener;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Firebase.setAndroidContext(this);
Firebase rootRef = new Firebase("https://test-219f8.firebaseio.com/images");
Query queryRef = rootRef.orderByKey().equalTo("sister");
queryRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
test data = dataSnapshot.getValue(test.class);
System.out.println(data.getUrl());
}
#Override
public void onCancelled(FirebaseError firebaseError) {
System.out.println("The read failed: " + firebaseError.getMessage());
}
});
}
}
you need to use addChildEventListener instead of addValueEventListener.
try this :
queryRef.addChildEventListener(new ChildEventListener() {
public void onChildAdded(DataSnapshot dataSnapshot, String previousKey) {
test data = dataSnapshot.getValue(test.class);
System.out.println(data.getUrl());
}
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
public void onCancelled(FirebaseError firebaseError) { }
});

Categories

Resources