Retrieve null values from Firebase database Android - 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) { }
});

Related

java.lang.NullPointerException...int java.lang.CharSequence.length()' on a null object reference [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
I have been getting this error since I implemented the
public void getOtherAnimals(){
DatabaseReference otherAnimalDb = FirebaseDatabase.getInstance().getReference().child("Users").child(animalTwo);
otherAnimalDb.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot snapshot, String s) {
if (snapshot.exists() && !snapshot.child("connections").child("no").hasChild(currentUId) && !snapshot.child("connections").child("yes").hasChild(currentUId)){
Cards item = new Cards(snapshot.getKey(), snapshot.child("name").getValue().toString());
rowItems.add(item);
arrayAdapter.notifyDataSetChanged();
}
}
section of code, the program worked beautifully before. I have done my reading on NullPointerExceptions but I don't have enough experience working with them to find the issue. I understand my program is pointing to a null object, but I cannot find it.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.adoptme, PID: 20525
java.lang.NullPointerException: Attempt to invoke interface method 'int java.lang.CharSequence.length()' on a null object reference
at java.util.regex.Matcher.reset(Matcher.java:177)
at java.util.regex.Matcher.<init>(Matcher.java:90)
at java.util.regex.Pattern.matcher(Pattern.java:297)
at com.google.firebase.database.core.utilities.Validation.isValidPathString(Validation.java:40)
at com.google.firebase.database.core.utilities.Validation.validatePathString(Validation.java:44)
at com.google.firebase.database.DataSnapshot.hasChild(DataSnapshot.java:80)
at com.example.android.adoptme.MainActivity$5.onChildAdded(MainActivity.java:186)
at com.google.firebase.database.core.ChildEventRegistration.fireEvent(ChildEventRegistration.java:79)
at com.google.firebase.database.core.view.DataEvent.fire(DataEvent.java:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(EventRaiser.java:55)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Here is my code: (And yes I am aware that there is probably a better way to write it, I am still working on it and refining it with research).
package com.example.android.adoptme;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.FitWindowsViewGroup;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
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 com.lorentzos.flingswipe.SwipeFlingAdapterView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private Cards cards_data[];
private arrayAdapter arrayAdapter;
private int i;
private FirebaseAuth firebaseAuth;
private String currentUId;
private DatabaseReference petDb;
ListView listView;
List<Cards> rowItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
petDb = FirebaseDatabase.getInstance().getReference().child("Users");
firebaseAuth = FirebaseAuth.getInstance();
checkAnimalType();
rowItems = new ArrayList<Cards>();
arrayAdapter = new arrayAdapter(this, R.layout.item, rowItems);
SwipeFlingAdapterView flingContainer = (SwipeFlingAdapterView) findViewById(R.id.frame);
flingContainer.setAdapter(arrayAdapter);
flingContainer.setFlingListener(new SwipeFlingAdapterView.onFlingListener() {
#Override
public void removeFirstObjectInAdapter() {
// this is the simplest way to delete an object from the Adapter (/AdapterView)
Log.d("LIST", "removed object!");
rowItems.remove(0);
arrayAdapter.notifyDataSetChanged();
}
#Override
public void onLeftCardExit(Object dataObject) {
Cards obj = (Cards) dataObject;
String userId = obj.getUserId();
petDb.child(userId).child(userId).child("connections").child("no").child(currentUId).setValue(true);
makeToast(MainActivity.this, "Left!");
}
#Override
public void onRightCardExit(Object dataObject) {
Cards obj = (Cards) dataObject;
String userId = obj.getUserId();
petDb.child(userId).child(userId).child("connections").child("yes").child(currentUId).setValue(true);
makeToast(MainActivity.this, "Right!");
}
#Override
public void onAdapterAboutToEmpty(int itemsInAdapter) {
}
#Override
public void onScroll(float scrollProgressPercent) {
}
});
// Optionally add an OnItemClickListener
flingContainer.setOnItemClickListener(new SwipeFlingAdapterView.OnItemClickListener() {
#Override
public void onItemClicked(int itemPosition, Object dataObject) {
makeToast(MainActivity.this, "Clicked!");
}
});
}
static void makeToast(Context ctx, String s){
Toast.makeText(ctx, s, Toast.LENGTH_SHORT).show();
}
private String animalOne, animalTwo;
public void checkAnimalType(){
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference dogDb = FirebaseDatabase.getInstance().getReference().child("Users").child("Dog");
dogDb.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded( DataSnapshot snapshot, String s) {
if (snapshot.getKey().equals(user.getUid())){
animalOne = "Dog";
animalTwo = "Cat";
getOtherAnimals();
}
}
#Override
public void onChildChanged(DataSnapshot snapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot snapshot) {
}
#Override
public void onChildMoved(DataSnapshot snapshot, String s) {
}
#Override
public void onCancelled(DatabaseError error) {
}
});
DatabaseReference catDb = FirebaseDatabase.getInstance().getReference().child("Users").child("Cat");
catDb.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot snapshot, String s) {
if (snapshot.getKey().equals(user.getUid())){
animalOne = "Cat";
animalTwo = "Dog";
getOtherAnimals();
}
}
#Override
public void onChildChanged(DataSnapshot snapshot, String s) {
}
#Override
public void onChildRemoved( DataSnapshot snapshot) {
}
#Override
public void onChildMoved(DataSnapshot snapshot, String s) {
}
#Override
public void onCancelled(DatabaseError error) {
}
});
}
public void getOtherAnimals(){
DatabaseReference otherAnimalDb = FirebaseDatabase.getInstance().getReference().child("Users").child(animalTwo);
otherAnimalDb.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot snapshot, String s) {
if (snapshot.exists() && !snapshot.child("connections").child("no").hasChild(currentUId) && !snapshot.child("connections").child("yes").hasChild(currentUId)){
Cards item = new Cards(snapshot.getKey(), snapshot.child("name").getValue().toString());
rowItems.add(item);
arrayAdapter.notifyDataSetChanged();
}
}
#Override
public void onChildChanged(DataSnapshot snapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot snapshot) {
}
#Override
public void onChildMoved(DataSnapshot snapshot, String s) {
}
#Override
public void onCancelled(DatabaseError error) {
}
});
}
public void logoutUser (View view){
firebaseAuth.signOut();
Intent intent = new Intent (MainActivity.this, LoginRegistration.class);
startActivity(intent);
}
}
I appreciate any help you can provide me. Thanks in advance.
I think the .hasChild(currentUId) might be causing issues here. You should verify once if it's pointing to correct node in the Firebase DB or not. I couldn't really comment so had to post an answer only.

android-reading and writing in realtime database

I have a user class, which have a contactlist(friends). I want to add the possibility to add friends.
My database
In my code I have a addFriend method, which call a checkUser method. Here I check if the user exists so I can add him in the friend list. I am having difficulties implementing that, like how can I retrieve a variable from an anonymous class?
Here is my code.
package com.android.pfe.other;
import android.support.annotation.Keep;
import android.util.Log;
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.IgnoreExtraProperties;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import java.io.Serializable;
import java.util.Hashtable;
import java.util.List;
/**
* Created by SADA INFO on 13/04/2018.
*/
#IgnoreExtraProperties
#Keep
public class User implements Serializable {
private static final String TAG ="UserClass" ;
public String username;
public String email;
public Hashtable contact;
public String Uid;
public List article;
public DatabaseReference mDatabase;
public List<User> UserList;
public User uti;
public User() {
// Default constructor required for calls to DataSnapshot.getValue(com.android.pfe.other.User.class)
}
public User(String username, String email,String uid) {
this.username = username;
this.email = email;
this.contact=new Hashtable<String,Boolean>();
this.Uid=Uid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public void addUser(String UserId, String name, String email) {
mDatabase = FirebaseDatabase.getInstance().getReference("User");
User user = new User(name, email,UserId);
mDatabase.child(UserId).setValue(user);
}
public void addFriend(String UserId, final String email)
{
mDatabase = FirebaseDatabase.getInstance().getReference("User");
DatabaseReference user = mDatabase.child(UserId);
final DatabaseReference friendlist = user.child("contact");
if(checkUser(email)==true)
friendlist.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Hashtable list = dataSnapshot.getValue(Hashtable.class);
if(list.isEmpty())
{
friendlist.setValue(email);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public boolean checkUser(String email){
Query query = FirebaseDatabase.getInstance().getReference("User").orderByChild("email").equalTo(email);
query.addListenerForSingleValueEvent(mValueEventListener);
if(uti==null)
{
return false;
}
return true;
}
ValueEventListener mValueEventListener=new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists())
{
uti=dataSnapshot.getValue(User.class);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "loadUser:onCancelled", databaseError.toException());
}
};
}
I would recommend that you define an interface say 'ICheckUserListener' with something like onSuccess(DataSnapshot dataSnapshot) and onError(Exception e) methods.
public void checkUser(String email, ICheckUserListener listener)
//Since this method is independent of a specific User instance, it can be static which would require minor adjustments to prevent a memory-leak
{
ValueEventListener mValueEventListener = new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
listener.success(dataSnapshot.exists() ? dataSnapshot : null);
}
#Override
public void onCancelled(DatabaseError databaseError)
{
Log.w(TAG, "loadUser:onCancelled", databaseError.toException());
listener.onError(databaseError.toException());
}
};
FirebaseDatabase
.getInstance()
.getReference("User")
.orderByChild("email") //This is redundant if email ids are unique
.equalTo(email)
.addListenerForSingleValueEvent(mValueEventListener);
}
You can then implement 'ICheckUserListener' in your 'addFriend' method to handle the result.

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) {
// ...
}
});

How can I set the value from Firebase in EditText?

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
}
});

Categories

Resources