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);
}
Related
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.
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.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
Hello my question is about my app is crash after I am trying to hit next fragment.
Code is compiling but i don't know how to solve this problem.
Something with onclicklistner.
I tried some solutions but didn't succeed.
This is my code:
ProfileFragment.java
package com.statusionew.statusio.fragments;
import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button;
import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.statusionew.statusio.ForgetchangePasswordActivity; import com.statusionew.statusio.LoginActivity; import com.statusionew.statusio.R; import com.statusionew.statusio.MainActivity;
import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick;
public class ProfileFragment extends BaseFragment implements View.OnClickListener{
FirebaseAuth auth;
FirebaseUser user;
ProgressDialog PD;
#BindView(R.id.sign_out_button) Button btnSignOut;
#BindView(R.id.change_password_button) Button btnChangePass;
#BindView(R.id.change_email_button) Button btnChangeEmail;
#BindView(R.id.delete_user_button) Button btnDeleteUser;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.activity_setting, container, false);
ButterKnife.bind(getActivity(), view);
((MainActivity) getActivity()).updateToolbarTitle("Profile");
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
auth = FirebaseAuth.getInstance();
user = auth.getCurrentUser();
PD = new ProgressDialog(getActivity());
PD.setMessage("Loading...");
PD.setCancelable(true);
PD.setCanceledOnTouchOutside(false);
btnSignOut.setOnClickListener(new View.OnClickListener() {
#Override
#OnClick(R.id.sign_out_button)
public void onClick(View view) {
auth.signOut();
FirebaseAuth.AuthStateListener authListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user == null) {
Intent intent = new Intent(getActivity(), LoginActivity.class);
startActivity(intent);
}
}
};
}
});
btnChangePass.setOnClickListener(new View.OnClickListener() {
#Override
#OnClick(R.id.change_password_button)
public void onClick(View view) {
startActivity(new Intent(getActivity().getApplicationContext(), ForgetchangePasswordActivity.class).putExtra("Mode", 1));
}
});
btnChangeEmail.setOnClickListener(new View.OnClickListener() {
#Override
#OnClick(R.id.change_email_button)
public void onClick(View view) {
startActivity(new Intent(getActivity().getApplicationContext(), ForgetchangePasswordActivity.class).putExtra("Mode", 2));
}
});
btnDeleteUser.setOnClickListener(new View.OnClickListener() {
#Override
#OnClick(R.id.delete_user_button)
public void onClick(View view) {
startActivity(new Intent(getActivity().getApplicationContext(), ForgetchangePasswordActivity.class).putExtra("Mode", 3));
}
});
}
#Override
public void onClick(View v) {
if (auth.getCurrentUser() == null) {
startActivity(new Intent(getActivity(), LoginActivity.class));
getActivity().finish();
}
super.onResume();
} }
this the log that say 'Attempt to invoke virtual method'-
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.statusionew.statusio, PID: 9206
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.statusionew.statusio.fragments.ProfileFragment.onCreate(ProfileFragment.java:65)
at android.support.v4.app.Fragment.performCreate(Fragment.java:2339)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1377)
at android.support.v4.app.FragmentTransition.addToFirstInLastOut(FragmentTransition.java:1109)
at android.support.v4.app.FragmentTransition.calculateFragments(FragmentTransition.java:996)
at android.support.v4.app.FragmentTransition.startTransitions(FragmentTransition.java:99)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2364)
at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2322)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2229)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:781)
at com.statusionew.statusio.views.FragNavController.executePendingTransactions(FragNavController.java:631)
at com.statusionew.statusio.views.FragNavController.switchTab(FragNavController.java:142)
at com.statusionew.statusio.views.FragNavController.switchTab(FragNavController.java:158)
at com.statusionew.statusio.MainActivity.switchTab(MainActivity.java:149)
at com.statusionew.statusio.MainActivity.access$100(MainActivity.java:30)
at com.statusionew.statusio.MainActivity$1.onTabSelected(MainActivity.java:87)
at android.support.design.widget.TabLayout.dispatchTabSelected(TabLayout.java:1165)
at android.support.design.widget.TabLayout.selectTab(TabLayout.java:1158)
at android.support.design.widget.TabLayout.selectTab(TabLayout.java:1128)
at android.support.design.widget.TabLayout$Tab.select(TabLayout.java:1427)
at android.support.design.widget.TabLayout$TabView.performClick(TabLayout.java:1537)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
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)
Connected to process 10580 on device emulator-5554
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/art: Not late-enabling -Xcheck:jni (already on)
W/art: Unexpected CPU variant for X86 using defaults: x86
W/System: ClassLoader referenced unknown path: /data/app/com.statusionew.statusio-1/lib/x86
D/FirebaseApp: com.google.firebase.crash.FirebaseCrash is not linked. Skipping initialization.
V/FA: Registered activity lifecycle callback
I/FirebaseInitProvider: FirebaseApp initialization successful
I/InstantRun: starting instant run server: is main process
E/InstantRun: IO Error creating local socket at com.statusionew.statusio
java.io.IOException: Address already in use
at android.net.LocalSocketImpl.bindLocal(Native Method)
at android.net.LocalSocketImpl.bind(LocalSocketImpl.java:308)
at android.net.LocalServerSocket.<init>(LocalServerSocket.java:48)
at com.android.tools.ir.server.Server.<init>(Server.java:91)
at com.android.tools.ir.server.Server.create(Server.java:85)
at com.android.tools.ir.server.InstantRunContentProvider.onCreate(InstantRunContentProvider.java:49)
at android.content.ContentProvider.attachInfo(ContentProvider.java:1751)
at android.content.ContentProvider.attachInfo(ContentProvider.java:1726)
at android.app.ActivityThread.installProvider(ActivityThread.java:5853)
at android.app.ActivityThread.installContentProviders(ActivityThread.java:5445)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5384)
at android.app.ActivityThread.-wrap2(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1545)
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)
It seems like you've got some misunderstandings about how Fragments and ButterKnife work.
OnCreate is called BEFORE onCreateView in a Fragment. So all your views are null when you're trying to access them in onCreate.
See Fragment Lifecycle:
https://www.tutorialspoint.com/android/images/fragment.jpg
OnCreate is not used that much in Fragments, onCreateView is used more.
Your ButterKnife bind code is also wrong. You're trying to bind the Activity to the views in the Fragment.
See ButterKnife documentation for correct usage: http://jakewharton.github.io/butterknife/
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
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.