Некоторое время назад у меня был основной экран входа в систему / регистрации и рабочий ящик, но когда я пытался реализовать базу данных элементов, какой класс при этом я не создавал и не вызывал нигде, все равно приложение перестало работать, оноОткрываясь и быстро закрываясь, мобильное устройство сообщало бы, что «приложение представляет постоянные сбои» даже без изменения бизнес-правил или модели.
Это моя операция запуска MainActivity, которая представляет собой вход в систему
package com.example.appteste;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import com.example.appteste.ui.login.LoginActivity;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.UserProfileChangeRequest;
import java.util.ArrayList;
import lecho.lib.hellocharts.model.PieChartData;
import static android.content.ContentValues.TAG;
public class MainActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
// private PieChart pieChart;w
final Button signUpButton = findViewById(R.id.createUserButton);
final EditText displayNameEditText = findViewById(R.id.name_field);
final EditText usernameEditText = findViewById(R.id.mail_field);
final EditText passwordEditText = findViewById(R.id.password_field);
final Button login = findViewById(R.id.login);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// sets the .xml current view
setContentView(R.layout.activity_sign_in);
// pie start
// pieChart = findViewById(R.id0
// pie end
// getEntries();
// declarations
mAuth = FirebaseAuth.getInstance();
signUpButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// calls createAccount
createAccount(displayNameEditText.getText().toString(), usernameEditText.getText().toString(), passwordEditText.getText().toString());
// logs in the system that
Log.v("signUp", "UserSignedUp:"+ usernameEditText.getText().toString() + "password: " + passwordEditText.getText().toString());
// Logs in the created user
mAuth.signInWithEmailAndPassword(usernameEditText.getText().toString(),
passwordEditText.getText().toString())
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// startActivity(new Intent(MainActivity.this, MenuActivity.class));
startActivity(new Intent(MainActivity.this, HomeActivity.class));
} else {
Toast.makeText(MainActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
}
}
});
// supposed to show a welcome message
// updateUiWithUser(mAuth.getCurrentUser());
// shows message to user? maybe?
Toast.makeText(MainActivity.this, "Register Succeed.",
Toast.LENGTH_SHORT).show();
}
});
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// change to Login screen
startActivity(new Intent(MainActivity.this, LoginActivity.class));
}
});
}
public void createAccount(final String displayName, String email, String password) {
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "createUserWithEmail:success");
FirebaseUser user = mAuth.getCurrentUser();
// sets the display Name for the user
user.updateProfile(new UserProfileChangeRequest.Builder().setDisplayName(displayName).build());
startActivity(new Intent(MainActivity.this, LoginActivity.class));
updateUiWithUser();
} else {
// If sign in fails, display a mcessage to the user.
Log.w(TAG, "createUserWithEmail:failure", task.getException());
Toast.makeText(MainActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
// updateUiWithUser(null);
}
// TODO discover what to add here
}
});
}
private void updateUiWithUser(FirebaseUser model) {
String welcome = getString(R.string.welcome) + model.getDisplayName();
// TODO : initiate successful logged in experience
Toast.makeText(getApplicationContext(), welcome, Toast.LENGTH_LONG).show();
}
private void updateUiWithUser() {
String welcome = getString(R.string.welcome) + mAuth.getCurrentUser().getDisplayName();
// TODO : initiate successful logged in experience
Toast.makeText(getApplicationContext(), welcome, Toast.LENGTH_LONG).show();
}
}
LoginActivity (куда идет MainActivity после регистрации)
package com.example.appteste.ui.login;
import android.app.Activity;
import androidx.annotation.NonNull;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.appcompat.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.appteste.HomeActivity;
import com.example.appteste.MenuActivity;
import com.example.appteste.R;
import com.example.appteste.ui.login.LoginViewModel;
import com.example.appteste.ui.login.LoginViewModelFactory;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import static android.content.ContentValues.TAG;
public class LoginActivity extends AppCompatActivity {
private LoginViewModel loginViewModel;
private FirebaseAuth mAuth;
private LoginResult login;
public LoginResult getLogin() {
return login;
}
public void setLogin(LoginResult login) {
this.login = login;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loginViewModel = ViewModelProviders.of(this, new LoginViewModelFactory())
.get(LoginViewModel.class);
final EditText usernameEditText = findViewById(R.id.username);
final EditText passwordEditText = findViewById(R.id.password);
final Button loginButton = findViewById(R.id.login);
final ProgressBar loadingProgressBar = findViewById(R.id.loading);
mAuth = FirebaseAuth.getInstance();
loginViewModel.getLoginFormState().observe(this, new Observer<LoginFormState>() {
@Override
public void onChanged(@Nullable LoginFormState loginFormState) {
if (loginFormState == null) {
return;
}
loginButton.setEnabled(loginFormState.isDataValid());
if (loginFormState.getUsernameError() != null) {
usernameEditText.setError(getString(loginFormState.getUsernameError()));
}
if (loginFormState.getPasswordError() != null) {
passwordEditText.setError(getString(loginFormState.getPasswordError()));
}
}
});
loginViewModel.getLoginResult().observe(this, new Observer<LoginResult>() {
@Override
public void onChanged(@Nullable LoginResult loginResult) {
if (loginResult == null) {
return;
}
loadingProgressBar.setVisibility(View.GONE);
if (loginResult.getError() != null) {
setLogin(loginResult);
showLoginFailed(loginResult.getError());
}
if (loginResult.getSuccess() != null) {
// updateUiWithUser(loginResult.getSuccess());
}
setResult(Activity.RESULT_OK);
//Complete and destroy login activity once successful
finish();
}
});
TextWatcher afterTextChangedListener = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// ignore
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// ignore
}
@Override
public void afterTextChanged(Editable s) {
loginViewModel.loginDataChanged(usernameEditText.getText().toString(),
passwordEditText.getText().toString());
}
};
usernameEditText.addTextChangedListener(afterTextChangedListener);
passwordEditText.addTextChangedListener(afterTextChangedListener);
passwordEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
loginViewModel.login(usernameEditText.getText().toString(),
passwordEditText.getText().toString());
}
return false;
}
});
loginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mAuth.signInWithEmailAndPassword(usernameEditText.getText().toString(),
passwordEditText.getText().toString())
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
updateUiWithUser(mAuth.getCurrentUser());
// startActivity(new Intent(LoginActivity.this, MenuActivity.class));
startActivity(new Intent(LoginActivity.this, HomeActivity.class));
} else {
Toast.makeText(LoginActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
});
}
// [START on_start_check_user]
@Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
// updateUiWithUser(getLogin().getSuccess());
updateUiWithUser(currentUser);
}
// [END on_start_check_user]
private void updateUiWithUser(FirebaseUser user) {
String welcome = getString(R.string.welcome) + user.getDisplayName();
// TODO : initiate successful logged in experience
Toast.makeText(getApplicationContext(), welcome, Toast.LENGTH_LONG).show();
}
private void showLoginFailed(@StringRes Integer errorString) {
Toast.makeText(getApplicationContext(), errorString, Toast.LENGTH_SHORT).show();
}
}
мой logcat:
2019-10-24 16:39:39.723 711-711/? E/Zygote: isWhitelistProcess - Process is Whitelisted
2019-10-24 16:39:39.723 711-711/? E/Zygote: accessInfo : 1
2019-10-24 16:39:40.209 711-711/com.example.appteste E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.appteste, PID: 711
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.appteste/com.example.appteste.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3019)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3256)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1947)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7037)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:164)
at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:157)
at android.content.Context.obtainStyledAttributes(Context.java:677)
at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:692)
at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:659)
at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:479)
at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:214)
at com.example.appteste.MainActivity.<init>(MainActivity.java:42)
at java.lang.Class.newInstance(Native Method)
at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:69)
at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:41)
at android.app.Instrumentation.newActivity(Instrumentation.java:1215)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3007)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3256)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1947)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7037)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)