This is the register fiile:
The error is when I stored data and after that, I log in when I click on the login button app got crushed.
this is the register section;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText textview1;
EditText textview2;
Button button1;
Button buttonlog;
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textview1 = (EditText)findViewById(R.id.ediuser);
textview2 = (EditText)findViewById(R.id.edipassword);
button1 = (Button)findViewById(R.id.btnreg);
buttonlog = (Button)findViewById(R.id.onlogin);
}
public void onreg(View view){
String username = textview1.getText().toString();
String Password = textview2.getText().toString();
sharedPreferences = getSharedPreferences("Dell", MODE_PRIVATE);
SharedPreferences.Editor editor1 = sharedPreferences.edit();
editor1.putString("username",username);
editor1.putString("password",Password);
editor1.apply();
Toast.makeText(this, "Register Successfully", Toast.LENGTH_SHORT).show();
}
public void onlog(View view){
Intent intent = new Intent(this,login.class);
startActivity(intent);
}
}
this is the login file:
package com.example.newshrd;
import androidx.appcompat.app.AppCompatActivity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class login extends AppCompatActivity {
EditText editText1;
EditText editText2;
Button button2;
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
editText1 = (EditText) findViewById(R.id.userlog);
editText2 = (EditText) findViewById(R.id.passwordlog);
button2 = (Button) findViewById(R.id.btnlog);
sharedPreferences = getSharedPreferences("Dell", MODE_PRIVATE);
}
//this is the login section find error and let me know please
public void onloghere(View view){
String userlog = editText1.getText().toString();
String passlog = editText2.getText().toString();
String userlogin= sharedPreferences.getString("username",null);
String userpaswwords=sharedPreferences.getString("passowrd",null);
if (userlog.contains(userlogin) && passlog.contains(userpaswwords)){
Toast.makeText(this, "Your are in", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(this, "You are not", Toast.LENGTH_SHORT).show();
}
}
}
please, someone, find the error and let me know what I am missing in this code.
It is properly formatted (at least by the preview it is), so how can I fix this? I'm new to Stack Overflow formatting.
When you save, key is "password":
editor1.putString("password",Password);
But when get, you have a typo for the key here "passowrd":
String userpaswwords=sharedPreferences.getString("passowrd",null);
The userpaswwords you get is null (you set SharedPreferences.getString(String key, #Nullable String defValue) defValue value to be null), and here crashes:
passlog.contains(userpaswwords)
Cuz String.contains(CharSequence s) needs the argument to be non-null.
Related
I made a simple app with a LoginActivity. It is crashing and throwing an IllegalArgumentException if the EditText(s) are empty. I use Firebase Authentication. I tried by using assert but still it did not work.
Dummy credentials to reproduce the issue:
Email: abc#abc.com
Password: 123456
StartActivity.java
import android.app.ProgressDialog;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import android.content.Intent;
import android.app.Activity;
import android.content.SharedPreferences;
import java.util.Objects;
public class StartActivity extends AppCompatActivity {
private static final String TAG = "EmailPassword";
private FirebaseAuth mAuth;
private LinearLayout linear1;
private TextInputLayout textinputlayout1;
private TextInputLayout textinputlayout2;
private TextInputEditText edittext1;
private TextInputEditText edittext2;
private Button button1;
private TextView textview1;
private Intent i =new Intent();
private SharedPreferences user;
private ProgressDialog prog;
private OnCompleteListener<AuthResult> _mAuth_sign_in_listener;
private void reload(){}
private void updateUI(FirebaseUser user){}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAuth = FirebaseAuth.getInstance();
setContentView(R.layout.activity_start);
LinearLayout _nav_view = (LinearLayout) findViewById(R.id._nav_view);
TextInputLayout textinputlayout1 = findViewById(R.id.textinputlayout1);
TextInputLayout textinputlayout2 = findViewById(R.id.textinputlayout2);
edittext1 = findViewById(R.id.edittext1);
edittext2 = findViewById(R.id.edittext2);
Button button1 = findViewById(R.id.button1);
TextView textview1 = findViewById(R.id.textview1);
SharedPreferences user = getSharedPreferences("user", Activity.MODE_PRIVATE);
Intent i= new Intent();
textview1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
i.setClass(getApplicationContext(), ForgotPassword.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(i);
}
});
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signIn();
}
});
}
#Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser != null) {
i.setClass(getApplicationContext(), MainActivity.class);
startActivity(i);
}
}
private void signIn(){
Toast.makeText(StartActivity.this,"Button clicked",Toast.LENGTH_SHORT).show();
String email=Objects.requireNonNull(edittext1.getText()).toString();
String password= Objects.requireNonNull(edittext2.getText()).toString();
if(edittext1!=null && edittext2!=null){
final ProgressDialog prog= new ProgressDialog(StartActivity.this);prog.setMax(100);prog.setMessage("Logging in...");prog.setIndeterminate(true);prog.setCancelable(true);
prog.show();
mAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(StartActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
final boolean success= task.isSuccessful();
if(success){
i.setClass(getApplicationContext(),MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
prog.cancel();
}
else{
final String error=task.getException()!=null?task.getException().getMessage():"";
prog.cancel();
Toast.makeText(StartActivity.this,""+error,Toast.LENGTH_LONG).show();
}
}
});
}
else {
prog.cancel();
Toast.makeText(getApplicationContext(),"Email/Password cannot be empty!", Toast.LENGTH_SHORT).show();
}
}
public void onClick(View view) {
}
}
MainActivity.java
package com.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toolbar;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class MainActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
private Toolbar toolbar1;
private Button button2;
private LinearLayout linear2;
private Intent i=new Intent();
private FirebaseUser user;
private TextView textview5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAuth = FirebaseAuth.getInstance();
FirebaseUser user= mAuth.getCurrentUser();
setContentView(R.layout.activity_main);
Toolbar toolbar1=findViewById(R.id.toolbar1);
LinearLayout linear2=findViewById(R.id.linear2);
textview5=findViewById(R.id.textview5);
Button button2=findViewById(R.id.button2);
assert user != null;
textview5.setText(user.getEmail());
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirebaseAuth.getInstance().signOut();
i.setClass(getApplicationContext(),StartActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
}
});
toolbar1.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
}
}
Screenshot of the crash
You are getting IllegalArgumentException because you let the user sign in with empty credentials. This is happening because you checking against nullity the EditText objects and not the actual values:
if(edittext1!=null && edittext2!=null) { ... }
Which is not correct. You should check if the values that are inserted by the user are different than the empty String. The following if statement should do the trick:
if(!email.isEmpty() && !password.isEmpty()) { ... }
It would be also better if you display a message to the user when the email or the password is empty.
I'm trying to open a fragment from another fragment but am getting errors.
The app opens on a home screen with a bottomNav view. Clicking one of the tabs opens a fragment with a login screen for Firebase users. After entering details and pressing login button, it's supposed to verify user and open another fragment.
Everything works fine until you press login.
Below is a working example where both fragments are actually activities and everything works fine.
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
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 implements View.OnClickListener{
public Button btnLogIn;
private EditText inputEmail, inputPassword;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAuth = FirebaseAuth.getInstance();
if (mAuth.getCurrentUser() != null) {
startActivity(new Intent(LoginActivity.this, SecondPage.class));
finish();
}
setContentView(R.layout.activity_login);
btnLogIn = findViewById(R.id.btn_login);
inputEmail = findViewById(R.id.email);
inputPassword = findViewById(R.id.password);
findViewById(R.id.btn_login).setOnClickListener(this);
mAuth = FirebaseAuth.getInstance();
}
#Override
public void onClick(View view){
final String email = inputEmail.getText().toString();
final String password = inputPassword.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
return;
}
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>(){
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
if (password.length() < 6) {
inputPassword.setError(getString(R.string.minimum_password));
} else {
Toast.makeText(LoginActivity.this, getString(R.string.auth_failed), Toast.LENGTH_LONG).show();
}
} else {
Intent intent = new Intent(LoginActivity.this, SecondPage.class);
startActivity(intent);
finish();
}
}
});
}
}
Now here is that same code, except now the LoginActivity is a fragment and needs to open another fragment. This is what gives me errors. I have changed what is needed for the fragment itself.
package com.nikelspot.app;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
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 Fragment implements View.OnClickListener {
public LoginActivity() {
//needed empty constructor
}
public Button btnLogIn;
private EditText inputEmail, inputPassword;
private FirebaseAuth mAuth;
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
mAuth = FirebaseAuth.getInstance();
if (mAuth.getCurrentUser() != null) {
startActivity(new Intent(getActivity(), SecondPage.class));
}
View rootView = inflater.inflate(R.layout.frag_login,
container, false);
btnLogIn = rootView.findViewById(R.id.btn_login);
inputEmail = rootView.findViewById(R.id.email);
inputPassword = rootView.findViewById(R.id.password);
mAuth = FirebaseAuth.getInstance();
rootView.findViewById(R.id.btn_login).setOnClickListener(this);
mAuth = FirebaseAuth.getInstance();
return rootView;
}
#Override
public void onClick(View view){
final String email = inputEmail.getText().toString();
final String password = inputPassword.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(getActivity(), "Enter email address!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getActivity(), "Enter password!", Toast.LENGTH_SHORT).show();
return;
}
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>(){
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
// there was an error
if (password.length() < 6) {
inputPassword.setError(getString(R.string.minimum_password));
}
else {
Toast.makeText(getActivity(), getString(R.string.auth_failed), Toast.LENGTH_LONG).show();
}
}
else {
Intent intent = new Intent(getActivity(), SecondPage.class);
startActivity(intent);
finish();
}
}
});
}
}
In Android Studio, the only thing wrong is the finish() method below is highlighted red. The error message says it cannot be resolved.
else {
Intent intent = new Intent(getActivity(), SecondPage.class);
startActivity(intent);
finish();
}
I know the finish() method cannot be called from within a fragment, but I have tried other solutions online and none of them have worked. This is the closest I can get.
Thanks!
You want the parent activity to open the fragment.
You could achieve this with an interface and callback.
On the incomplete, you initiate a callback to the activity with a method to start the second fragment.
Read this for more information : https://gist.github.com/butelo/8729891
I was wondering if anyone could point me in the right direction with this. I have an SQL Lite database set up that allows the user to add their account details. It also allows to edit the account details when returning to the application.
I really want the application to identify whether the user has previously added an account or is a new user. If they are a new user it will display a register button. If it is a returning user it will forward them onto the main menu activity.
I will attach some code as an example.
Any help would be greatly appreciated!
Register.java
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class Register extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
}
public void btnCreate(View view) {
SQLHelper sqlHelper = new SQLHelper(this);
EditText addName = (EditText) findViewById(R.id.nameText);
EditText edtEmail = (EditText) findViewById(R.id.nameEmail);
EditText edtNumber = (EditText) findViewById(R.id.editNumber);
EditText edtAge = (EditText) findViewById(R.id.editAge);
EditText edtNurse = (EditText) findViewById(R.id.editNurse);
sqlHelper.insert(addName.getText().toString(), edtEmail.getText().toString(), Integer.parseInt(edtNumber.getText().toString()), Integer.parseInt(edtAge.getText().toString()), edtNurse.getText().toString());
Toast.makeText(this, "Account Has Been Created", Toast.LENGTH_SHORT).show();
startActivity(new Intent(Register.this, MainMenu.class));
}
}
Welcome.java:
package my.example.com.mymedicare;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class Welcome extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
};
public void btnRegister(View view) {
startActivity(new Intent(Welcome.this, Register.class));
}
public void btnContinue(View view) {
startActivity(new Intent(Welcome.this, MainMenu.class));
}
}
I am trying to save a ArrayAdapter to shared preferences. I can get one string recovered using this code, but only one, I was not able to recover the entire ArrayAdapter.
package com.example.eduleito.listacompras;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private EditText edt_item;
private Button btn_limpar;
private ImageButton btn_adcionar;
private ListView lst_item;
private ArrayAdapter adp_item;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
edt_item = (EditText) findViewById(R.id.edt_item);
btn_limpar = (Button) findViewById(R.id.btn_limpar);
btn_adcionar = (ImageButton) findViewById(R.id.btn_adcionar);
lst_item = (ListView) findViewById(R.id.lst_item);
btn_adcionar.setOnClickListener(this);
btn_limpar.setOnClickListener(this);
adp_item = new ArrayAdapter(this, android.R.layout.simple_list_item_1);
lst_item.setAdapter(adp_item);
loadSavedPreferences();
}
private void loadSavedPreferences(){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String item = sharedPreferences.getString("storeditem", "");
adp_item.add(item);
}
private void savePreferences(String key, String value){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
#Override
public void onClick(View v) {
if (v == btn_adcionar) {
String item = edt_item.getText().toString();
adp_item.add(item);
savePreferences("storeditem", item);
edt_item.setText("");
} else if (v == btn_limpar) {
adp_item.clear();
}
}
}
Google:
Storage Options on developer.android.com
The SharedPreferences class provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types.
The user should enter a phone number in "edixxx" EditText , I get the number and try to send "msghoshharon" String to it, but when I tap on button I get this Exception: " Invalid destinationAdress"
Any idea? I can't figure out what is the problem with this code! :(
Looking for help.
package com.sms.validation;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class acadmin extends Activity {
private SharedPreferences sphala;
public String enterd;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tanzadmin);
final String msghoshharon="admin123456";
sphala = getSharedPreferences("myPrefs",
MODE_PRIVATE);
final String number = (sphala.getString("number", ""));
EditText text = (EditText)findViewById(R.id.edixxx);
enterd = text.getText().toString();
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
sendSMS(enterd, msghoshharon);
}
});
}
public void sendSMS(String enterd, String msghoshharon) {
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(enterd, null, msghoshharon, null, null);
Toast.makeText(getApplicationContext(), "has been sent",
Toast.LENGTH_LONG).show();
} catch (Exception ex) {
Toast.makeText(getApplicationContext(), ex.getMessage().toString(),
Toast.LENGTH_LONG).show();
ex.printStackTrace();
}
}
}
Try this
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class acadmin extends AppCompatActivity implements View.OnClickListener {
private SharedPreferences sphala;
public String enterd;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tanzadmin);
final String msghoshharon="admin123456";
sphala = getSharedPreferences("myPrefs",
MODE_PRIVATE);
final String number = (sphala.getString("number", ""));
EditText text = (EditText)findViewById(R.id.edixxx);
final Button button = (Button) findViewById(R.id.button);
}
public void sendSMS(String enterd, String msghoshharon) {
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(enterd, null, msghoshharon, null, null);
Toast.makeText(getApplicationContext(), "has been sent",
Toast.LENGTH_LONG).show();
} catch (Exception ex) {
Toast.makeText(getApplicationContext(), ex.getMessage().toString(),
Toast.LENGTH_LONG).show();
ex.printStackTrace();
}
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.button:
enterd = text.getText().toString();
sendSMS(enterd, msghoshharon);
break;
}
}
}