what im trying to do right now is trying to grab a location object that is already in my firebase database eg: Artic base and store it in the localeobj i created but for some reason when i run the program it keeps saying localeobj is null am i doing my listener correctly?
package com.example.spy;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.util.ArrayList;
import java.util.Random;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class GameJoin extends AppCompatActivity implements View.OnClickListener {
private FirebaseDatabase database;
private DatabaseReference myRef;
private FirebaseUser user;
private TextView location;
private TextView role;
private TextView desc;
private Button back;
private Intent extra;
private Bundle data;
private String spy;
private Location localeObj;
private String game_code;
private Random rand;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
rand = new Random();
//Firebase stuff
user = FirebaseAuth.getInstance().getCurrentUser();
database = FirebaseDatabase.getInstance();
myRef = database.getReference();
//Views
role = (TextView) findViewById(R.id.label_role);
location = (TextView) findViewById(R.id.label_location);
desc = (TextView) findViewById(R.id.descriptionText);
//Buttons
back = (Button) findViewById(R.id.button3);
//Attach a listener to the button
findViewById(R.id.button3).setOnClickListener(this);
//Retrieve data from previous activity
extra = getIntent();
data = extra.getBundleExtra("game_data");
game_code = data.getString("game_code");
//TODO: Pull location object from Firebase
myRef.child("lobby").child(game_code).child("location").addValueEventListener( new ValueEventListener() {
#Override
public void onCancelled(DatabaseError error) {
System.out.println("************************IN CANCELLED*************************************");
}
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
System.out.println("************************OUTSIDE IF*************************************");
for (DataSnapshot data : dataSnapshot.getChildren()) {
localeObj = dataSnapshot.getValue(Location.class);
System.out.println("************************IN IF*************************************");
}
}
});
myRef.child("lobby").child(game_code).child("spy").addValueEventListener( new ValueEventListener() {
#Override
public void onCancelled(DatabaseError error) {
}
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
spy = (String) dataSnapshot.getValue(String.class);
}
}
});
//Display a special UI if the user is a spy
if (user.getEmail().equals(spy)) {
role.setText("You are the spy. Don't get caught!");
location.setText("Mystery Location");
desc.setText("Welcome to Spy Fall. Keep your identity hidden for the length of the game, or figure out what the location is to win the game.");
} else {
role.setText(localeObj.getRole(rand.nextInt(3)));
location.setText(localeObj.getLocationName());
desc.setText("Welcome to Spy Fall. Infer who is the spy before time runs out in order to win the game.");
}
}
#Override
public void onClick(View v) {
//Stuff happens when buttons are clicked
int id = v.getId();
if (id == R.id.button3) {
//Clean up old game lobby information
myRef = database.getReference("lobby");
myRef.child(game_code).child("players").child(user.getUid()).removeValue(); //Remove all data associated with the current game
//Return to the main lobby
Intent main_lobby = new Intent(GameJoin.this, MainActivity.class);
startActivity(main_lobby);
}
}
}
Here is the tomcat message i get too
--------- beginning of crash
05-09 11:01:42.718 3083-3083/com.example.spy E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.spy, PID: 3083
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.spy/com.example.spy.GameJoin}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.spy.Location.getRole(java.lang.Integer)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.spy.Location.getRole(java.lang.Integer)' on a null object reference
at com.example.spy.GameJoin.onCreate(GameJoin.java:112)
at android.app.Activity.performCreate(Activity.java:6679)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
https://gyazo.com/2b0c1ee92f365f06b1737c99793c96b3
ive posted how my database structure looks like too
If you want to get the locationName please use the following code:
myRef.child("lobby").child(game_code).child("location").addValueEventListener( new ValueEventListener() {
#Override
public void onCancelled(DatabaseError error) {
System.out.println("************************IN CANCELLED*************************************");
}
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
System.out.println("************************OUTSIDE IF*************************************");
String locationName = (String) dataSnapshot.child("locationName").getValue();
}
})
Hope it helps.
Related
Process: mishelb.app.globe_all, PID: 11971
com.google.firebase.database.DatabaseException: Found conflicting getters for name: isChangingConfigurations
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper$BeanMapper.<init>(CustomClassMapper.java:478)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.loadOrCreateBeanMapperForClass(CustomClassMapper.java:330)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.serialize(CustomClassMapper.java:167)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToPlainJavaTypes(CustomClassMapper.java:61)
at com.google.firebase.database.DatabaseReference.setValueInternal(DatabaseReference.java:282)
at com.google.firebase.database.DatabaseReference.setValue(DatabaseReference.java:159)
at com.example.globe_all.SignupScreen.updateUI(SignupScreen.java:92)
at com.example.globe_all.SignupScreen$2.onComplete(SignupScreen.java:77)
at com.google.android.gms.tasks.zzi.run(com.google.android.gms:play-services-tasks##18.0.1:1)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:8167)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:496)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1100)
So I have this in my log. I am using android studio and Firebase, and after trying to
mDataBase.child(keyID).setValue(u);
I get this error code.
Here is the entirety of the code:
package com.example.globe_all;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class SignupScreen extends AppCompatActivity {
private DatabaseReference mDataBase;
private FirebaseDatabase database;
private FirebaseAuth mAuth;
private static final String USER = "user";
private EditText user, email, pass, passRep;
private Button signup;
private User u;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup_screen);
user = findViewById(R.id.user);
email = findViewById(R.id.email);
pass = findViewById(R.id.password);
passRep = findViewById(R.id.pass_repeat);
signup = findViewById(R.id.signu);
database = FirebaseDatabase.getInstance();
mDataBase = database.getReference();
mAuth = FirebaseAuth.getInstance();
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!(TextUtils.isEmpty(email.getText().toString()) && TextUtils.isEmpty(user.getText().toString()) &&
TextUtils.isEmpty(pass.getText().toString()) && TextUtils.isEmpty(passRep.getText().toString())) &&
pass.getText().toString().equals(passRep.getText().toString())) {
u = new User(user.getText().toString(), email.getText().toString(),
pass.getText().toString());
registerUser(email.getText().toString(), pass.getText().toString());
}
}
});
}
public void registerUser(String email, String password) {
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirebaseUser user = mAuth.getCurrentUser();
updateUI(user);
} else {
Log.d("FAIL", "process failed");
}
}
});
}
public void updateUI (FirebaseUser currentU) {
String keyID = mDataBase.push().getKey();
u.setId(keyID);
assert keyID != null;
mDataBase.child(keyID).setValue(u);
Intent login = new Intent(this, LoginScreen.class);
}
}
After attempting the solution provided by
Ticherhaz, still get the error:
Process: mishelb.app.globe_all, PID: 8895
com.google.firebase.database.DatabaseException: Found conflicting getters for name: isChangingConfigurations
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper$BeanMapper.<init>(CustomClassMapper.java:478)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.loadOrCreateBeanMapperForClass(CustomClassMapper.java:330)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.serialize(CustomClassMapper.java:167)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToPlainJavaTypes(CustomClassMapper.java:61)
at com.google.firebase.database.DatabaseReference.setValueInternal(DatabaseReference.java:282)
at com.google.firebase.database.DatabaseReference.setValue(DatabaseReference.java:159)
at com.example.globe_all.SignupScreen.updateUI(SignupScreen.java:89)
at com.example.globe_all.SignupScreen$2.onComplete(SignupScreen.java:75)
at com.google.android.gms.tasks.zzi.run(com.google.android.gms:play-services-tasks##18.0.1:1)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:8167)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:496)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1100)
You re-set back the setId. You are suppose to use the param itself.
At the onClick you comment this line object. So it will become like this.
if (!(TextUtils.isEmpty(email.getText().toString()) && TextUtils.isEmpty(user.getText().toString()) &&
TextUtils.isEmpty(pass.getText().toString()) && TextUtils.isEmpty(passRep.getText().toString())) && pass.getText().toString().equals(passRep.getText().toString())) {
//Comment this line
//u = new User(user.getText().toString(), email.getText().toString(), pass.getText().toString());
registerUser(email.getText().toString(), pass.getText().toString());
}
And then at the updateUi method, you create the User object.
public void updateUI (FirebaseUser currentU) {
final String keyID = mDataBase.push().getKey();
final User userToDB = new User(keyID, user.getText().toString(), email.getText().toString(), pass.getText().toString());
mDataBase.child(keyID).setValue(userToDB);
Intent login = new Intent(this, LoginScreen.class);
}
UPDATE
Since the error regarding your User class, related with isChangingConfigurations. You need to rename the variable since this is reserve to the Firebase
Change
isChangingConfigurations
to
isChangingConfigures
Thanks everyone for the answers, I finally figured it out.
In turns out the database requires my User class to have get() and set()
methods for each of the class' properties.
After setting these up, and inserting my realtime-database URL in:
database = FirebaseDatabase.getInstance(URL);
It finally worked!
I am getting a null pointer exception, while I am trying to add data into realtime database in firebase
package com.example.ecommerce;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.*;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
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.HashMap;
public class register extends AppCompatActivity {
EditText inputname, password, Phone;
Button createaccount;
ProgressDialog loadingbar;
FirebaseDatabase database;
DatabaseReference ref;
User user;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
inputname = findViewById(R.id.username);
password = findViewById(R.id.reg_password);
Phone = findViewById(R.id.reg_phone_number);
createaccount = findViewById(R.id.create_account);
// loadingbar=new ProgressDialog(this);
ref = database.getReference("User");
user = new User();
}
public void getValues() {
user.setName(inputname.getText().toString());
user.setPhone(Phone.getText().toString());
user.setPassword(password.getText().toString());
}
public void btn(View view) {
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
getValues();
ref.child("user02").setValue(user);
Toast.makeText(register.this, "Data Inserted", Toast.LENGTH_LONG).show();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
User class :
package com.example.ecommerce;
public class User {
private String Name;
private String Phone;
private String Password;
public User() {
}
public User(String name, String phone, String password) {
Name = name;
Phone = phone;
Password = password;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getPhone() {
return Phone;
}
public void setPhone(String phone) {
Phone = phone;
}
public String getPassword() {
return Password;
}
public void setPassword(String password) {
Password = password;
}
}
log:
2019-07-22 12:02:52.086 15273-15273/com.example.ecommerce E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.ecommerce, PID: 15273
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ecommerce/com.example.ecommerce.register}: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.database.DatabaseReference com.google.firebase.database.FirebaseDatabase.getReference(java.lang.String)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3121)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3257)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:81)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1935)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7116)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:925)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.database.DatabaseReference com.google.firebase.database.FirebaseDatabase.getReference(java.lang.String)' on a null object reference
at com.example.ecommerce.register.onCreate(register.java:44)
at android.app.Activity.performCreate(Activity.java:7698)
at android.app.Activity.performCreate(Activity.java:7687)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3096)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3257)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:81)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1935)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7116)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:925)
You need to create a database object in your oncreate method. Due to your database object you getting null pointer exception. Your code of oncreate method should be like.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
inputname = findViewById(R.id.username);
password = findViewById(R.id.reg_password);
Phone = findViewById(R.id.reg_phone_number);
createaccount = findViewById(R.id.create_account);
// loadingbar=new ProgressDialog(this);
database = FirebaseDatabase.getInstance();
ref = database.getReference("User");
user = new User();
}
database is null it doesnt reference anything in the heap, you need to initialize it by doing:
FirebaseDatabase database = FirebaseDatabase.getInstance();
Then you can do:
DatabaseReference ref = database.getReference("User");
Seems like you forgot to initialise
FirebaseDatabase database = FirebaseDatabase.getInstance();
Initialise your database , before initialising ref (DatabaseReference).
In order to write to your root "user" ,
User user =new User(
Name = etName.text.toString(),
Phone = etPhone.text.toString(),
password = etPassword.text.toString()
)
database.child(userId).setValue(user)
I keep getting a null object error and my app crashes, though I don't see why there should be an error. I have looked at other examples and those are all the same, and don't help with my issue. My issue occurring although from what I have seen it shouldn't be. The code is:
package com.example.matthew.myapplication;
import android.app.Activity;
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.Spinner;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
import static android.content.ContentValues.TAG;
public class makecharact extends Activity {
Button retur, mak, cont;
FirebaseUser user;
DataSnapshot datasss;
Spinner spinner2;
List<String> list = new ArrayList<String>();
String id;
DatabaseReference myRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.charlist);
Intent task = getIntent();
retur = (Button) findViewById(R.id.returnToLast);
mak = (Button) findViewById(R.id.make);
cont = (Button) findViewById(R.id.Conti);
addListenerOnButton();
ValueEventListener postListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
datasss = dataSnapshot;
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
myRef = FirebaseDatabase.getInstance().getReference();
user = FirebaseAuth.getInstance().getCurrentUser();
Log.d("Test Point 1", "Got to line 61 at the least");
id = user.getUid();
int check = 0;
boolean done = false;
Log.d("User ID", id);
while(done == false) {
String sCheck = Integer.toString(check);
if (datasss.hasChild(id) == true){
if(datasss.child(id).hasChild("Character List") == true){
if (datasss.child(id).child("Character List").hasChild(sCheck) == true) {
list.add(datasss.child(id).child("Character List").child(sCheck).getValue().toString());
check = check + 1;
}else{
done = false;
}
}else{
list.add("No characters");
done = true;
}
}
}
ArrayAdapter<String> dataset = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, list);
dataset.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(dataset);
Log.d("Test Point 2", "Got to line 77 at the least");
}
public void addListenerOnButton() {
cont.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
String stats;
stats = spinner2.getSelectedItem().toString();
myRef.child(id).child("Current Character").setValue(stats);
Intent TaskIntent = new Intent(getApplicationContext(), MainScreen.class);
startActivity(TaskIntent);
finish();
}
});
mak.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
Log.d(TAG, "Moving");
Intent TaskIntent = new Intent(getApplicationContext(), spinner.class);
startActivity(TaskIntent);
finish();
}
});
retur.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "Moving");
finish();
}
});
}
}
My logcat shows:
05-31 21:05:39.802 14318-14318/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.matthew.myapplication, PID: 14318
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.matthew.myapplication/com.example.matthew.myapplication.makecharact}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.google.firebase.database.DataSnapshot.hasChild(java.lang.String)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3253)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3349)
at android.app.ActivityThread.access$1100(ActivityThread.java:223)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7223)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.google.firebase.database.DataSnapshot.hasChild(java.lang.String)' on a null object reference
at com.example.matthew.myapplication.makecharact.addListenerOnButton(makecharact.java:81)
at com.example.matthew.myapplication.makecharact.onCreate(makecharact.java:45)
at android.app.Activity.performCreate(Activity.java:6877)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1136)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3206)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3349)
at android.app.ActivityThread.access$1100(ActivityThread.java:223)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7223)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
I have tried a lot though I still don't get why it isn't working. Any help is appreciated, even if it is it's already been solved on another post (which i couldn't find with a link to said post. Thanks
Yes it will return Null pointer exception Because your variable dataass not initialized.
and its is initialized only when ValueEventListener() is triggers onDataChange() So you need to execute every thing inside the onDataChange()
ValueEventListener postListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
datasss = dataSnapshot;myRef = FirebaseDatabase.getInstance().getReference();
user = FirebaseAuth.getInstance().getCurrentUser();
Log.d("Test Point 1", "Got to line 61 at the least");
id = user.getUid();
int check = 0;
boolean done = false;
Log.d("User ID", id);
while(done == false) {
String sCheck = Integer.toString(check);
if (datasss.hasChild(id) == true){
if(datasss.child(id).hasChild("Character List") == true){
if (datasss.child(id).child("Character List").hasChild(sCheck) == true) {
list.add(datasss.child(id).child("Character List").child(sCheck).getValue().toString());
check = check + 1;
}else{
done = false;
}
}else{
list.add("No characters");
done = true;
}
}
}
ArrayAdapter<String> dataset = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, list);
dataset.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(dataset);
Log.d("Test Point 2", "Got to line 77 at the least");
}
You can get firebase data like this.
DatabaseReference databaseTracks;
List<Track> tracks;
databaseTracks = FirebaseDatabase.getInstance().getReference("tracks").child(intent.getStringExtra(MainActivity.ARTIST_ID));
#Override
protected void onStart() {
super.onStart();
databaseTracks.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
tracks.clear();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Track track = postSnapshot.getValue(Track.class);
tracks.add(track);
}
TrackList trackListAdapter = new TrackList(ArtistActivity.this, tracks);
listViewTracks.setAdapter(trackListAdapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
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
}
});
I have seen lots of question like this but can't seem to get any of the solutions to work for me in my situation. I am using android studio, If you need any more info or files let me know and I will post.
I will post my code here first
package com.example.mick.drivers6;
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.TextView;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.firebase.client.ValueEventListener;
//https://drivers6-55085.firebaseio.com/
public class MainActivity extends AppCompatActivity {
private EditText editTextName;
private EditText editLon;
private EditText editLat;
private TextView textViewPersons;
private Button buttonSave;
int count=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Firebase.setAndroidContext(this);
buttonSave = (Button) findViewById(R.id.buttonSave);
editTextName = (EditText) findViewById(R.id.editTextName);
editLat = (EditText) findViewById(R.id.editLatitude);
editLon = (EditText) findViewById(R.id.editLongitude);
textViewPersons = (TextView) findViewById(R.id.textViewPersons);
//Click Listener for button
buttonSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Creating firebase object
Firebase ref = new Firebase(Config.FIREBASE_URL);
//Getting values to store
String name = editTextName.getText().toString().trim();
String lon = editLon.getText().toString().trim();
String lat = editLat.getText().toString().trim();
//Creating Person object
Driver d = new Driver();
//Adding values
d.setName(name);
d.setLat(lat);
d.setLon(lon);
//Storing values to firebase
ref.setValue(d);
// ref.child("Counter").setValue(count);
count++;
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
for(DataSnapshot postSnapshot : snapshot.getChildren())
{
Driver d = postSnapshot.getValue(Driver.class);
// int numFromDB = postSnapshot.getValue(int.class);
// String test = " Count is on "+numFromDB;
String details = "Name : "+d.getName()+"\nLatitude : "+d.getLat()+"\nLongitude : "+d.getLon();
textViewPersons.setText(details);
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
System.out.println("The read failed: " + firebaseError.getMessage());
}
});
}
});
}
}
Here is the Driver class
package com.example.mick.drivers6;
/**
* Created by Mick on 13/02/2017.
*/
public class Driver {
private String name,lat,lon;
public Driver() {
}
public String getLat() {
return lat;
}
public void setLat(String lat) {
this.lat = lat;
}
public String getLon() {
return lon;
}
public void setLon(String lon) {
this.lon = lon;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
The data will upload to the database on firebase but then the app will crash and I get the error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mick.drivers6, PID: 2936
com.firebase.client.FirebaseException: Failed to bounce to type
at com.firebase.client.DataSnapshot.getValue(DataSnapshot.java:185)
at com.example.mick.drivers6.MainActivity$1$1.onDataChange(MainActivity.java:68)
at com.firebase.client.core.ValueEventRegistration.fireEvent(ValueEventRegistration.java:45)
at com.firebase.client.core.view.DataEvent.fire(DataEvent.java:45)
at com.firebase.client.core.view.EventRaiser$1.run(EventRaiser.java:38)
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)
Caused by: com.fasterxml.jackson.databind.JsonMappingException: Can not instantiate value of type [simple type, class com.example.mick.drivers6.Driver] from String value; no single-String constructor/factory method
at com.fasterxml.jackson.databind.deser.std.StdValueInstantiator._createFromStringFallbacks(StdValueInstantiator.java:428)
at com.fasterxml.jackson.databind.deser.std.StdValueInstantiator.createFromString(StdValueInstantiator.java:299)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromString(BeanDeserializerBase.java:1056)
at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:136)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:123)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:2888)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2034)
at com.firebase.client.DataSnapshot.getValue(DataSnapshot.java:183)
at com.example.mick.drivers6.MainActivity$1$1.onDataChange(MainActivity.java:68)
at com.firebase.client.core.ValueEventRegistration.fireEvent(ValueEventRegistration.java:45)
at com.firebase.client.core.view.DataEvent.fire(DataEvent.java:45)
at com.firebase.client.core.view.EventRaiser$1.run(EventRaiser.java:38)
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)
Application terminated.
When i click export JSON on what has been added to the database on firebase I get this
{
"lat" : "66",
"lon" : "85",
"name" : "mickjj"
}
Thanks
You are storing an instance of Driver at location ref. You are then adding a listener to that location and expecting to find children that are instances of Driver. Instead just use the snapshot value: snapshot.getValue(Driver.class).
Or if you intend to have multiple drivers, add them with unique keys: ref.push().setValue(d). Then your listener logic to scan over the children will work.
If this is new development, you should also consider using the new Firebase SDK instead of the legacy SDK. Reference the Upgrade Guide.
You probably need to add a default empty constructor to your Driver.class:
public Driver() {
}
This will enable reading the class from the database as you try to do in the line that causes the error.