EditText data not being passed over without button click - java

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 :)

Related

Android Save Contact by click button event

I want to make a button that when its clicked it creates and saves all the person's information such as name, email and phone # into the contact list without opening the contact form or hitting save, code is in Java.
EditText name;
EditText phone;
Button addContact;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
name = findViewById(R.id.editTextTextPersonName);
phone = findViewById(R.id.editTextPhone2);
addContact = findViewById(R.id.buttonDone);
addContact.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
if(!name.getText().toString().isEmpty() && !phone.getText().toString().isEmpty()){
Intent intent = new Intent(Intent.ACTION_INSERT);
intent.setType(ContactsContract.RawContacts.CONTENT_TYPE);
intent.putExtra(ContactsContract.Intents.Insert.NAME, name.getText().toString());
intent.putExtra(ContactsContract.Intents.Insert.PHONE, phone.getText().toString());
if(intent.resolveActivity(getPackageManager()) !=null){
startActivity(intent);
}else{
Toast.makeText(MainActivity2.this, "Try again", Toast.LENGTH_SHORT).show();
}
}else{
Toast.makeText(MainActivity2.this, "Try again", Toast.LENGTH_LONG).show();
}
}
}
);
}
}
You'll need to use the ContactsProvider. You'll see how to use it and some examples.

How to make two "intent" in android studio code not processing at the same time?

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.

How can i pass editTexts from Activity class to nonActivity

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.

Password - String comparison

My app consists of an Activity, which asks for a String password, in order to launch a second Activity. I am using an EditText for input and a Button for verification. If the Button is pressed, the app should check whether the inserted password, (let's assume it's "ABC") matches the password in the array. If not, set the inserted password to a red color.
public class Login extends AppCompatActivity{
Button mButton;
EditText mEdit;
String [] mArray;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
mButton = (Button)findViewById(R.id.anmelden_button);
mEdit = (EditText)findViewById(R.id.password);
mButton.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
Log.v("EditText", mEdit.getText().toString());
}
});
String [] mArray = getResources().getStringArray(R.array.password);
if (mArray.equals(mEdit.getText().toString())){
Intent intent = new Intent(this, secondactivity.class);
startActivity(intent);
}else{
mEdit.setTextColor(Color.RED);
}
}
}
My problem is, that when I insert "ABC" and press the Button, nothing happens at all.
You need to loop through all the passwords first, then check to see if you found what you wanted.
Your onclick listener should something look like this:
mButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
String [] mArray = getResources().getStringArray(R.array.password);
// loop to check all passwords
for (String s : mArray) {
if (s.equals(mEdit.getText().toString())) {
// found the password
Intent intent = new Intent(this, secondactivity.class);
startActivity(intent);
return;
}
}
mEdit.setTextColor(Color.RED);
}
});
Put your password checking code inside the onClickListener
Loop through each element of the array, checking it against the value in your EditText

Issue with shared

I am creating an application and am using shared prefs. The first two activities are a login screen and a reset password screen.
The login username and password initially are "user".When the user logs on, they are redirected to the reset password activity where they must change the password by entering a password, confirm it, and also enter the original password (user).
The new password will be saved to shared preferences thus overwriting the original password.
My issue is that when i run the app on the emulator it crashes every time irrespective of what username and password i use.. Here is the code so far:
LOGIN ACTIVITY
public class SignIn extends Activity {
static final String MY_PREFS = "Prefs";
static final String SAVED_PASSWORD = "Password";
// Object used for Shared Preferences
SharedPreferences appPrefs;
// First method called when the activity is opened
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
// get Shared Preferences for this application
SharedPreferences appPrefs = getSharedPreferences(SAVED_PASSWORD, 0);
}
// Called when the "LOGIN" button is pressed
public void loginBtnClicked(View v){
// The username and password that is to be used on initial use of the application
String userName = "user";
String original_password = "user";
// Get the settings for the password string from the prefs and assign a name
String existingPassword = appPrefs.getString(SAVED_PASSWORD,null);
// Widgets used during the login phase
EditText usernameField = (EditText)findViewById(R.id.editText_username);
EditText passwordField = (EditText)findViewById(R.id.editText_password);
Button reset =(Button)findViewById(R.id.goToReset);
Button next =(Button)findViewById(R.id.next);
// Get the text from the editText fields,convert to a string, and assign a name
String name = usernameField.getText().toString();
String pass = passwordField.getText().toString();
// If either field is empty inform user and return to give them another go
if (name.equals(null)|| pass.equals(null)){
Toast.makeText(this,"ERROR!!, all fields must be filled",Toast.LENGTH_SHORT).show();
return;
}
//========================================
// VALIDATION OF LOGIN INFORMATION SUBMITTED
//========================================
// If there NOT information saved to preferences.
if (existingPassword.equals(null)){
// IF the username and password are "USER"
if(name.equals(userName) && pass.equals(original_password)){
// Create an intent to open the next window
Intent reset_intent = new Intent(this,ResetPassword.class);
// Start the new activity
startActivity(reset_intent);
}
}
//If there IS information saved to preferences.
else if (existingPassword!=null){
//IF the username is "USER"...
if(name.equals(userName) ){
// If the password is what is saved to preferences.
if(pass.equals(existingPassword)){
// Make buttons visible for user choice
reset.setVisibility(View.VISIBLE);
next.setVisibility(View.VISIBLE);
}
else{
// Display a toast pop-up to show the text from the intent
Toast.makeText(this,"ERROR!!,password incorrect",Toast.LENGTH_SHORT).show();
}
}
else{
// Display a toast pop-up to show the text from the intent
Toast.makeText(this,"ERROR!!,username incorrect",Toast.LENGTH_SHORT).show();
}
}
}
// Called when the "GO TO RESET" button is pressed
public void ResetBtnClicked(View v){
// Create an intent to open the next window
Intent reset_intent = new Intent(this,ResetPassword.class);
// Start the new activity
startActivity(reset_intent);
}
//Called when the "NEXT" button is pressed
public void onNextBtnClicked (){
// Create an intent to open the next window
Intent personal_intent = new Intent(this,PersonalDetails.class);
// Start the new activity
startActivity(personal_intent);
}
}
public class ResetPassword extends Activity {
public static final String MY_PREFS = "Prefs";
public static final String SAVED_PASSWORD = "Password";
// for shared preferences
SharedPreferences appPrefs;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reset_password);
// get shared prefs for this application
SharedPreferences appPrefs = getSharedPreferences(SAVED_PASSWORD, 0);
}
//Save the new password
public void resetBtnClicked(View v){
// Widgets used during password reset.
EditText newPassword = (EditText)findViewById(R.id.editText_newPassword);
EditText confirmPassword = (EditText)findViewById(R.id.editText_retypePassword);
EditText currentPassword = (EditText)findViewById(R.id.editText_existingPassword);
// Get the text from the editText fields,convert to a string, and assign a name
String newPass = newPassword.getText().toString();
String confirmPass = confirmPassword.getText().toString();
String currentPass = currentPassword.getText().toString();
// get the settings for the password string from the prefs
String existingPassword = appPrefs.getString(SAVED_PASSWORD,null);
//========================================
// VALIDATION OF PASSWORD INFORMATION SUBMITTED
//========================================
// if the current password submitted is the same as the saved password
if(currentPass.equals(existingPassword)){
//if the new password is the same in both the new and re-enter fields
if(newPass.equals(confirmPass)){
//save the preferences
//get the editor for prefs
Editor prefsEditor = appPrefs.edit();
// update the prefs with the new settings
prefsEditor.putString(SAVED_PASSWORD,newPass);
prefsEditor.commit();
// Create an intent to open the next window
Intent personal_intent = new Intent(this,PersonalDetails.class);
// display a toast pop-up to show the text from the intent
Toast.makeText(this,"New password saved",Toast.LENGTH_SHORT).show();
// Start the new activity
startActivity(personal_intent);
}
// If the passwords do not match
else {
// display a toast pop-up to show the text from the intent
Toast.makeText(this,"Passwords do not match!!",Toast.LENGTH_SHORT).show();
}
}
// if the current password is incorrect
else{
// display a toast pop-up to show the text from the intent
Toast.makeText(this,"Incorrect password used!!",Toast.LENGTH_SHORT).show();
}
// If there is no password saved to prefs.
if (existingPassword.equals(null)){
if(newPass.equals(confirmPass)){
//save the preferences
//get the editor for prefs
Editor prefsEditor = appPrefs.edit();
// update the prefs with the new settings
prefsEditor.putString(SAVED_PASSWORD,newPass);
prefsEditor.commit();
// Create an intent to open the next window
Intent personal_intent = new Intent(this,PersonalDetails.class);
// display a toast pop-up to show the text from the intent
Toast.makeText(this,"New password saved",Toast.LENGTH_SHORT).show();
// Start the new activity
startActivity(personal_intent);
}
else{
// display a toast pop-up to show the text from the intent
Toast.makeText(this,"Passwords do not match!!",Toast.LENGTH_SHORT).show();
}
}
}
}
Any help would be greatly appreciated guys.
By looking at your code app is crashing at these lines bcz you are creating/init a local variable with same instance variable name ie. appPrefs and instance variable appPrefs still null (default value) 1. SignIn Activity
String existingPassword = appPrefs.getString(SAVED_PASSWORD,null);
2. ResetPassword Activity
String existingPassword = appPrefs.getString(SAVED_PASSWORD,null);
Reason :
For both activity you are not initializing the appPrefs object, which is a instance variable
Solution :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reset_password);
// get shared prefs for this application
//your code creates a new local variable with same instance variable name ie. appPrefs
//SharedPreferences appPrefs = getSharedPreferences(SAVED_PASSWORD, 0);
//changes : init instance variable
appPrefs = getSharedPreferences(SAVED_PASSWORD, 0);
}

Categories