I'm using Firebase Realtime Database to store data for a project. I'm using Android Studio and Java to create a mobile app. In this particular activity, a new user is filling out a form to sign up for the service. Once they input their info and hit the submit button, the on click handles that info and inserts it into the Database.
Here is the relevant code for that class:
public class CreateUserActivity extends AppCompatActivity {
private DatabaseReference mDatabaseReference;
private List<String> mInterestList;
private EditText mUsername;
private EditText mPassword;
private EditText mEmail;
private EditText mLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_user);
mDatabaseReference = FirebaseDatabase.getInstance().getReference();
mInterestList = new ArrayList<>();
mUsername = findViewById(R.id.text_username);
mPassword = findViewById(R.id.text_password);
mEmail = findViewById(R.id.text_email);
mLocation = findViewById(R.id.text_location);
}
public void onCheckboxClicked(View view) {
CheckBox checkbox = (CheckBox) view;
boolean isChecked = checkbox.isChecked();
String interest = checkbox.getText().toString();
if(isChecked) {
mInterestList.add(interest);
}else {
mInterestList.remove(interest);
}
}
public void onSaveUser(View view) {
String username = mUsername.getText().toString();
String password = mPassword.getText().toString();
String email = mEmail.getText().toString();
String location = mLocation.getText().toString();
if(TextUtils.isEmpty(username) ||
TextUtils.isEmpty(password) ||
TextUtils.isEmpty(email) ||
TextUtils.isEmpty(location) ||
mInterestList.size() == 0) {
displayToast("Please enter values for all fields");
}else {
List<String> interests = mInterestList;
User user = new User(username, password, email, location, interests, null);
mDatabaseReference.child("users").child(username).setValue(user, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(#Nullable DatabaseError databaseError, #NonNull DatabaseReference databaseReference) {
if(databaseError != null) {
Log.e(GetTogetherApp.LOG_TAG, databaseError.getMessage());
}else{
displayToast("User created!");
}
}
});
}
}
As I've run through breakpoints the error seems to fire on this line:
mDatabaseReference.child("users").child(username).setValue()
Specifically once I try and enter into the setValue() method. The other two child() calls work to find the path as intended. I have the database reference set as a member variable, so I'm not sure why it seems to lose it at that point.
Here's a look at my database structure
Firebase Database Structure Pic
Error in Android Studio:
The error message in your screenshot is in the variable inspector in the Android Studio debugger. It means that where the error occurs, there is no variable mDatabaseReference so the debugger can't show its value. This is not the actual cause of the crash, merely the debugger telling you that it can't show you something you asked for.
You can find the actual cause of the problem by inspecting the InvocationTargetException e.
Related
I would like to compare the Id that the user has inputted with the Id from the database as a login process. However, when I run the code after filling all the ID and password, the application returns that inputted ID and inputted pw are empty. What's the problem?
It happens because
final String inputId = editId.getText().toString();
final String inputPw = editPw.getText().toString();
These strings are initialized at the beginning in the onCreate() method.
When you click the button the buttonLogIn.setOnClickListener is executed with the same values initialized (empty values).
You have to get the new values from the EditText views.
buttonLogIn.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
//...
String user = editId.getText().toString();
String psw = editPw.getText().toString();
//..
if (!TextUtils.isEmpty(user)&& !TextUtils.isEmpty(psw)){ ... }
}
});
As mentioned by #Andy in the comments, you have to change also the check on firebase because the method is asynchronous.
if (TextUtils.isEmpty(user)&& TextUtils.isEmpty(psw)){
Toast.makeText(LoginScreen.this, "Complete all fields", Toast.LENGTH_SHORT).show();
} else {
//Firebase check
....
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//....
//Check the values here
if (userId.equals(inputId)) && userPw.equals(inputPw)){...}
}
}
You need to get the value from the edit text after the text has been updated:
if (!TextUtils.isEmpty(editId.getText().toString())&& !TextUtils.isEmpty(editPw.getText().toString()))...
I want to store the data from both the RadioButtons as well as the EditText values in the User attribute registeredData, but I don't know how to access my function in a way that allows me to grab all the data, as well as displaying a color change from the RadioButtons. Also how do I check if the input data is already in use (like email)?
I have tried splitting them into two different functions, but I can't get the data back from them into my User attribute registeredData. This is my first try at coding an app so any help is appreciated.
public class Registration extends AppCompatActivity {
private EditText displayname, email, password, confirmpassword;
private Button bsubmit;
private RadioGroup rgroup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
displayname = findViewById(R.id.displayname);
email = findViewById(R.id.useremail);
password = findViewById(R.id.password);
confirmpassword = findViewById(R.id.confirmpassword);
bsubmit = findViewById(R.id.bsubmit);
rgroup = findViewById(R.id.rgroupteams);
bsubmit.setOnClickListener(onRegister);
}
private View.OnClickListener onRegister = new View.OnClickListener() {
#Override
public void onClick(View v) {
final User registeredData;
registeredData = new User();
switch (v.getId()) {
case R.id.bsubmit:
String useremail = email.getText().toString();
String userdisplayname = displayname.getText().toString();
String userpassword = password.getText().toString();
registeredData.email = useremail;
registeredData.displayname = userdisplayname;
registeredData.password = userpassword;
case R.id.rgroupteams:
RadioGroup group = findViewById(R.id.rgroupteams);
group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int idOfSelected) {
switch (idOfSelected) {
case R.id.rbtnmantis:
bsubmit.setBackgroundColor(Color.parseColor("#FF0000"));
bsubmit.setTextColor(Color.parseColor("#000000"));
registeredData.team = "Mantis";
break;
case R.id.rbtlightbringers:
bsubmit.setBackgroundColor(Color.parseColor("#F4DC00"));
bsubmit.setTextColor(Color.parseColor("#000000"));
registeredData.team = "LightBringers";
break;
case R.id.rbtncryptographers:
bsubmit.setBackgroundColor(Color.parseColor("#1C00AA"));
bsubmit.setTextColor(Color.parseColor("#FFFFFF"));
registeredData.team = "Cryptographers";
break;
default:
registeredData.team = "";
}
}
});
}
}
};
}
Right now the color change only turns on after I've have clicked the submit button because I don't know how to better set my setOnClickListener(), I haven't made use of any variables in the registeredData outside of this either, are they set up to be able to be accessed for some data (like displayname) to be displayed?
You need to move onCheckedChangeListener outside of onClickListener. Also, move registeredData outside onClickListener. Make sure that registeredData is "globally" accessible. Then on button click and checked listener you can set data from input fields and from checkboxes to the object.
Second, with TextUtils.isEmpty(email.getText().toString()) you can get boolean if email is empty or not. This you can use for other input fields, just send text to the isEmpty method
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I am trying to show user information stored in my Firebase Realtime Database to text views on a separate page but when I run, LOGCAT is is throwing the error below. I am retrieving the unique id that is stored for the user but Im guessing it is not pulling the data.
This is for a new android studio application that takes a users information stored it in the database and retrieves to a profile pulling all of the information like name, email, school, etc. I have tried changing the object of user and the verification of the user to to authentication check but to no avail. I'm guessing it's a simple fix but I am not seeing it. The error is here.
public class ProfileActivity extends AppCompatActivity {
//Firebase and Database Stuff
private FirebaseAuth mAuth;
private FirebaseUser user; // saying it is never assigned
private TextView Email;
private TextView TwoPNum;
private TextView Meal;
private TextView PantherFunds;
private TextView Expiration;
private TextView Campus;
private Button logout;
private FirebaseDatabase mFirebaseDatabase;
private FirebaseAuth.AuthStateListener mAuthListener;
private DatabaseReference myRef;
// TAG
private static final String TAG = "ProfileActivity";
//declare the database reference object. This is what we use to access the database.
// KEEP AN EYE ON
private String userID = user.getUid();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
Email = (TextView) findViewById(R.id.profileEmail);
TwoPNum = (TextView) findViewById(R.id.profileUid);
Meal = (TextView) findViewById(R.id.mealsNum);
PantherFunds = (TextView) findViewById(R.id.pFundsNum);
Expiration = (TextView) findViewById(R.id.expirationDate);
Campus = (TextView) findViewById(R.id.campusText);
//declare the database reference object. This is what we use to access the database.
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = mFirebaseDatabase.getReference();
logout = (Button) findViewById(R.id.button_logout);
user = mAuth.getCurrentUser();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(FirebaseAuth firebaseAuth) {
user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
toastMessage("Successfully signed in with: " + user.getEmail());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
toastMessage("Successfully signed out.");
}
//... I think a method declaration is meant to go here but not sure
}
};
//new stuff
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
showData(dataSnapshot);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void showData(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
UserInformation uInfo = new UserInformation();
uInfo.setName(ds.child(userID).getValue(UserInformation.class).getName()); //set the name
uInfo.setEmail(ds.child(userID).getValue(UserInformation.class).getEmail()); //set the email
uInfo.setCampus(ds.child(userID).getValue(UserInformation.class).getCampus()); //set the phone_num
uInfo.setExpiration_date(ds.child(userID).getValue(UserInformation.class).getExpiration_date());// set expiration date
uInfo.setpfunds(ds.child(userID).getValue(UserInformation.class).getpfunds()); // get pantherfunds
uInfo.setMeals(ds.child(userID).getValue(UserInformation.class).getMeals()); // get Meals
uInfo.setTwop_num(ds.child(userID).getValue(UserInformation.class).getTwop_num()); // get Meals
//display all the information
Log.d(TAG, "showData: name: " + uInfo.getName());
Log.d(TAG, "showData: email: " + uInfo.getEmail());
Log.d(TAG, "showData: campus : " + uInfo.getCampus());
Log.d(TAG, "showData: expiration_date: " + uInfo.getExpiration_date());
Log.d(TAG, "showData: pfunds: " + uInfo.getpfunds());
Log.d(TAG, "showData: : meals" + uInfo.getMeals());
Log.d(TAG, "showData: twop_num: " + uInfo.getTwop_num());
// Show Data in TextViews
Email.append(uInfo.getEmail());
TwoPNum.append(uInfo.getTwop_num());
Meal.append(String.valueOf(uInfo.getMeals()));
PantherFunds.append(String.valueOf(uInfo.getpfunds()));
Expiration.append(String.valueOf(uInfo.getExpiration_date()));
Campus.append(uInfo.getCampus());
}
}
I expect for a user to log in and their data be shown in text views but am getting this error message
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo
{com.example.hootidapp/com.example.hootidapp.ProfileActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method
'java.lang.String com.google.firebase.auth.FirebaseAuth.getUid()' on a
null object reference
and
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'java.lang.String com.google.firebase.auth.FirebaseAuth.getUid()'
on a null object reference
at com.example.hootidapp.ProfileActivity.<init>(ProfileActivity.java:45)
In this line of code:
user = mAuth.getCurrentUser();
getCurrentUser() returned null because no user was signed in at the time it was called, and you're using auth before the auth listener was able to get a non-null user object. Check for null before calling getUid() on user. Or, ensure that you only call it after a user object is available.
I want to get user's name from my firebase database but I'm getting this error
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
here is my firebase database structure:
below is my code which is proffering the same error:
public class MyAccount extends AppCompatActivity {
private Button mSetupButton;
private EditText mSetupName;
private EditText mSetupBio;
private ImageButton mSetupImageButton;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private String mPostKey=null;
private DatabaseReference mDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_account);
mAuth=FirebaseAuth.getInstance();
String user_id=mAuth.getCurrentUser().getUid();
mDatabase= FirebaseDatabase.getInstance().getReference().child("Profiles");
mPostKey=getIntent().getExtras().getString(user_id);
mSetupName = (EditText) findViewById(R.id.accountName);
mSetupBio = (EditText) findViewById(R.id.accountBio);
mSetupButton = (Button) findViewById(R.id.accountButton);
mSetupImageButton = (ImageButton) findViewById(R.id.accountImageButton);
mDatabase.child(mPostKey).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String post_name = (String) dataSnapshot.child("Name").getValue();
mSetupName.setText(post_name);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
Apparently the error is in getting user id.
just update or add as per your naming convention and your requirements in FirstScreen(i have almost done the required changes you need to make).
Intent i = new Intent(FirstScreen.this, MyAccount.class);
String user_id;
i.putExtra("user_id", user_id);
Assuming the previous activity is MainActivity, then this is the code for it to put the extra to the intent
String mPostKey = // the post key value here
Intent intent = new Intent(MainActivity.this, MyAccount.class);
intent.putExtra("post_key", mPostKey);
startActivity(intent);
To get the extra in MyAccount activity, call
mPostKey = getIntent().getExtras().getString("post_key");
By the way, I recommend you to change your database structure by putting the uid as the "post key", so it will be easier for you to read the user's information without retrieving the "post key"
{
"profiles": {
"0059HUGgfNcEyX73ZpTi6HQUscu1": {
"email": "aaa#gmail.com",
"image": "...",
"name": "...",
"phone": "..."
},
"other user's uid": {
...
}
}
}
With this database structure, you don't need the mPostKey anymore (don't need to put and get the intent extra). To get the user's information, you can just do this
mDatabase.child(mAuth.getCurrentUser().getUid()). addValueEventListener(eventListener);
Hope my answer helps :)
To get the name of the currently logged in user from firebase simply use the following code:
String user_name=mAuth.getCurrentUser().getDisplayName();
I am spinning my wheels trying to create and Save a Customer Object to SQLite in Android,
Here is my Customer Class
public class Customer {
private int id;
private String Name;
private String EmailAddress;
private String Phone;
private Double InitialValue;
private Double BalanceOnCard = 0.00;
private String CardUID;
private Date EnrollmentDate = new Date();
private Date LastTransactionDate = new Date();
public Customer(){}
In my Activity I create private variables like so
public class EnrollmentActivity extends MenuOnlyActivity {
private CustomerSQLiteHelper db;
private final String TAG = "Customer_Add";
Button submitButton;
Button cancelButton;
private EditText customerNameEditText;
private EditText customerEmailEditText;
private EditText customerPhoneEditText;
private EditText valueToAddEditText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_enrollment);
submitButton = (Button) findViewById(R.id.buttonEnrollment);
cancelButton = (Button) findViewById(R.id.CancelEnrollment);
customerNameEditText = (EditText) findViewById(R.id.editTextCustomerName);
customerEmailEditText = (EditText) findViewById(R.id.editTextCustomerEmailAddress);
customerPhoneEditText = (EditText) findViewById(R.id.editTextBusinessPhoneNumber);
valueToAddEditText = (EditText) findViewById(R.id.editTextValueToAdd);
And here is the SubmitButton listener and it is within this code block that it fails, Its not getting to the point of calling the DatabaseHelper to save the Customer object, it fails somewhere right after creating a blank Customer object and starting to set the instance variables.
Log.i(TAG, "Entering Submit Button event");
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (customerNameEditText.getText().length() == 0) {
Toast.makeText(EnrollmentActivity.this, "Enter Customer's name", Toast.LENGTH_SHORT).show();
customerNameEditText.requestFocus();
return;
}
Log.i(TAG, "Create new customer");
//Create new customer object
Customer enteredCustomer = new Customer();
Log.i(TAG, "Created blank customer object");
Log.i(TAG, "populate the new customer object");
//Populate the values of the new object with the values entered in the screen
enteredCustomer.setId(1);
enteredCustomer.setName(customerNameEditText.getText().toString());
enteredCustomer.setEmailAddress(customerEmailEditText.getText().toString());
enteredCustomer.setPhone(customerPhoneEditText.getText().toString());
String enteredValueSting = valueToAddEditText.getText().toString();
double storedValue = Double.parseDouble(enteredValueSting); //convert String to Double
enteredCustomer.setInitialValue(storedValue);
enteredCustomer.setCardUID("ABC123");
Log.i(TAG, "Creating DB Instance");
db = new CustomerSQLiteHelper(EnrollmentActivity.this);
Log.i(TAG, "Created Database instance");
if (db.create(enteredCustomer) != -1) {
Toast.makeText(EnrollmentActivity.this,"Add Customer Successful",Toast.LENGTH_SHORT).show();
customerNameEditText.getText().clear();
customerEmailEditText.getText().clear();
customerPhoneEditText.getText().clear();
valueToAddEditText.getText().clear();
} else {
Toast.makeText(EnrollmentActivity.this, "Add Customer failed", Toast.LENGTH_SHORT).show();
}
}
});
The error message is all over the place, It consistently gives a toast "Unfortunately PROJECT_NAME has stopped" The current console error is "n established connection was aborted by the software in your host machine
java.io.IOException: An established connection was aborted by the software in your host machine" I have restarted Eclipse and Emulator a couple of times. Any help/suggestion will be greatly appreciated.
After more hair pulling I did two things to isolate and resolve the issue, first I created a a default constructor and initialized the parameters to sensible defaults, null for strings and 0 for Ints, then I renamed all my XML IDs to match the Java variables I created in the Activity. Now I am able to create instance of my Customer objects and persist to database.