I'm having a problem when trying to get data from "EditText" in Android.
The app crashes immediately when I try to assign "EditText" value to a String variable (I used toString() method).
The problem is in the two lines after the onCreate method.
Here is my code:
public class MainActivity extends AppCompatActivity {
EditText em;
EditText pw;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText em = (EditText) findViewById(R.id.email1);
EditText pw = (EditText) findViewById(R.id.password1);
mAuth = FirebaseAuth.getInstance();
}
// When I remove those two lines the app runs normally
String email = em.getText().toString();
String password = pw.getText().toString();
void login(View v){
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(MainActivity.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
FirebaseUser user = mAuth.getCurrentUser();
String Logged = user.getEmail().toString();
Intent intent = new Intent(MainActivity.this, afterLogin.class);
intent.putExtra("email", Logged);
startActivity(intent);
finish();
} else {
// If sign in fails, display a message to the user.
Toast.makeText(MainActivity.this, "Wrong email/password.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
Why are these statements outside?
String email = em.getText().toString();
String password = pw.getText().toString();
You are trying to assign these before onCreate was executed.
Extracting data at class level is similar to doing this in constructor.
Think about it.. constructor runs first, then the onCreate executes.
So, you are essentially running
null.getText().toString(); //because em and pw were still null
Instead of doing this, please move these statements to login method or any other event method you might want to create.
You're declaring and initializing String email and String password before onCreate so the EditTexts are null. Move the String initialization into your onCreate like this:
EditText em;
EditText pw;
String email;
String password;
onCreate {
EditText em = findViewById(R.id.email1);
EditText pw = findViewById(R.id.password1);
email = em.getText().toString;
password = pw.getText().toString;
}
Of course, the EditTexts will probably be empty at that point, so you'll probably want to get their values later, or use a TextWatcher.
Related
In the code below (log in code), I have one button that if it clicked, it will start two intent. One intent is to use to open A class and the other is to use to send a string value to B class. But when the button clicked, the second intent not just sending the string value but also open the B class. The code supposedly to just send the string value to B class and open A class.
How to fix this?
package com.example.project;
public class login extends AppCompatActivity {
DatabaseReference reff;
EditText kode, pass;
Button masuk;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
FirebaseApp.initializeApp(this);
kode = (EditText)findViewById(R.id.kode);
pass = (EditText)findViewById(R.id.pass);
masuk = (Button)findViewById(R.id.masuk);
masuk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(TextUtils.isEmpty(kode.getText().toString()) || TextUtils.isEmpty(pass.getText().toString())){
Toast.makeText(login.this, "isi kode alat atau password", Toast.LENGTH_LONG).show();
}
else {
final String value = kode.getText().toString().trim();
reff = FirebaseDatabase.getInstance().getReference().child(value);
final String password = pass.getText().toString().trim();
// Read from the database
reff.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
String passin = dataSnapshot.child("pass").getValue().toString();
if (passin.equals(password)){
Intent intent = new Intent(login.this, MainActivity.class);
startActivity(intent);
Intent send = new Intent(login.this, addmember.class);
send.putExtra("kode", value);
startActivity(send);
}
else if(!passin.equals(password)){
Toast.makeText(login.this, "password salah", Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
}
});
}
}
});
}
Here, you can't start activity because you are trying to start two activities at same time. This is not possible and if possible this approach is not too good. In safe side, you can use EventBus library that used for pushing event as data and subscriber that receive that data. This is the right way to do what you want here.
I am building an app where you can upload images to my company server
My problem is that I have a login screen with Email, Password and Client ID(in LoginActivity)
Now The data you enter there is passed to another Activity(CameraActivity) and that is used to build a URL with Uri.Builder.
The data is being saved within the edittext boxes BUT it is only being passed(using intents) to the other activity on the button click so, you have to go back to the login screen and click the button to reSubmit the data for every upload and everytime you start the app(The Data is stored within the textboxes but it is not being passed to the other activity without the button click), for the URI.Builder to work and give the entered information to the URL.
I want the client to enter that information ONCE and click the Button ONCE and then it is stored and used everytime regardless of the app being exited etc.
Login Activity, This activity has the edittext boxes and the entered information is being saved but not passed to the other activity without the button click
public class LoginActivity extends AppCompatActivity {
String ID = "id";
String EMAIL = "email";
String PASS = "pass";
private SharedPreferences mPreference;
EditText email, password, id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
email=findViewById(R.id.emailtext);
password=findViewById(R.id.pwdtext);
id=findViewById(R.id.clientid);
Button loginBtn=findViewById(R.id.button);
mPreference = PreferenceManager.getDefaultSharedPreferences(this);
id.setText(mPreference.getString(ID, ""));
email.setText(mPreference.getString(EMAIL, ""));
password.setText(mPreference.getString(PASS, ""));
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EMAIL =email.getText().toString();
PASS =password.getText().toString();
ID =id.getText().toString();
mPreference.edit().putString(ID,ID).apply();
mPreference.edit().putString(EMAIL, EMAIL).apply();
mPreference.edit().putString(PASS, PASS).apply();
Intent intent=new Intent(LoginActivity.this,
CameraActivity.class);
intent.putExtra("clientId", ID);
intent.putExtra("email", EMAIL);
intent.putExtra("password", PASS);
startActivity(intent);
}
});
}
}
As suggested in the question comment, SharedPreferences is a good option.
SharedPreferences getPreferences(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context);
}
void setEmail(Context context, String email) {
SharedPreferences.Editor editor = getPreferences(context).edit();
editor.putString("EMAIL", email);
editor.apply();
}
String getEmail(Context context) {
return getPreferences(context).getString("EMAIL", "");
}
Above is an example of how you can put things and retrieve things from the shared preferences. Since you have more than an email to store (user ID, etc...) you could even store an object as a gson so you would have to call only one function. But of course this is your call.
You can start the CameraActivity if data exist in SharedPreferences.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
email=findViewById(R.id.emailtext);
password=findViewById(R.id.pwdtext);
id=findViewById(R.id.clientid);
Button loginBtn=findViewById(R.id.button);
mPreference = PreferenceManager.getDefaultSharedPreferences(this);
//Check if data exist
if(mPreference.contain(ID))
{
Intent intent=new Intent(LoginActivity.this,
CameraActivity.class);
intent.putExtra("clientId", mPreference.getString(ID, ""));
intent.putExtra("email", mPreference.getString(EMAIL, ""));
intent.putExtra("password", mPreference.getString(PASS, ""));
startActivity(intent);
}
//Rest of the code
}
Cheers :)
My Activity Login has edittext's value first entered by username and second value by password. I'm trying to pass this values of editText from Activity Class to nonActivityClass(Java Class).
Does exist any way to do this?
In MyLoginAcitivy:
yourButtonLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String username = yourEditTextUsername.getText().toString();
String password = yourEditTextPassword.getText().toString();
Intent intent = new Intent(this,nonActivityClass.class);
intent.putExtra("username",username);
intent.putExtra("password",password);
startActivity(intent);
}
});
In nonActivityClass:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.YOUR_LAY_OUT);
Intent intent = getIntent();
if(intent != null){
String username = intent.getStringExtra("username");
String password = intent.getStringExtra("password");
}
}
I do not know why you want to do that. But you can do this using Preferences.
At your Activity save your data to Pref and load them at your Class
It depends on what you want to do with the data, I'm not sure what your issue is. You can use a Class with a Static method which can accept username and passwords then do your checking there or what ever operation you want after which you can return the result. There are other options to try out. Just like database classes which are not 'Activity classes', you can also pass values to them.
As in any normal class in Java with constructors:
User newuser = new User(uname, pwd); // in your activity
// in your class
public User(String uname,String pwd){
this.uname = uname;
this.pwd = pwd;
}
Please also consider to learn java basics before use it in android.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
It's been a month since I've kicked off with android studio, at this time I'm stuck at a point where I have to pass a set of <EditText/> values from MainActivity to UpdateActivity and then send those values to the Sqlite database for updating a table.
What I have accomplished:
Successfully sending values from MainActivity's <EditText/> to UpdateActivity's <EditText/>
How I have done that from MainActivity:
public class MainActivity extends AppCompatActivity {
DatabaseHelper myDb;
EditText editName, editSurname, editMarks;
Button btnUpdate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDb = new DatabaseHelper(this);
editName = (EditText) findViewById(R.id.UpdName);
editSurname = (EditText) findViewById(R.id.editTextSurname);
editMarks = (EditText) findViewById(R.id.UpdMarks);
btnUpdate = (Button)findViewById(R.id.btnUpdate);
btnUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String MainName = editName.getText().toString();
String MainSurname = editSurname.getText().toString();
String MainMarks = editMarks.getText().toString();
Intent UpdateAct = new Intent(MainActivity.this, UpdateActivity.class);
UpdateAct.putExtra("Name", MainName);
UpdateAct.putExtra("SurName",MainSurname );
UpdateAct.putExtra("Marks", MainMarks);
startActivity(UpdateAct);
}
});
}
Then inside the UpdateActivity:
public class UpdateActivity extends AppCompatActivity {
DatabaseHelper myDb;
Button btnUpd;
EditText editTextId, editUpdtName, editUpdSurname, editUpdMarks;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update);
Intent getData = getIntent();
String Name = getData.getStringExtra("Name");
String SurName = getData.getStringExtra("SurName");
String Marks = getData.getStringExtra("Marks");
editTextId = (EditText)findViewById(R.id.editTextID);
editUpdtName = (EditText)findViewById(R.id.UpdName);
editUpdSurname = (EditText)findViewById(R.id.UpdSurname);
editUpdMarks = (EditText)findViewById(R.id.UpdMarks);
btnUpd = (Button)findViewById(R.Id.btnUpd);
editUpdtName.setText(Name);
editUpdSurname.setText(SurName);
editUpdMarks.setText(Marks);
}
What I'm stuck at is to send these values to a function named updateData();
For that I have tried to use the values from MainActivity directly to UpdateActivity but failed, then I tried to cast those <EditText/> and use it inside the function but failed again.
Inside my UpdateActivity:
..//
editUpdtName.setText(Name);
editUpdSurname.setText(SurName);
editUpdMarks.setText(Marks);
//updateData(Name, SurName, Marks);
updateData();
}
//function definiton
// public void updateData(final String Name, final String SurName, final String Marks)
public void updateData()
{
btnUpd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// boolean isUpdated = myDb.updateData(editTextId.getText().toString(), Name,SurName, Marks);
boolean isUpdated = myDb.updateData(editTextId.getText().toString(), editUpdtName.getText().toString(),
editUpdSurname.getText().toString(), editUpdMarks.getText().toString());
if(isUpdated == true){
Toast.makeText(UpdateActivity.this, "Data Updated Successfully!", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(UpdateActivity.this, "Data NOT Updated!", Toast.LENGTH_SHORT).show();
}
}
});
}
}
The app crashes everytime the function updateData(); is called, to ensure that is the real cause I have even commented and also tried putting it in a handler to run it after 3000ms, as expcted it crashed after the time period.
Solved it by initializing the db.
myDb = new DatabaseHelper(this);
You forgot to initialize myDb.
Initialize it in your onCreate() method:
myDb = new DatabaseHelper(this);
Why not just pass the values to updateData()?
editUpdtName.setText(Name);
editUpdSurname.setText(SurName);
editUpdMarks.setText(Marks);
updateData(Name, SurName, Marks);
have you initialized btnUpd? I can not see this in your onCreate()
btnUpd = (Button) findViewById(...)
So to begin with, I know I can easily get a source code for the login screen, and I may even do that. But the problem here is that I've been trying to figure out my mistake on that code for like 2 days, so I got "a little" frustrated. There it is:
I'm trying to integrate a login screen to my application, and put a single condition which lets only a specific e-mail and password to login to the app. Problem is probably in if-else conditions of onCreate method. If works well, I can login using that specific e-mail and password, yet when I enter an invalid information, application freezes and crashes after a point. I don't even get the error message I wrote. Note that I already tried to use boolean x = false/true for the while loop, still didn't work. Would really appreciate any help on that. Thanks in advance.
public Button loginButton;
private EditText emailText;
private EditText passwordText;
private TextView errorView;
private String x = "go";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loginButton = (Button) findViewById(R.id.loginButton);
errorView = (TextView) findViewById(R.id.errorView);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
while (x.equals("go")) {
emailText = (EditText) findViewById(R.id.emailText);
passwordText = (EditText) findViewById(R.id.passwordText);
if (emailText.getText().toString().equals("meric.erler#metu.edu.tr")
&& passwordText.getText().toString().equals("meric1234")) {
x = "return";
} else {
errorView.setText("Invalid E-mail or Password.");
}
x.equals("go");
}
String email = emailText.getText().toString();
startData(email);
}
});
}
//probably irrelevant after this point
public void startData(String email) {
Intent intent = new Intent(LoginActivity.this, DataActivity.class);
intent.putExtra("email", email);
startActivity(intent);
}
This should work, but I haven't compiled it to test it.
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
emailText = (EditText) findViewById(R.id.emailText);
passwordText = (EditText) findViewById(R.id.passwordText);
String email = emailText.getText().toString();
if (email.equals("meric.erler#metu.edu.tr")
&& passwordText.getText().toString().equals("meric1234")) {
startData(email);
} else {
errorView.setText("Invalid E-mail or Password.");
}
}
});