I would like to have a Checkbox button to Remember User Id and Password. Can anyone please guide me in the right direction as to how to get it started?
I just built this into my app, here's the basic code and some explanation:
Basically the key here is SharedPreferences. You'll setup a SharedPreferences object and store your username and password after the user has entered them. Then, when they run the application again, the preferences will have their data stored and will then repopulate the login fields.
LoginActivity.java
package com.realsimpleapps.LoginTesting;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
public class LoginActivity extends Activity implements OnClickListener {
private String username,password;
private Button ok;
private EditText editTextUsername,editTextPassword;
private CheckBox saveLoginCheckBox;
private SharedPreferences loginPreferences;
private SharedPreferences.Editor loginPrefsEditor;
private Boolean saveLogin;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
ok = (Button)findViewById(R.id.buttonLogin);
ok.setOnClickListener(this);
editTextUsername = (EditText)findViewById(R.id.editTextUsername);
editTextPassword = (EditText)findViewById(R.id.editTextPassword);
saveLoginCheckBox = (CheckBox)findViewById(R.id.saveLoginCheckBox);
loginPreferences = getSharedPreferences("loginPrefs", MODE_PRIVATE);
loginPrefsEditor = loginPreferences.edit();
saveLogin = loginPreferences.getBoolean("saveLogin", false);
if (saveLogin == true) {
editTextUsername.setText(loginPreferences.getString("username", ""));
editTextPassword.setText(loginPreferences.getString("password", ""));
saveLoginCheckBox.setChecked(true);
}
}
public void onClick(View view) {
if (view == ok) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editTextUsername.getWindowToken(), 0);
username = editTextUsername.getText().toString();
password = editTextPassword.getText().toString();
if (saveLoginCheckBox.isChecked()) {
loginPrefsEditor.putBoolean("saveLogin", true);
loginPrefsEditor.putString("username", username);
loginPrefsEditor.putString("password", password);
loginPrefsEditor.commit();
} else {
loginPrefsEditor.clear();
loginPrefsEditor.commit();
}
doSomethingElse();
}
}
public void doSomethingElse() {
startActivity(new Intent(LoginActivity.this, MainActivity.class));
LoginActivity.this.finish();
}
}
The method at end, doSomethingElse() is your placeholder to go to the next step for your application. My doSomethingElse() method simply loads another activity.
Here's a basic xml file for the login page:
login.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#000"
android:padding="10dp" >
<EditText
android:id="#+id/editTextUsername"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/imageView1"
android:hint="Username"
android:inputType="textNoSuggestions"
android:imeOptions="actionNext" />
<EditText
android:id="#+id/editTextPassword"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/editTextUsername"
android:hint="Password"
android:inputType="textPassword"
android:imeOptions="actionDone" />
<CheckBox
android:id="#+id/saveLoginCheckBox"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/editTextPassword"
android:text="Save Login?"
android:textColor="#FFF" />
<Button
android:id="#+id/buttonLogin"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/saveLoginCheckBox"
android:layout_marginTop="40dp"
android:text="Login" />
</RelativeLayout>
IMPORTANT: You'll likely want to encrypt the password before storing it in SharedPreferences. Details for that are beyond the scope of this question, but here is the code I used to do that: http://www.androidsnippets.com/encryptdecrypt-strings. You'll have to come up with some kind of key schema too.
This code has been tested on Android 2.1, SDK 7. Let me know how it works for you.
David
Seeing this answer i will consider what i want to do with this data. If you want to persist this data in local storage or doing this asyncronously.
loginPrefsEditor.commit();
Persists your data in local storage and block your UI Main Thread.
or
loginPrefsEditor.apply();
In this case makes an asyncronous work and it doesn´t block you main thread.
Related
I was creating an app then a question come out:
how can i keep user in activity?
I've put two editTexts with input of int.
i want user be kept in activity until he/she puts valid numbers in edittexts.
any ideas?
The solution is very simple all you need to do is get the string values from the edit text box and have a condition in your setonclicklistener that checks the strings if they match to a certain value, if yes the intent from current activity will take you to next if not it will show an error on the edit text box (by using .setError()) and return.
Here is the Java Class Code:
package com.example.text_to_speech;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
public class ActivityA extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity);
EditText editText1,editText2;
Button button;
editText1=findViewById(R.id.ed1);
editText2=findViewById(R.id.ed2);
button=findViewById(R.id.check_input);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!editText1.getText().toString().equals("Don"))
{
Toast.makeText(ActivityA.this, "You Can't Leave this Activity, Input Correct Fields", Toast.LENGTH_SHORT).show();
editText1.setError("Input Correct values");
return;
}
if(!editText1.getText().toString().equals("Tom"))
{
Toast.makeText(ActivityA.this, "You Can't Leave this Activity, Input Correct Fields", Toast.LENGTH_SHORT).show();
editText2.setError("Input Correct values");
return;
}
Intent intent=new Intent(ActivityA.this,MainActivity.class);
startActivity(intent);
}
});
}
}
XML Code:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ActivityA">
<EditText
android:layout_margin="10dp"
android:id="#+id/ed1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:hint="Input Data Here"
android:textColor="#000000"
android:textSize="20sp" />
<EditText
android:layout_margin="10dp"
android:layout_below="#id/ed1"
android:id="#+id/ed2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:hint="Input Data Here"
android:textColor="#000000"
android:textSize="20sp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/ed2"
android:id="#+id/check_input"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_margin="20dp"
android:text="Go to Next Activity"
/>
</RelativeLayout>
Output:
I have two rather basic questions I believe which needs answering:
1) When I run my emulator on the home screen my SignIn button is unresponsive and I am unsure why as I have tried alternative methods but whenever I click nothing happens and no error is showing. Code is shown below:
package com.techblogon.loginexample;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class HomeActivity extends Activity
{
Button btnSignIn,btnSignUp;
LoginDataBaseAdapter loginDataBaseAdapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// create a instance of SQLite Database
loginDataBaseAdapter=new LoginDataBaseAdapter(this);
loginDataBaseAdapter=loginDataBaseAdapter.open();
// Get The Reference Of Buttons
btnSignIn=(Button)findViewById(R.id.buttonSignIN);
btnSignUp=(Button)findViewById(R.id.buttonSignUP);
// Set OnClick Listener on SignUp button
btnSignUp.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
/// Create Intent for SignUpActivity and Start The Activity
Intent intentSignUP=new Intent(getApplicationContext(),SignUPActivity.class);
startActivity(intentSignUP);
}
});
}
// Method to handleClick Event of Sign In Button
public void signIn(View V)
{
final Dialog dialog = new Dialog(HomeActivity.this);
dialog.setContentView(R.layout.login);
dialog.setTitle("Login");
final EditText editTextUserName=(EditText)dialog.findViewById(R.id.editTextUserNameToLogin);
final EditText editTextPassword=(EditText)dialog.findViewById(R.id.editTextPasswordToLogin);
Button btnSignIn=(Button)dialog.findViewById(R.id.buttonSignIN);
// Set On ClickListener
btnSignIn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// get The User name and Password
String userName=editTextUserName.getText().toString();
String password=editTextPassword.getText().toString();
// fetch the Password form database for respective user name
String storedPassword=loginDataBaseAdapter.getSinlgeEntry(userName);
// check if the Stored password matches with Password entered by user
if(password.equals(storedPassword))
{
Toast.makeText(HomeActivity.this, "Welcome", Toast.LENGTH_LONG).show();
dialog.dismiss();
Intent ii=new Intent(HomeActivity.this,MainMenu.class);
startActivity(ii);
}
else
{
Toast.makeText(HomeActivity.this, "User Name or Password does not match", Toast.LENGTH_LONG).show();
}
}
});
dialog.show();
}
#Override
protected void onDestroy() {
super.onDestroy();
// Close The Database
loginDataBaseAdapter.close();
}
}
Could somebody provide me with the best sqlite database viewer for eclipse, I am looking to view the records of the database I have created on my emulator
My XML is as follows
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:orientation="vertical" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="#drawable/picture" />
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Hello, Welcome"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:id="#+id/buttonSignIN"
android:layout_width="fill_parent"
android:layout_height="70dp"
android:text="Sign In" />
<Button
android:id="#+id/buttonSignUP"
android:layout_width="fill_parent"
android:layout_height="70dp"
android:text="Sign Up" />
</LinearLayout>
you are missing an attribute in xml for buttonSignIN button
android:onClick="signIn"
Try this,
<Button
android:id="#+id/buttonSignIN"
android:layout_width="fill_parent"
android:layout_height="70dp"
android:onClick="signIn"
android:text="Sign In" />
You need to understand the difference between setting clickListener in java code and setting a attribute from xml for the button click. These are two different ways in which you could achieve click events for any element.
I want to show TextView editable like the app "Google Keep" but
EditText text = (EditText)findViewById(R.id.edittext);
String value = text.getText().toString();
didn't work
Hello I've made a example that I think you can use:
Layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:textColor="#FF0000"
android:text="#string/hello_world" />
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/getInfoButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="GET INFO"
android:layout_gravity="center_horizontal"
/>
</LinearLayout>
MainActivity
package com.example.testedittext;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView info;
private EditText input;
private Button getInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
info = (TextView) findViewById(R.id.textView);
input = (EditText)findViewById(R.id.editText);
getInfo = (Button)findViewById(R.id.getInfoButton);
getInfo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String inputText = input.getText().toString();
info.setText(inputText);
}
});
}
}
Here is the output:
Hope this helps,
Cheers
That is the correct syntax for getting the text in string format of an edittext.
The value of String "value" is actually "" right now because you called
text.getText().toString();
IMMEDIATELY after EditText text was instantiated. As you can imagine, the moment it was created, there was no text inside it, so that's why "value" has an empty string.
If you want to retrieve the value of the edittext at a specific call, I'd recommend adding a button in your xml layout, and in your code, add this:
Button button = (Button) findViewById(R.id.somebutton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
text.getText().toString();
}
});
This will get the current String value of the edittext when you click on the button.
You have to use the value String somewhere else it will tell you that its not used.
Then you have to use that piece of code at a point of time where you have had a change to set the value of that ediettext.
I have a working Preferences setup launched from a menu option. In the preferences I have setup a Custom Preference that must launch a dialog with 3 TextViews to set confirm and change a password. Now I do not know how to launch the dialog from the PreferenceActivity's onPreferenceClick. If I sound like a newby - I am, sorry!
Here is my xml layout for the dialog popup:
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical"
android:id="#+id/root"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/TextView_Pwd1"
android:text="#string/settings_oldpassword"
android:textStyle="bold" />
<EditText
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:id="#+id/EditText_OldPwd" />
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/TextView_Pwd1"
android:text="#string/settings_password"
android:textStyle="bold" />
<EditText
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:id="#+id/EditText_Pwd1"
android:inputType="textPassword" />
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/TextView_Pwd2"
android:text="#string/settings_password2"
android:textStyle="bold" />
<EditText
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:id="#+id/EditText_Pwd2"
android:inputType="textPassword" />
<TextView
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:id="#+id/TextView_PwdProblem"
android:textStyle="bold"
android:gravity="center" />
<TextView
android:id="#+id/TextView_PwdProblem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="#string/settings_pwd_not_equal" />
<CheckBox
android:id="#+id/checkShowPwdText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/settings_showpwd_text" />
Here is my DialogChangePassword class for the dialog popup:
package biz.linsys.package;
import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.DialogPreference;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class DialogChangePassword extends DialogPreference {
private String strPass1;
private String strPass2;
public DialogChangePassword(Context context, AttributeSet attrs) {
super(context, attrs);
setDialogLayoutResource(R.layout.dialog_pwdchange);
}
#Override
protected void onBindDialogView(View view) {
Dialog pwdDialog = getDialog();
final EditText password1 = (EditText) pwdDialog.findViewById(R.id.EditText_Pwd1);
final EditText password2 = (EditText) pwdDialog.findViewById(R.id.EditText_Pwd2);
final TextView error = (TextView) pwdDialog.findViewById(R.id.TextView_PwdProblem);
password2.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
strPass1 = password1.getText().toString();
strPass2 = password2.getText().toString();
if (strPass1.equals(strPass2)) {
error.setText(R.string.settings_pwd_equal);
} else {
error.setText(R.string.settings_pwd_not_equal);
}
} public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {}
});
super.onBindDialogView(view);
}
#Override
protected void onDialogClosed(boolean positiveResult) {
if(!positiveResult) return;
SharedPreferences.Editor editor = getEditor();
if (strPass1.equals(strPass2)) {
editor.putString("password", strPass1);
editor.commit();
}
super.onDialogClosed(positiveResult);
}
}
This the PreferenceActivity class containing Custom Preference onPreferenceClick. This is where I need to call the dialog box to change the user password setting.
package biz.linsys.package;
import android.content.Context;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
public class Preferences extends PreferenceActivity {
public static Context dialogContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
// Get the custom preference
Preference customPref = (Preference) findPreference("customPref");
customPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
// [ NEED TO CALL DIALOG FROM HERE ]
return false;
}
});
}
}
This is something that is missing in the documentation, and I've found lots of similar questions regarding it, mostly with no definite answers. I've faced the same problem today, and somehow I've found the solution, so I'll summarize my quest here, just in hope someone will find this useful. BTW your question is the most detailed and accurate among others.
The general point is that you don't need to create the dialog manually, you just 1) create a subclass of the DialogPreference that will handle the logic of a complex preference and 2) create a node of the proper type in your preferences.xml so the dialog will be spawned automatically.
The problem of the Android SDK is that you cannot add that proper node using the visual XML editor, you need to go and edit the file manually.
The problem of the documentation is that it misses this very bit of information.
So here is the step-by-step solution:
1) Create a subclass of DialogPreference that will handle your special preference. For details on what is needed in your subclass, I'd recommend this answer.
2) Create a Preference node in your preferences.xml.
3) Edit the preferences.xml and replace the Preference with full name of your DialogPreference subclass including the package path, e. g. com.sample.MyPreferenceDialog. You may also add some attributes to the node to customize the dialog (title, icon, etc.), see this answer or the documentation for DialogPreference for details.
That's all. You don't need to add OnPreferenceClickListener to the preferences, the dialog will show up automatically.
Note: I am not 100% sure that this is the intended way of using things, but it seems to be working.
Another newbie question here. I'm trying to create a form which takes several text input fields from the user, however my view keeps crashing/failing to load with the following error reported in the log:
Window already focused, ignoring focus gain of:com.android.internal.view.IInputMethodClient$Stub$Proxy#628a9148
This is what my xml looks like (this crashes)
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content">"
<LinearLayout
android:orientation="vertical"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_gravity="top">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Please enter contact details\n\nName:"/>
<EditText
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:maxLength="30"
android:maxLines="1"
android:hint="#string/compose_name"></EditText>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="\nSurname:"/>
<EditText
android:id="#+id/surname"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:layout_below="#id/name"
android:maxLength="30"
android:maxLines="1"
android:hint="#string/compose_surname"></EditText>-->
<Button
android:id="#+id/new_contact_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/submit" />
</LinearLayout>
</ScrollView>
However if I remove just the line:
android:id="#+id/surname"
It works (well at least it loads the view, of course I can't access the content in the EditText field without creating an id for it).
The view also fails if I add #+id tags to both the TextView fields (but works if I add only one).
What's going on here? I thought you should be able to label multiple view fields in your UI (all the examples in my book let me do this)?
I'm using NetBeans to develop on.
EDIT: Adding Javacode:
package org.me.savingsdepositrecord;
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;
public class NewContact extends Activity
implements OnClickListener, View.OnKeyListener {
//private EditText nameField;
//private String name;
private Button submitButton;
EditText nameField = null;
EditText surnameField = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_contact);
nameField = (EditText) findViewById(R.id.name);
nameField.setOnKeyListener(this);
surnameField = (EditText) findViewById(R.id.surname);
submitButton = (Button) findViewById(R.id.new_contact_button);
// Set up click listeners for all the buttons
submitButton.setOnClickListener(this);
}
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER)) {
String name = nameField.getText().toString();
String surname = surnameField.getText().toString();
// TODO: Save Nickname setting (strNicknameToSave)
return true;
}
return false;
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.new_contact_button:
Intent i = new Intent(this, MainActivity.class);
finish();
startActivity(i);
break;
// More buttons go here (if any) ...
}
}
}
Yes, you can label multiple fields. It might be a good to take out the android:layout_below attribute since that isn't supported in LinearLayout.
Otherwise, your Java code might be the culprit. Can you post it as well?
Edit: I also tested your code and found no errors, although I had to remove the '-->' and the #string references.