This is my code:
package com.example.scheda_ais;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.io.File;
public class MainActivity extends AppCompatActivity {
EditText degustatore;
Button completa;
SharedPreferences sharedPref;
String generalita;
String appoggio;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPref = this.getSharedPreferences("il_sottoscritto",Context.MODE_PRIVATE);
degustatore = findViewById(R.id.degustatore);
completa = findViewById(R.id.completa);
completa.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
generalita = degustatore.getText().toString();
if(generalita != ""){
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("generalita", generalita);
editor.commit();
}
appoggio = sharedPref.getString("generalita", "vuoto");
Log.d("generalita", appoggio);
}
});
}
When I press the Button with an empty EditText (no input at all), nothing is printed by Log, while Log should print "generalita" + "vuoto".
Why String appoggio is empty?
If I input something in EditText, Log prints correctly "generalita" + appoggio.
Please someone help me. Thanks.
By using != to compare your string you are comparing "object instance" but "" and generalita string is not the same object so you are entering in the if and put "" to your preference so the preference is not null when you log it and the default value is not print.
that's what appens:
sharedPref = this.getSharedPreferences("il_sottoscritto",Context.MODE_PRIVATE);
degustatore = findViewById(R.id.degustatore);
completa = findViewById(R.id.completa);
completa.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
generalita = degustatore.getText().toString();
// generalita instance and "" intance are not equal so the trest will pass
if(generalita != ""){
SharedPreferences.Editor editor = sharedPref.edit();
// here you're putting "" to your preference
editor.putString("generalita", generalita);
editor.commit();
}
// sharedPref.getString("generalita", "vuoto") return ""
appoggio = sharedPref.getString("generalita", "vuoto");
Log.d("generalita", appoggio);
}
});
you should do like that
completa.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
generalita = degustatore.getText().toString();
if(!generalita.equals("")){
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("generalita", generalita);
editor.commit();
}
appoggio = sharedPref.getString("generalita", "vuoto");
Log.d("generalita", appoggio);
}
});
change this appoggio = sharedPref.getString("generalita", "vuoto");
to appoggio = sharedPref.getString("generalita", "");
There are two issues with what you wrote.
As #SebastienRieu said correctly
the first one , you can't do == for Strings in java.
You need to write:
if(!"".equals(generalita)){
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("generalita", generalita);
editor.commit();
}
And the 2nd one, you said you were expecting "generalita" + "vuoto"
However in this code:
appoggio = sharedPref.getString("generalita", "vuoto");
Log.d("generalita", appoggio);
in the Log the first word "generalita" is not text printed in the log, but rather a TAG that is filterable. If you want to see "generalita vuoto", then you'd have to put both on the right side.
Replace generalita != "", by !generalita.isEmpty() to check the length of your String.
Related
I am working with SharedPreference but I cannot save info.
These is my code:
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class SharedPrefApp extends Activity implements View.OnClickListener {
Button buton1 , buton2 ;
EditText etv1 , etv2 ;
TextView tv1;
private static SharedPreferences sharedPref;
protected void onCreate(Bundle bambam){
super.onCreate(bambam);
setContentView(R.layout.sharedpref_xml);
buton1 = ( Button) findViewById(R.id.button12);
buton2 = ( Button) findViewById(R.id.button13);
etv1= (EditText) findViewById(R.id.editText4);
etv2= (EditText) findViewById(R.id.editText5);
tv1 = (TextView) findViewById(R.id.textView12);
buton1.setOnClickListener(this);
buton2.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()){
case R.id.button12:
sharedPref = getSharedPreferences("namapassword" , Context.MODE_PRIVATE );
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("isim" , etv1.getText().toString());
editor.putString("sifre" , etv2.getText().toString());
editor.apply();
Toast.makeText(this , "Kaydedildi" , Toast.LENGTH_SHORT).show();
break;
case R.id.button13:
sharedPref = getSharedPreferences("namepassword" , Context.MODE_PRIVATE);
String a = sharedPref.getString("isim", "olmadı");
String b = sharedPref.getString("sifre" , "olmadı");
tv1.setText(a + " " + b);
Toast.makeText(this, "Gosterildi" , Toast.LENGTH_SHORT).show();
break;
}
}
}
It returns olmadı olmadı in application. Why it doesn't work?
You have a typo in your code. You spelled name as nama, resulting in that you are trying to store and fetch values from two different preferences.
Your first button (R.id.button12) call to get shared preferences is:
sharedPref = getSharedPreferences("namapassword" , Context.MODE_PRIVATE );
change it to:
sharedPref = getSharedPreferences("namepassword" , Context.MODE_PRIVATE );
Why are you using editor.apply() method
try to using commit() method
For example
editor.commit()
Try the below code
sharedPref = getSharedPreferences("namapassword" , Context.MODE_PRIVATE );
sharedprefs.edit.putString("isim" , etv1.getText().toString()).commit();
Oh Boy... Your getString shouldb like the follows..
String a = sharedPref.getString("isim", null);
String b = sharedPref.getString("sifre" , null);
I am doing an android app which would save the password for the next time the user wants to use this app. when I try to run my application, the password is entered,but there is a pop-up said the application has stopped?
package com.wheresmyphone;
import android.os.Bundle;
import android.app.Activity;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class Check extends Activity {
String StringPreference;
SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_check);
Button b = (Button)findViewById(R.id.Button01);
final EditText preferences = (EditText)findViewById(R.id.txt12345);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
EditText sharedPreferences = (EditText)findViewById(R.id.txt12345);
String StringPreference = preferences.getText().toString();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.check, menu);
return true;
}
/**
* Method used to get Shared Preferences */
public SharedPreferences getPreferences()
{
return getSharedPreferences(null, 0);
}
/**
* Method used to save Preferences */
public void savePreferences(String key, String value)
{
SharedPreferences sharedPreferences = getPreferences();
SharedPreferences.Editor editor = preferences.edit();
String StringPreference = sharedPreferences.toString();
editor.putString("sharedString", StringPreference);
editor.commit();
}
/**
* Method used to load Preferences */
public String loadPreferences(String key)
{
try {
SharedPreferences sharedPreferences = getPreferences();
String strSavedMemo = sharedPreferences.getString(key, "");
return strSavedMemo;
} catch (NullPointerException nullPointerException)
{
Log.e("Error caused at TelaSketchUtin loadPreferences method",
">======>" + nullPointerException);
return null;
}
}
/**
* Method used to delete Preferences */
public boolean deletePreferences(String key)
{
SharedPreferences.Editor editor=getPreferences().edit();
editor.remove(key).commit();
return false;
}
{
}
}
I'm not sure, but i think you missed something at this point:
return getSharedPreferences(null, 0);
Look here:
http://developer.android.com/reference/android/content/Context.html#getSharedPreferences%28java.lang.String,%20int%29
Parameters
name
Desired preferences file. If a preferences file by this name does not exist, it will be created when you retrieve an editor (SharedPreferences.edit()) and then commit changes (Editor.commit()).
If you set "name" to null, he cant create a file.
Might be the solution, add this on top
private final String KEY_SHAREDPREFS = "tmpsharedprefs";
and then use it
return getSharedPreferences(KEY_SHAREDPREFS, 0);
See your are trying to get string from preference, first you have to get password from edittext like this code
EditText passwordText = (EditText)findViewById(R.id.txt12345);
String password = passwordText.getText().toString();
and then store this password in shared preferences
Use SharedPreferences as,
To Save:
SharedPreferences settings;
SharedPreferences.Editor editor;
public static final String PREFS_NAME = "app_pref";
public static final String KEY_p_id = "KEY_test";
settings = getSharedPreferences(PREFS_NAME, 0);
editor = settings.edit();
editor.putString(Login_screen.KEY_test, values.get(0));
editor.commit();
To Remove:
editor.remove("KEY_test").commit();
To Get:
settings = getSharedPreferences(PREFS_NAME, 0);
String TestId = settings.getString("KEY_test", null);
A simple task remainder application.
I have to save and retrieve the three edit text values in this app using shared preferences.
Which storage option is best for this app,
1.shared preferences
2.internal storage
Storing
EditText Task = (EditText)findViewById(R.id.ettask);
EditText date = (EditText)findViewById(R.id.etdate);
EditText time = (EditText)findViewById(R.id.ettime);
String taskstr = Task.getText().toString();
String datestr= date .getText().toString();
String timestr= time .getText().toString();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
Editor edit = preferences.edit();
edit.putString("pref_task", taskstr);
edit.putString("pref_date", datestr);
edit.putString("pref_date", timestr);
edit.commit();
Retrieving
pref_task = preferences.getString("pref_task", "n/a");
pref_date = preferences.getString("pref_date","n/a");
pref_time = preferences.getString("pref_date","n/a");
Complete example:
package com.example.logindemo;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
public class LoginPage extends Activity {
EditText name = null, pwd = null;
SharedPreferences login_pref = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_page);
name = (EditText) findViewById(R.id.name_edt);
pwd = (EditText) findViewById(R.id.pwd_edt);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_login_page, menu);
return true;
}
public void loginMethod(View v) {
login_pref = this.getSharedPreferences("login_pref",
MODE_WORLD_READABLE);
SharedPreferences.Editor login_pref_editor = login_pref.edit();
login_pref_editor.putString("Name", name.getText().toString());
login_pref_editor.commit();
startActivity(new Intent(this, WelcomeScreen.class));
}
}
Hope it helps. I feel Shared preference will be a better way
Use below code to Store data into SharedPreferences.
SharedPreferences myPrefs = PreferenceManager.getDefaultSharedPreferences(this);
Editor editor = myPrefs.edit();
editor.putString("Date", mEdttxtDate.getText().toString());
editor.commit();
For Retrive data from SharedPreferences.
SharedPreferences myPrefs = PreferenceManager.getDefaultSharedPreferences(this);
String mDate = myPrefs.getString("Date","nothing");
it will solve your problem.
for inserting
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
Editor edit = preferences.edit();
edit.putString("pref_empId", _empid);
edit.putString("pref_userType", _usertype);
edit.commit();
for getting shared preferences
pref_empId = preferences.getString("pref_empId","n/a");
pref_userType = preferences.getString("pref_userType","n/a");
// I declared myPrefs globally in the lass
SharedPreferences myPrefs = null;
// this is called in my do draw function
public void doDraw() {
myPrefs = this.getSharedPreferences("myPrefs", Context.MODE_WORLD_READABLE);
SharedPreferences.Editor editor = myPrefs.edit();
editor.putInt("MYHIGHSCORE", score);
editor.commit();
}
Whenever I call SharedPreferences.Editor editor = myPrefs.edit();, my program crashes. What I'm doing wrong? I'm trying to store an int for a high score system. And SharedPreferences was suggested a lot for a mini high score system like mine.
Edit:
package com.example.logindemo;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
public class LoginPage extends Activity {
EditText name = null, pwd = null;
SharedPreferences login_pref = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_page);
name = (EditText) findViewById(R.id.name_edt);
pwd = (EditText) findViewById(R.id.pwd_edt);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_login_page, menu);
return true;
}
public void loginMethod(View v) {
login_pref = this.getSharedPreferences("login_pref",
MODE_WORLD_READABLE);
SharedPreferences.Editor login_pref_editor = login_pref.edit();
login_pref_editor.putString("Name", name.getText().toString());
login_pref_editor.commit();
startActivity(new Intent(this, WelcomeScreen.class));
}
}
Try this. I think your shared pref object was not fetched properly.
Note: Edited post to add whole class's code.
If you intend to have only one preference file, try to use this code to retrieve the SharedPreference.
myPrefs = PreferenceManager.getDefaultSharedPreferences(this);
I guess the problem is not at edit() but when u apply() your changes. Look at the solution here
I want to save the value of a string at exit of my application(process kill) in last activity , so that when I start that application again I can retrieve that value in first activity.
I tried the sharedpreferences but that does not solve my problem. Here is the code snippet.
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Intent int1 = getIntent();
String pth = prefs.getString("pathreturned", "true");
to retrieve in the first activity.
and this one to save it in the previous activity:
SharedPreferences myPrefs = getSharedPreferences("myPrefs", MODE_PRIVATE);
SharedPreferences.Editor e = myPrefs.edit();
e.putString("pathreturned", path);
e.commit();
In your previous Activity, use the same code as the one you used before...
Instead of
SharedPreferences myPrefs = getSharedPreferences("myPrefs", MODE_PRIVATE);
use
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Here is a complete Example of Saving Strings Via SharedPreferences
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
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 SharedPrefs extends Activity implements OnClickListener{
private EditText dataInput;
private TextView dataView;
private SharedPreferences sharedString;
public static final String myFile = "MySharedDataFile";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sharedprefs);
setUpVariables();
sharedString = getSharedPreferences(myFile, 0);
}
public void setUpVariables(){
dataInput = (EditText) findViewById(R.id.dataToUse);
dataView = (TextView) findViewById(R.id.showDataView);
Button save = (Button) findViewById(R.id.savedataButton);
Button load = (Button) findViewById(R.id.loadDataButton);
save.setOnClickListener(this);
load.setOnClickListener(this);
}
public void onClick(View arg0) {
switch(arg0.getId()){
case R.id.savedataButton:
String dataToSave = dataInput.getText().toString();
Editor storeData = sharedString.edit();
storeData.putString("key", dataToSave);
storeData.commit();
break;
case R.id.loadDataButton:
sharedString = getSharedPreferences(myFile, 0);
String savedData = sharedString.getString("key", "No data Found");
dataView.setText(savedData);
break;
}
}
}
Unless you know which Activity is going to be "last" you should save your value at the close of each activity. Override the onStop method and save it there.