Firebase User Registration / Authentication with Username - java

Im very new new to Firebase and Im creating my first app.
Im having 2 issues that I would like to get some help please.
I have linked my Android Studio application to my Firebase project and created the code for the Sigup of new user.
SignupActivity.java
package com.company.fbaseapp.activities;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
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.company.fbaseapp.R;
public class SignupActivity extends AppCompatActivity {
private static final String TAG = "SignupActivity";
private EditText mUsername;
private EditText mEmail;
private EditText mPassword;
private Button mSignup;
private ProgressBar mProgressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
//mUsername = (EditText) findViewById(R.id.input_username);
mEmail = (EditText) findViewById(R.id.input_email);
mPassword = (EditText) findViewById(R.id.input_password);
mSignup = (Button) findViewById(R.id.btn_signup);
mSignup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: attempting to signup.");
// Check for null valued EditText fields
if (!isEmpty (mEmail.getText().toString()) && !isEmpty (mPassword.getText().toString())) {
signupNewUser(mEmail.getText().toString(), mPassword.getText().toString());
//Toast.makeText(SignupActivity.this, "Thank you for signing up", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(SignupActivity.this, "You must fill out all the fields", Toast.LENGTH_SHORT).show();
}
}
} );
hideSoftKeyboard();
}
private void signupNewUser(String email, String password) {
showDialog();
FirebaseAuth.getInstance().createUserWithEmailAndPassword(email, password)
.addOnCompleteListener( new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "onComplete: onComplete: " + task.isSuccessful());
if (task.isSuccessful()) {
Log.d(TAG, "onComplete: AuthState: " + FirebaseAuth.getInstance()
.getCurrentUser()
.getUid());
FirebaseUser currentperson=FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("Users").child(currentperson.getUid());
ref.child("Username").setValue(name);
FirebaseAuth.getInstance().signOut();
redirectLoginScreen();
}
if (!task.isSuccessful()) {
Toast.makeText(SignupActivity.this, "Unable to signup", Toast.LENGTH_SHORT).show();
}
}
});
}
/**
* Return true if the #param is null
* #param string
* #return
*/
private boolean isEmpty(String string){
return string.equals("");
}
/**
* Redirects the user to the login screen
*/
private void redirectLoginScreen(){
Log.d(TAG, "redirectLoginScreen: redirecting to login screen.");
Intent intent = new Intent(SignupActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
private void showDialog(){
mProgressBar.setVisibility(View.VISIBLE);
}
private void hideDialog(){
if(mProgressBar.getVisibility() == View.VISIBLE){
mProgressBar.setVisibility(View.INVISIBLE);
}
}
private void hideSoftKeyboard(){
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
}
LogCat
12-30 01:19:18.492 31917-31917/com.company.fbaseapp D/SignupActivity: onClick: attempting to signup.
12-30 01:19:18.493 31917-31917/com.company.fbaseapp D/AndroidRuntime: Shutting down VM
12-30 01:19:18.497 31917-31917/com.company.fbaseapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.company.fbaseapp, PID: 31917
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ProgressBar.setVisibility(int)' on a null object reference
at com.company.fbaseapp.activities.SignupActivity.showDialog(SignupActivity.java:126)
at com.company.fbaseapp.activities.SignupActivity.signupNewUser(SignupActivity.java:72)
at com.company.fbaseapp.activities.SignupActivity.access$300(SignupActivity.java:21)
at com.company.fbaseapp.activities.SignupActivity$1.onClick(SignupActivity.java:54)
at android.view.View.performClick(View.java:6289)
at android.view.View$PerformClick.run(View.java:24800)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6809)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
12-30 01:19:18.499 31917-31917/com.company.fbaseapp D/AppTracker: App Event: crash
The first issue is that the application is crashing when I click on the mSignup button.
Thesecond issue is that I would like to know how I can add a Unique Username to each registerd user.
Please help me figure out how to fix these 2 issues.
Thanks

This is the error:
`Attempt to invoke virtual method 'void android.widget.ProgressBar.setVisibility(int)' on a null object reference`
the progressbar is null, you need to add this:
mProgressBar = (ProgressBar) findViewById(R.id.progressBar); //your id in xml
Regarding unique username for each user, you can do this:
FirebaseUser currentperson=FirebaseAuth.getInstance().getCurrentUser();
then if you are saving to the database, you can do this:
DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("Users");
ref.child(currentperson.getUid());
The above will add a unique userid to each username.
If you mean to add a unique username in authentication, you cannot do that. But the email is unique there by default so if you try to register another user with same email then you will get error:authentication failed
Edit:
You cannot add username in authentication, if you go to the console then you will see the userid and email there added. The authentication provides you with a userid but username cannot be added in the authentication, it can only be added in the database, can do this:
DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("Users").child(currentperson.getUid());
ref.child("Username").setValue(name);
then in your firebase database you would have this:
Users
LA0rRvP4TrewYbMSl0bDA3ork8h2
Username: hisname_here

Related

Cannot load a java class/ layout file in android studio

After successfully passing the login screen, I have called the AddJournalActivity.java class.. However, it crashes, as shown in the video.. What do I do? This is the code for AddJournalActivity.java
package com.project.journeyjournal;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.storage.StorageReference;
public class AddJournalActivity extends AppCompatActivity implements View.OnClickListener {
private static final int GALLERY_CODE = 1;
private Button saveButton;
private ImageView addPhotoButton;
private EditText titleEditText;
private EditText thoughtsEditText;
private ImageView imageView;
private FirebaseAuth firebaseAuth;
private FirebaseAuth.AuthStateListener authStateListener;
private FirebaseUser user;
//connection to firestore
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private StorageReference storageReference;
private CollectionReference collectionReference = db.collection("Journal");
private Uri imageUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_journal);
firebaseAuth = FirebaseAuth.getInstance();
titleEditText = findViewById(R.id.post_title_et);
thoughtsEditText = findViewById(R.id.post_description_et);
imageView = findViewById(R.id.post_imageView);
saveButton = findViewById(R.id.post_save_journal_button);
saveButton.setOnClickListener(this);
addPhotoButton = findViewById(R.id.postCameraButton);
addPhotoButton.setOnClickListener(this);
authStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
user = firebaseAuth.getCurrentUser();
if (user != null){
} else{
}
}
};
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.post_save_journal_button:
//save Journal
break;
case R.id.postCameraButton:
//get image from camera or gallery
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, GALLERY_CODE);
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_CODE && resultCode == RESULT_OK ){
if (data != null){
imageUri = data.getData();
imageView.setImageURI(imageUri);//show image
}
}
}
#Override
protected void onStart() {
super.onStart();
user = firebaseAuth.getCurrentUser();
firebaseAuth.addAuthStateListener((authStateListener));
}
#Override
protected void onStop() {
super.onStop();
if (firebaseAuth!= null){
firebaseAuth.removeAuthStateListener(authStateListener);
}
}
}
I tried opening other pages instead of AddJournalActivity after the login activity, and it was working fine. If I delete all the code in the .java file, then the layout file opens just fine. So I assume that the problem is with AddJournalActivity.java. But I am unable to find it.
I have added the Logcat if it helps.2022-04-06 11:19:46.326 15573-15573/com.project.journeyjournal E/AndroidRuntime: FATAL EXCEPTION: main Process: com.project.journeyjournal, PID: 15573 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.project.journeyjournal/com.project.journeyjournal.AddJournalActivity}: java.lang.ClassCastException: androidx.cardview.widget.CardView cannot be cast to android.widget.ImageView at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3308) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3457) at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) 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:2044) at android.os.Handler.dispatchMessage(Handler.java:107) at android.os.Looper.loop(Looper.java:224) at android.app.ActivityThread.main(ActivityThread.java:7560) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950) Caused by: java.lang.ClassCastException: androidx.cardview.widget.CardView cannot be cast to android.widget.ImageView at com.project.journeyjournal.AddJournalActivity.onCreate(AddJournalActivity.java:51) at android.app.Activity.performCreate(Activity.java:7893) at android.app.Activity.performCreate(Activity.java:7880) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1307) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3283) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3457)  at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)  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:2044)  at android.os.Handler.dispatchMessage(Handler.java:107)  at android.os.Looper.loop(Looper.java:224)  at android.app.ActivityThread.main(ActivityThread.java:7560)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950) 
I watched your video. Your app crashes after logging in.
By observing your logcat, I can see an error causing with CardView and ImageView. You didn't provide your XML Code, so I'm not sure what exactly is the cause.
Here check this line-
ComponentInfo{com.project.journeyjournal/com.project.journeyjournal.AddJournalActivity}:
java.lang.ClassCastException: androidx.cardview.widget.CardView cannot be cast to android.widget.ImageView
Solution
Possibly you have a CardView in XML which has an ID post_imageView or postCameraButton and you're binding this ID to ImageView by calling
imageView = findViewById(R.id.post_imageView);
or
addPhotoButton = findViewById(R.id.postCameraButton);
Check your IDs in XML and let me know the update.

Can't open another activity, when button is clicked, instead opens the same activity

When i click on my create account button, it should open another activity but instead, it just opens the same activity again and erases my inputs in the email and password. I also have my activities defined in the manifest.
package com.example.music_link_firebase;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
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;
public class LoginActivity extends AppCompatActivity {
EditText lemail, lpassword;
Button login, lregister;
ProgressBar lprogressBar;
FirebaseAuth lfAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
lemail = findViewById(R.id.email1);
lpassword = findViewById(R.id.password1);
login = findViewById(R.id.login1);
lregister = findViewById(R.id.signup);
lprogressBar = findViewById(R.id.progressBar2);
lfAuth = FirebaseAuth.getInstance();
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String email = lemail.getText().toString().trim();
String password = lpassword.getText().toString().trim();
if(TextUtils.isEmpty(email)){
lemail.setError("Email is required");
return;
}
if(TextUtils.isEmpty(password)){
lpassword.setError("password is required");
}
if(password.length() < 6){
lpassword.setError("password must be longer than 5 characters");
}
lprogressBar.setVisibility(View.VISIBLE);
//authenticate the user
lfAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(LoginActivity.this, "Logged in successfully", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), HomeActivity.class));
}
else{
Toast.makeText(LoginActivity.this, "Error ! " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
lprogressBar.setVisibility(View.GONE);
}
}
});
}
});
lregister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
});
}
}
the java code for the activity that's supposed to open when the button is clicked
package com.example.music_link_firebase;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
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;
public class MainActivity extends AppCompatActivity {
EditText rEmail, rpassword, rphone, rfullname;
Button rsignin, rRegister;
FirebaseAuth rfAuth;
ProgressBar rprogressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rfullname = findViewById(R.id.fullname);
rEmail = findViewById(R.id.email);
rpassword = findViewById(R.id.password);
rphone = findViewById(R.id.phone);
rsignin = findViewById(R.id.signin);
rRegister = findViewById(R.id.register);
rfAuth = FirebaseAuth.getInstance();
rprogressBar = findViewById(R.id.progressBar);
if(rfAuth.getCurrentUser() != null){
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
finish();
}
rRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String email = rEmail.getText().toString().trim();
String password = rpassword.getText().toString().trim();
if(TextUtils.isEmpty(email)){
rEmail.setError("Email is required");
return;
}
if(TextUtils.isEmpty(password)){
rpassword.setError("password is required");
return;
}
if(password.length() < 6){
rpassword.setError("password must be longer than 5 characters");
return;
}
rprogressBar.setVisibility(View.VISIBLE);
// register the user to firebase
rfAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(MainActivity.this, "user created", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), LoginActivity.class));
}
else
Toast.makeText(MainActivity.this, "Error ! " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
rprogressBar.setVisibility(View.GONE);
}
});
}
});
rsignin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getApplicationContext(), LoginActivity.class));
}
});
}
}
it doesn't show any error but i checked the logcat why this is happening and this is what it shows everytime i click the create account button:
2022-03-04 00:03:03.734 31199-31199/com.example.music_link_firebase D/DecorView: onWindowFocusChangedFromViewRoot hasFocus: true, DecorView#7893d4e[LoginActivity]
2022-03-04 00:03:03.735 31199-31199/com.example.music_link_firebase D/ViewRootImpl[LoginActivity]: windowFocusChanged hasFocus=true inTouchMode=true
2022-03-04 00:03:04.429 31199-31199/com.example.music_link_firebase E/c_link_firebas: Invalid ID 0x00000000.
2022-03-04 00:03:04.436 31199-31199/com.example.music_link_firebase E/c_link_firebas: Invalid ID 0x00000000.
2022-03-04 00:03:04.467 31199-31199/com.example.music_link_firebase D/ViewRootImpl[LoginActivity]: windowFocusChanged hasFocus=false inTouchMode=true
2022-03-04 00:03:04.522 31199-31199/com.example.music_link_firebase E/c_link_firebas: Invalid ID 0x00000000.
2022-03-04 00:03:04.544 31199-31199/com.example.music_link_firebase D/ViewRootImpl: support adaptive color gamut feature!
2022-03-04 00:03:04.529 31199-31199/com.example.music_link_firebase E/c_link_firebas: Invalid ID 0x00000000.
2022-03-04 00:03:04.545 31199-31199/com.example.music_link_firebase V/ViewRootImpl: The specified message queue synchronization barrier token has not been posted or has already been removed
2022-03-04 00:03:04.584 31199-31199/com.example.music_link_firebase W/Choreographer: Already have a pending vsync event. There should only be one at a time.
2022-03-04 00:03:04.605 31199-31199/com.example.music_link_firebase D/DecorView: onWindowFocusChangedFromViewRoot hasFocus: true, DecorView#dd70151[LoginActivity]
2022-03-04 00:03:04.606 31199-31199/com.example.music_link_firebase D/ViewRootImpl[LoginActivity]: windowFocusChanged hasFocus=true inTouchMode=true
2022-03-04 00:03:04.648 31199-4783/com.example.music_link_firebase W/System: A resource failed to call close.
2022-03-04 00:03:04.648 31199-4783/com.example.music_link_firebase W/System: A resource failed to call close.
I followed a youtube tutorial for this code so i'm not sure why this is happening. Also, when i first ran the program it directed me first to the MainActivity which is the registration page. after i registered and i encountered the problem, whenever i try to stop the program and run it again it now sends me directly to the LoginActivity which is not supposed to happen. not sure also why. I also checked on firebase if my previous registration was inserted in the database and it was there so i'm not really sure where i went wrong.

App crashes after adding FirebaseAuth.getInstance

I had added firebase authentication yesterday and it was working fine but today after editing some files it is crashing.
App only crashes when I add "firebaseAuth =FirebaseAuth.getInstance()".
If I remove it then all things work fine but now I cannot add firebase.
SignUp.java
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
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;
public class SignUp extends AppCompatActivity implements View.OnClickListener {
private TextView alreadyRegistered;
private EditText mEmailView;
private EditText mPasswordView;
private Button signup;
private FirebaseAuth firebaseAuth;
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
progressDialog=new ProgressDialog(this);
mEmailView = (EditText) findViewById(R.id.email_signup);
mPasswordView = (EditText) findViewById(R.id.password_signup);
signup=(Button)findViewById(R.id.signup);
alreadyRegistered=(TextView)findViewById(R.id.already_registered);
// firebaseAuth =FirebaseAuth.getInstance();
//// if(firebaseAuth.getCurrentUser() != null){
//// //that means user is already logged in
//// //so close this activity
//// finish();
////
//// //and open profile activity
//// startActivity(new Intent(getApplicationContext(), Home.class));
//// }
alreadyRegistered.setOnClickListener(this);
signup.setOnClickListener(this);
}
private void registerUser() {
//getting email and password from edit texts
String email = mEmailView.getText().toString().trim();
String password = mPasswordView.getText().toString().trim();
//checking if email and passwords are empty
if (TextUtils.isEmpty(email)) {
Toast.makeText(this, "Please enter email", Toast.LENGTH_LONG).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(this, "Please enter password", Toast.LENGTH_LONG).show();
return;
}
//if the email and password are not empty
//displaying a progress dialog
progressDialog.setMessage("Registering Please Wait...");
progressDialog.show();
//creating a new user
firebaseAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
//checking if success
if (task.isSuccessful()) {
//display some message here
Toast.makeText(SignUp.this, "Successfully registered", Toast.LENGTH_LONG).show();
Intent intent = new Intent(SignUp.this, MainActivity.class);
startActivity(intent);
} else {
//display some message here
Toast.makeText(SignUp.this, "Registration Error", Toast.LENGTH_LONG).show();
}
// progressDialog.dismiss();
}
});
}
#Override
public void onClick(View v) {
if(v==signup)
{
registerUser();
}
if(v==alreadyRegistered)
{
Intent intent = new Intent(SignUp.this,MainActivity.class);
startActivity(intent);
}
}
}
I tried debugging and it crashes when I run that particular line.
Crash Logs
2019-02-16 14:43:23.569 25053-25053/com.example.android.nirog E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.nirog, PID: 25053
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.nirog/com.example.android.nirog.SignUp}: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.example.android.nirog. Make sure to call FirebaseApp.initializeApp(Context) first.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2949)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3027)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1745)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:200)
at android.app.ActivityThread.main(ActivityThread.java:6956)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:519)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:836)
Caused by: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.example.android.nirog. Make sure to call FirebaseApp.initializeApp(Context) first.
at com.google.firebase.FirebaseApp.getInstance(com.google.firebase:firebase-common##16.0.2:240)
at com.google.firebase.auth.FirebaseAuth.getInstance(Unknown Source:1)
at com.example.android.nirog.SignUp.onCreate(SignUp.java:44)
at android.app.Activity.performCreate(Activity.java:7225)
at android.app.Activity.performCreate(Activity.java:7216)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1215)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2902)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3027) 
at android.app.ActivityThread.-wrap11(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1745) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:200) 
at android.app.ActivityThread.main(ActivityThread.java:6956) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:519) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:836) 
2019-02-16 14:43:23.623 25053-25053/com.example.android.nirog I/Process: Sending signal. PID: 25053 SIG: 9
This is most helpful in android with fluuter and firebase
in app level build.gradle
defaultConfig {
minSdkVersion 23
}
in project level gradle.properties add
org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true
android.enableR8=true
in build.gradle add
dependencies {
classpath 'com.android.tools.build:gradle:3.4.2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath 'com.google.gms:google-services:4.2.0'
}
you can skip that Kotlin plugin if you are not using Kotlin support
Dont forget to run flutter clean and then flutter pub upgrade
These changes helped me preventing my app crashes, It should help you too.
You have not initialised firebase. Add this in onCreate of your SignUp class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
FirebaseApp.initializeApp(Context)
Make sure to call FirebaseApp.initializeApp(Context) first in Android method added in MyApplication class in your project like :
override fun onCreate() {
super.onCreate()
{
FirebaseApp.initializeApp(Context);
}

App Crashed while passing data using Intent on Pressing Next Button (getStringExtra) [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I want to move all data 5 (EditText) from activity 1 to 2
public class MainActivity extends Activity
private EditText fName_ET;
private EditText lName_ET;
private EditText phoneNum_ET;
private EditText eMail_ET;
private EditText deviceModel_ET;
private EditText nameDevice_ET;
private Button nextPage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
fName_ET = (EditText)findViewById(R.id.fName_ET);
lName_ET = (EditText)findViewById(R.id.lName_ET);
phoneNum_ET = (EditText)findViewById(R.id.phone_ET);
eMail_ET = (EditText)findViewById(R.id.mail_ET);
nameDevice_ET = (EditText)findViewById(R.id.name_device);
deviceModel_ET = (EditText)findViewById(R.id.model_device);
nextPage = (Button)findViewById(R.id.next_btn);
nextPage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
String fName = fName_ET.getText().toString().trim();
String lName = lName_ET.getText().toString().trim();
String email = eMail_ET.getText().toString().trim();
String phone = phoneNum_ET.getText().toString().trim();
String nameDevice = nameDevice_ET.getText().toString().trim();
String modelDevice =deviceModel_ET.getText().toString().trim();
intent.putExtra("modelDevice",modelDevice);
intent.putExtra("fName", fName);
intent.putExtra("lName", lName);
intent.putExtra("phone", phone);
intent.putExtra("email", email);
intent.putExtra("nameDevice", nameDevice);
startActivity(intent);
}
});
public class Main2Activity extends Activity
{
package com.example.eranp.cp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class Main2Activity extends Activity {
private EditText pro_device_det;
private Button saveDataBase;
private DatabaseReference databaseCustomer, databaseDevice, databaseProblem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main3);
databaseCustomer = FirebaseDatabase.getInstance().getReference("customers");
databaseDevice = FirebaseDatabase.getInstance().getReference("device");
databaseProblem = FirebaseDatabase.getInstance().getReference("problem");
saveDataBase = (Button) findViewById(R.id.save_btn);
pro_device_det = (EditText) findViewById(R.id.pro_device_det);
Intent intent = getIntent();
final String fName = intent.getStringExtra("fName");
final String lName = intent.getStringExtra("lName");
final String phone = intent.getStringExtra("phone");
final String email = intent.getStringExtra("email");
final String modelDevice = intent.getStringExtra("modelDevice");
final String nameDevice = intent.getStringExtra("nameDevice");
saveDataBase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String proDeviceDet = pro_device_det.getText().toString().trim();
String shortProDeviceDet = string3Words(proDeviceDet);
DateFormat df = new SimpleDateFormat("d MMM yyyy, HH:mm");
String date = df.format(Calendar.getInstance().getTime());
if (!TextUtils.isEmpty(proDeviceDet)) {
String id = databaseCustomer.push().getKey();
Customer customer = new Customer(id, fName, lName, email, phone);
databaseCustomer.child(id).setValue(customer);
Device device = new Device(id, nameDevice, modelDevice);
databaseDevice.child(id).setValue(device);
Problem problem = new Problem(id, date, proDeviceDet, 0, shortProDeviceDet);
// Toast.makeText(this , "Customer added", Toast.LENGTH_LONG).show();
} else {
// Toast.makeText(this, "Please write on an empty cell", Toast.LENGTH_LONG).show();
}
}
});
}
private String string3Words(String s) {
String[] splitted = s.split("\\s+");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < splitted.length; i++) {
sb.append(splitted[i]);
if (i == 3) {
break;
}
}
String newS = sb.toString();
return newS;
}
}
log when I press:
down VM 03-09 14:47:16.903 3476-3476/com.example.eranp.clientpage
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.eranp.clientpage, PID: 3476
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.eranp.clientpage/com.example.eranp.clientpage.Main2Activity}:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.Button.setOnClickListener(android.view.View$OnClickListener)'
on a null object reference
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2924)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2985)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1635)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6692)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'void
android.widget.Button.setOnClickListener(android.view.View$OnClickListener)'
on a null object reference
at
com.example.eranp.clientpage.Main2Activity.onCreate(Main2Activity.java:50)
at android.app.Activity.performCreate(Activity.java:6912)
at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2877)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2985) 
at android.app.ActivityThread.-wrap14(ActivityThread.java) 
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1635) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6692) 
at java.lang.reflect.Method.invoke(Native Method) 
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
Why when I press the next button the app crashing?
Thank you for helping!
You are trying to set a click listener on a button in Main2Activity. Most likely the button can't be inflated from the second activity's layout because it doesn't exist.
android.widget.Button.setOnClickListener(android.view.View$OnClickListener)'
on a null object reference at
com.example.eranp.clientpage.Main2Activity.onCreate(Main2Activity.java:50)
at
As per your error log you are getting error because of this
Attempt to invoke virtual method 'void
android.widget.Button.setOnClickListener(android.view.View$OnClickListener)'
on a null object reference at com.example.eranp.clientpage.Main2Activity.onCreate(Main2Activity.java:50)
saveDataBase = (Button) findViewById(R.id.save_btn);
saveDataBase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// code...
}
});
Check weather button id is correct and is in same layout of the activity or not.

Illegal destination address sms manager shared preferences

I am using numbers stored in shared preferences to send text messages but when i run the app it crashes and the logcat says there is an illegal destination address how?
here is my logcat
12-30 21:01:30.758 12239-12239/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.android.beez.help2, PID: 12239
java.lang.IllegalArgumentException: Invalid destinationAddress
at android.telephony.SmsManager.sendTextMessage(SmsManager.java:127)
at com.android.beez.help2.MainActivity.sendSms(MainActivity.java:63)
at com.android.beez.help2.MainActivity$2.onClick(MainActivity.java:41)
at android.view.View.performClick(View.java:4475)
at android.view.View$PerformClick.run(View.java:18790)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5328)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:828)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:644)
at dalvik.system.NativeStart.main(Native Method)
and here is my
MainActivity.java
package com.android.beez.help2;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.LocationManager;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button button;
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonInit();
Button setupMa = (Button) findViewById(R.id.setupMA);
setupMa.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent a = new Intent(MainActivity.this,Setup.class);
startActivity(a);
}
});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loadCredit();
sendSms();
}
});
}
protected void sendSms() {
spInit();
String number1 = sharedPreferences.getString("first", "");
String number2 = sharedPreferences.getString("second", "");
String number3 = sharedPreferences.getString("third", "");
String name = sharedPreferences.getString("name", "");
String text = "Help, this is " + name + ", if you are reading this I am in trouble please help me" +
" Iam located at " + "http://www.google.com/maps/place/"+GPSTracker.latitude+","+GPSTracker.longitude+ " " +
"" +
"" +
"-Sent via the Emergency App";
SmsManager manager = SmsManager.getDefault();
manager.sendTextMessage(number1, null, text, null, null);
manager.sendTextMessage(number2, null, text, null, null);
manager.sendTextMessage(number3, null, text, null, null);
boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.getBoolean("isFirstRun", true);
if (isFirstRun) {
Intent launchSetups = new Intent(MainActivity.this, Setup.class);
startActivity(launchSetups);
}
}
protected void loadCredit() {
spInit();
String creditLine = sharedPreferences.getString("dialLoadSp","");
Uri number = Uri.parse("tel:"+creditLine);
Intent callIntent = new Intent(Intent.ACTION_DIAL, number);
startActivity(callIntent);
}
public void buttonInit() {
button = (Button) findViewById(R.id.button_main);
}
public void spInit() {
sharedPreferences = MainActivity.this.getSharedPreferences("com.android.beez.help2",MODE_PRIVATE);
}
}
The numbers the messages are being sent to are from editTexts and are the stored in sharedPreferences. could the problem be from shared preferences or is it and issue of the text manager
I think you should specify the destination address add an if... if(num1!="" || num2!="" || num3...)
manager.sendText...
Oh, I know this one :) Hope I'm not to late.
IllegalArgumentException is thrown if destinationAddress or text are empty.
In your case, you have this String number1 = sharedPreferences.getString("first", ""); which means that your number1 is empty at first run of the app, and therefore you get that exception.
Also you didn't provide full code here, where you said that numbers would be fill from edit text.

Categories