#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.screenlocked);
//Retrieve stored ID
final String STORAGE = "Storage";
SharedPreferences unique = getSharedPreferences(STORAGE, 0);
LoginID = unique.getString("identifier", "");
//Retrieve stored phone number
final String phoneNumber = unique.getString("PhoneNumber", "");
phoneView = (TextView) findViewById(R.id.phone);
phoneView.setText(phoneNumber.toString());
//Retrieve user input
input = (EditText) findViewById(R.id.editText1);
userInput = input.getText().toString();
//Set login button
login = (Button) findViewById(R.id.login);
login.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
compareID();
}
});
}
public void compareID(){
if (userInput.equals(LoginID)){
//phone screen unlocked
//continue
Toast.makeText(ScreenLockActivity.this, "Success!", Toast.LENGTH_SHORT).show();
}
else{
count += 1;
input.setText("");
Toast.makeText(ScreenLockActivity.this, count, Toast.LENGTH_SHORT).show();
}
}
I am developing a login activity and I would like to record down how many times the user tried to login, so every time there is a login attempt the count will increment by one... but when i run the activity, this error appears in my logcat:
android.content.res.Resources$NotFoundException: String resource ID #0x1,
Can someone help me solve this problem?
Here is your mistake:
Toast.makeText(ScreenLockActivity.this, count, Toast.LENGTH_SHORT).show();
the makeText you are trying to invoke here, is the makeText that takes as second parameter a resId. See here for more info. Since you want to print the count value, you have to convert it in a String.
String value = String.valueOf(count);
Toast.makeText(ScreenLockActivity.this, value, Toast.LENGTH_SHORT).show();
This line should be inside onClick() or compareID():
userInput = input.getText().toString();
Related
I'm trying to save userName but the saved text file always returns , 6. How can I get it to show whatever value of userName entered into EditText, and the rest? for example Don, 6. I have read you have to use getText() but that isn't returning anything in the saved file.
However, if I replace 6 with an intent to receive score from previous activity, this works! like this...
Bundle extras = getIntent().getExtras();
int score = extras.getInt("Score");
So this becomes...
public void addListenerToEndButton() {
quit = (Button) findViewById(R.id.endBtn);
userName = (EditText) findViewById(R.id.userName);
Bundle extras = getIntent().getExtras();
int score = extras.getInt("score");
quit.setOnClickListener(new View.OnClickListener() {
String strName = userName.getText().toString();
#Override
public void onClick(View v) {
saveProgress(strName + ", " + score, "results.txt");
finish();
System.exit(0);
}
});
}
But it still returns empty, whatever score is. For example , 4.
I've read this post that suggests it should be inside onClickListener which it is:
EditText getText().toString() not working
This is my saveProgress class:
public void saveProgress(String contents, String fileName) {
try {
File fp = new File(this.getFilesDir(), fileName);
FileWriter out = new FileWriter(fp);
out.append(contents);
out.append("\n\r");
out.close();
}
catch (IOException e) {
Log.d("Me","file error:" + e);
}
}
Change your onClick() method with the following:
public void addListenerToEndButton() {
quit = (Button) findViewById(R.id.endBtn);
userName = (EditText) findViewById(R.id.userName);
Bundle extras = getIntent().getExtras();
int score = extras.getInt("score");
quit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String strName = userName.getText().toString();
saveProgress(strName + ", " + score, "results.txt");
finish();
System.exit(0);
}
});
}
Calls, initializations, operations, exc, should go inside the onClick method of the listener. The onClick is fired only when the button is clicked, everything outside the onClick but inside the Listener is called on Listener initialization
I guess you understood 'inside onClickListener' wrong. What you are doing atm is that you read strName when you create the listener, but I guess you want to read it when quit is clicked.
So just move the line into the function and the value will be correct.
public void addListenerToEndButton() {
quit = (Button) findViewById(R.id.endBtn);
userName = (EditText) findViewById(R.id.userName);
quit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String strName = userName.getText().toString();
saveProgress(strName + ", " + 6, "results.txt");
finish();
System.exit(0);
}
});
}
I have 2 questions want to ask about android studio and sqlite.
1) I am trying to run my project in emulator or phone. When I want to return to previous activity by pressing the return button(return function for phone) but it close all my project.But I saw my friend's can return to previous activity by pressing the return button.May I know how and why??
2) I had done update function for my project.The situation is when userA go to "view profile" activity and click edit info, another activity that call "updateinfo" will come out.Then after userA update his information by clicking update button.It's successful update and go back to "view profile" activity to see his updated profile.
But the problem I faced is it does not show out the updated information.It just show a blank "view profile" activity without any information that updated or haven updated.
What should I do?
here my database update function
public boolean updateProfile(String username, String password, String email, String phone)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put (COL_2,username);
values.put(COL_3,password);
values.put(COL_4,email);
values.put(COL_5,phone);
db.update(Table_NAME,values,COL_2 + "=?",new String[]{username});
db.close();
return true;
}
here is my updateinfo activity function
public class EditProfile extends AppCompatActivity {
EditText etEmail,etPhone,etPassword,etConPassword,etUsername;
String password,conpassword,Email,Phone;
Button bUpdate;
DatabaseOperations DB = new DatabaseOperations(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
etEmail = (EditText) findViewById(R.id.etEmail);
etPhone = (EditText) findViewById(R.id.etPhone);
etPassword = (EditText) findViewById(R.id.etPassword);
etConPassword = (EditText) findViewById(R.id.etConPassword);
etUsername = (EditText) findViewById(R.id.etUsername);
bUpdate = (Button) findViewById(R.id.bUpdate);
Intent i = getIntent();
String email = i.getStringExtra("email");
etEmail.setText(email);
String phone = i.getStringExtra("phone");
etPhone.setText(phone);
String username = i.getStringExtra("username");
etUsername.setText(username);
bUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
password = etPassword.getText().toString();
conpassword = etConPassword.getText().toString();
Email = etEmail.getText().toString();
Phone = etPhone.getText().toString();
if (!(password.equals(conpassword))) {
Toast.makeText(getBaseContext(), "Passwords are not matching", Toast.LENGTH_LONG).show();
etPassword.setText("");
etConPassword.setText("");
etEmail.setText("");
etPhone.setText("");
} else if (etPassword.length() == 0 || etConPassword.length() == 0 || etEmail.length() == 0 || etPhone.length() == 0) {
etPassword.setError("Please complete all information");
etConPassword.setError("Please complete all information");
etEmail.setError("Please complete all information");
etPhone.setError("Please complete all information");
} else if (etPassword.length() < 6) {
etPassword.requestFocus();
etPassword.setError("Password at least 6 characters");
etPassword.setText("");
etConPassword.setText("");
etEmail.setText("");
etPhone.setText("");
} else {
boolean isUpdate = DB.updateProfile(etUsername.getText().toString(),etPassword.getText().toString(),etEmail.getText().toString(),etPhone.getText().toString());
if(isUpdate == true) {
Toast.makeText(getBaseContext(), "Update Success", Toast.LENGTH_LONG).show();
Intent i = new Intent(EditProfile.this, MyProfile.class);
startActivity(i);
finish();
}
else
{
Toast.makeText(getBaseContext(), "Data Not Updated", Toast.LENGTH_LONG).show();
}
}
}
});
}
and here is my viewprofile activity function
public class MyProfile extends AppCompatActivity {
EditText etName,etEmail,etPhone,etShow;
Button bEdit;
String fullname,email,phone;
DatabaseOperations db = new DatabaseOperations(this);
PersonalData profileInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_profile);
etName = (EditText) findViewById(R.id.etName);
etEmail = (EditText) findViewById(R.id.etEmail);
etPhone = (EditText) findViewById(R.id.etPhone);
bEdit = (Button) findViewById(R.id.bEdit);
etShow = (EditText) findViewById(R.id.etShow);
fullname = etName.getText().toString();
email = etEmail.getText().toString();
phone = etPhone.getText().toString();
Intent i = getIntent();
String username = i.getStringExtra("username");
etShow.setText(username);
profileInfo = db.getAllinfo(username);
etName.setText(profileInfo.get_name());
etEmail.setText(profileInfo.get_email());
etPhone.setText(profileInfo.get_phone());
bEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MyProfile.this,EditProfile.class);
i.putExtra("email", etEmail.getText().toString());;
i.putExtra("phone", etPhone.getText().toString());;
i.putExtra("username", etShow.getText().toString());
startActivity(i);
finish();
}
});
}
you always start new activity and finish the last activity
startActivity(i);
finish();
dont finish it if you want to go back later, you can go back to last activity with finish(); or pressing back in phone
you just need to call finish() when update success (you need to implement answer number 1 first)
Toast.makeText(getBaseContext(), "Update Success", Toast.LENGTH_LONG).show();
Intent i = new Intent(EditProfile.this, MyProfile.class);
startActivity(i);
finish();
in MyProfile make the username variable global
String username;
#Override
protected void onCreate(Bundle savedInstanceState) {
....
username = i.getStringExtra("username");
....
}
last,this code need to be inside onResume()
etShow.setText(username);
profileInfo = db.getAllinfo(username);
etName.setText(profileInfo.get_name());
etEmail.setText(profileInfo.get_email());
etPhone.setText(profileInfo.get_phone());
public boolean update(editProfile.EUsers eusers){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentvalues = new ContentValues();
String username = eusers.getUsername();
String password = eusers.getPassword();
int id = eusers.getId();
contentvalues.put(editProfile.EUsers.COL3_PASSWORD,password);
contentvalues.put(editProfile.EUsers.COL2_USERNAME,username);
int res =db.update(editProfile.EUsers.TABLE_NAME,values,editProfile.EUsers.COL1_ID+" = ?",new String[]{String.valueOf(id)});
if(res >0)
return true;
return false;
}
I've been getting null returns from getting strings from my saved preferences. I'm not sure how savedpreferences worked but my understanding was that when call a sharedpreferences, it creates the keypair file on the phone so you can come back to it later.
My program is essentially a string creation application. When you press a button, it creates a string to send as an sms. My settings activity page has four edittexts that save whatever is inside them with a buttonclick and returns to the main activity. The final button creates a String by getting the value from the keyvalue pair and constructs the message. However, I've always gotten null for each of the values.
Heres the code for the settings page and then the main page. Please ask if I could add more, I didn't add ALL of the code, just the sharedpreferences portions.
public SharedPreferences sp;
public Editor e;
public void savethethings(){ //run this when enter is pressed/savew
EditText smsintro_hint = (EditText) findViewById(R.id.settings_smsintro_hint);
EditText smsbody_hint = (EditText) findViewById(R.id.settings_smsbody_hint);
EditText checkboxbody_hint = (EditText) findViewById(R.id.settings_checkboxbody_hint);
EditText checkboxbody_description_hint = (EditText) findViewById(R.id.settings_checkboxbody_description_hint);
String introstring = smsintro_hint.getText().toString();
String bodystring = smsbody_hint.getText().toString();
String checkboxbodystring = checkboxbody_hint.getText().toString();
String checkboxdescriptionstring = checkboxbody_description_hint.getText().toString();
e.putString("intro", introstring);
e.commit(); // you forgot to commit
if(!bodystring.isEmpty())
{
e.putString("body", bodystring);
e.commit();
}
if(!checkboxbodystring.isEmpty())
{
e.putString("checkbody", checkboxbodystring);
e.commit();
}
if(!checkboxdescriptionstring.isEmpty())
{
e.putString("checkboxdescr", checkboxdescriptionstring);
e.commit();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.settingmenu);
//SP
sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); // forget about
// named preferences - get the default ones and finish with it
e = sp.edit();
Button tt = (Button)findViewById(R.id.savebutton);
tt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
public void save(View view)
{
//THINGS HAPPEN HERE WITH SHARED PREFERENCES :(
savethethings();
this.finish();
return;
}
public String finishedtext(String userstring)
{
smsintroduction = (sp.getString("intro", ""));
smsbody = (sp.getString("body", ""));
checkboxtext = (sp.getString("checkbody", ""));
checkboxmessage = (sp.getString("checkboxdescr", ""));
if(smsintroduction.isEmpty())
{
if(smsbody.isEmpty())
{
if(checkboxtext.isEmpty())
{
if(checkboxmessage.isEmpty()) //topkek for most AND statements Ive ever put in in if/then form
{
//Essentially the DEFAULT if they're ALL null
smsbody = "Hi "+ userstring +"! This is coming from jake's phone and it wants to send a text so we can talk or whatever. ";
}
}
}
}
Toast.makeText( this, "Creating text, then press send!", Toast.LENGTH_LONG).show();
String thetext = "";
thetext = smsintroduction + " " + smsbody + " " + checkboxtext;
return thetext;
}
public void savethethings(){ //run this when enter is pressed/savew
EditText smsintro_hint = (EditText) findViewById(R.id.settings_smsintro_hint);
EditText smsbody_hint = (EditText) findViewById(R.id.settings_smsbody_hint);
EditText checkboxbody_hint = (EditText) findViewById(R.id.settings_checkboxbody_hint);
EditText checkboxbody_description_hint = (EditText) findViewById(R.id.settings_checkboxbody_description_hint);
String introstring = smsintro_hint.getText().toString();
String bodystring = smsbody_hint.getText().toString();
String checkboxbodystring = checkboxbody_hint.getText().toString();
String checkboxdescriptionstring = checkboxbody_description_hint.getText().toString();
// if(!introstring.isEmpty()) //if the fields are NOT empty, they should get saved.
// {
e.putString("intro", introstring);
e.commit(); // you forgot to commit
if(!bodystring.isEmpty())
{
e.putString("body", bodystring);
e.commit();
}
if(!checkboxbodystring.isEmpty())
{
e.putString("checkbody", checkboxbodystring);
e.commit();
}
if(!checkboxdescriptionstring.isEmpty())
{
e.putString("checkboxdescr", checkboxdescriptionstring);
e.commit();
}
}
Create java class named SessionManger and put all your methods for setting and getting SharedPreferences values. When you want to save value use the object of this class and set and get the values.
Sample code given below.
public class SessionManager {
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
int PRIVATE_MODE = 0;
public SessionManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences("name_that_you_use", PRIVATE_MODE);
editor = pref.edit();
editor.apply();
}
public void setIntroMessage(String data) {
editor.putString("intro", data);
editor.commit();
}
public String getIntroMessage() {
return pref.getString("intro", null);
}
}
I have a login activity on app start and I need to check if use has used this app before and then I need to place the username and his password entered recently.
For this I have used shared preferences and used as shown below:
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
username= usernameET.getText().toString();
password= passwordET.getText().toString();
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
data.edit().putString("username", username).commit();
data.edit().putString("password", password).commit();
}
});
Now I'm getting these values on app restart as shown below:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String storedUsername = data.getString("username", "");
String storedPassword = data.getString("password", "");
if (storedUsername != null && storedPassword != null) {
usernameET.setText(storedUsername);
passwordET.setText(storedPassword);
} else {
}
}
Coder, what is your issue? This is not working?
Please, tell us what is happening.
The implementation with SharedPreference would be my suggestion for you, is it not working?
I made a very simple implemention here and it works as usual...
On the onCreate:
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String storedUsername = data.getString("username", "");
String storedPassword = data.getString("password", "");
Toast.makeText(this, "saved Strings, user = " + storedUsername + " pass = " + storedPassword, Toast.LENGTH_LONG).show();
On the click of an ImageButton
#Override
public void onClick(View v) {
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
data.edit().putString("username", "carlos").commit();
data.edit().putString("password", "password").commit();
}
Sounds like you are not setting the content on the SharedPreferences. Could you please make sure the action is executed?
Didn't really see a question asked but...
data.getString is going to return the default value if it is not set, which you're setting as a blank string(""). Either change your if:
if (!storedUsername.equals("") && !storedPassword.equals(""))
or change your default value to null
String storedUsername = data.getString("username", null);
String storedPassword = data.getString("password", null);
After the User logged in and ticked the checkbox for "Keep me Logged in", the activity will proceed to another activity where it has many EditTexts. However, if the user accidentally close/shutdown the device, the data will be retrieved upon going back to that application since the user ticked the "Keep me Logged in". I used onSaveInstanceState and onRestoreInstanceState but it doesn't help. Please help me with this.
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
final EditText txt_Fname = (EditText) findViewById(R.id.txt_Fname);
final EditText txt_Mname = (EditText) findViewById(R.id.txt_Mname);
final EditText txt_Lname = (EditText) findViewById(R.id.txt_Lname);
final EditText txt_Suffix = (EditText) findViewById(R.id.txt_Suffix);
String Fname = txt_Fname.getText().toString();
String Mname = txt_Mname.getText().toString();
String Lname = txt_Lname.getText().toString();
String Suffix = txt_Suffix.getText().toString();
outState.putString("shared_fname", Fname);
outState.putString("shared_mname", Mname);
outState.putString("shared_lname", Lname);
outState.putString("shared_suffix", Suffix);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
final EditText txt_Fname = (EditText) findViewById(R.id.txt_Fname);
final EditText txt_Mname = (EditText) findViewById(R.id.txt_Mname);
final EditText txt_Lname = (EditText) findViewById(R.id.txt_Lname);
final EditText txt_Suffix = (EditText) findViewById(R.id.txt_Suffix);
txt_Fname.setText(savedInstanceState.getString("shared_fname"));
txt_Mname.setText(savedInstanceState.getString("shared_mname"));
txt_Lname.setText(savedInstanceState.getString("shared_lname"));
txt_Suffix.setText(savedInstanceState.getString("shared_suffix"));
}
Use SharedPreference to save data, when you switching between activities and shutting down the application. Below are example methods, you can call during onCreate() and onDestroy().
void saveText() {
sPref = getPreferences(MODE_PRIVATE);
Editor ed = sPref.edit();
ed.putString(SAVED_TEXT, etText.getText().toString());
ed.commit();
Toast.makeText(this, "Text saved", Toast.LENGTH_SHORT).show();
}
void loadText() {
sPref = getPreferences(MODE_PRIVATE);
String savedText = sPref.getString(SAVED_TEXT, "");
etText.setText(savedText);
Toast.makeText(this, "Text loaded", Toast.LENGTH_SHORT).show();
}