Where the data will be stored when using Sharedpreferences - android

Hi please tell me whats wrong in the code I am learning shared preferences and after using them my app is not running it's stopped by displaying unfortunately example stopped.where will be the data stored i am not finding any file related to preferences in DDMS.`
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sp=getSharedPreferences(MY_FILE,Context.MODE_PRIVATE);
Editor e=sp.edit();
e.putString("name", textview1.getText().toString());
e.commit();
String name=sp.getString("name","");
Log.i("NAme","name entered:"+ name);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i=new Intent(MainActivity.this,MenuScreen.class);
startActivity(i);
}
});
}`

You have not initialized textview1. Add something like
textview1 = (TextView)findViewById(R.id.your_textview_id);
after setContentView().
No preferences are saved as the program terminates before the sharedpreferences edit is committed.
To answer the question in the title, the shared preferences are stored under your app package's data directory.
For app crashes, always first have a look at the exception stacktrace in logcat. Include it in the questions you post, too.

Related

How to save and get SharedPreferences in different activities?

I've been having issues understanding how to save and read SharedPreferences. I'm trying to save four separate SharedPreferences but as I couldn't figure out how to do it, I decided to try with a simple String.
In this code I'm trying to create and save a string in SharedPreferences
Button enrollNewStudent = (Button) findViewById(R.id.enrollStudentButton) ;
enrollNewStudent.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
SharedPreferences prefs = getSharedPreferences(getString(R.string.testing), MODE_PRIVATE);
SharedPreferences.Editor editor = getSharedPreferences(getString(R.string.testing), MODE_PRIVATE).edit();
editor.putString("name", "Dave");
editor.commit();
startActivity(new Intent(MainActivity.this, AddNewStudent.class));
}
});
And in this next part I'm trying to read the SharedPreferences and have a TextView set to it in a second activity.
Context context = this;
SharedPreferences sharedPref = getSharedPreferences(getString(R.string.testing),MODE_PRIVATE);
String toPutInTextView = sharedPref.getString(getString(R.string.testing), null);
TextView textView = findViewById(R.id.exampleTextView);
textView.setText(toPutInTextView);
When I run this app and click the button to switch to the second activity the TextView on the second activity is blank.
Does anybody see a problem with this? I've been trying to piece together what I need to do from the android developers website and from other questions here but I just cannot get this working. This is for a university project.
The problem is: sharedPref.getString(getString(R.string.testing), null) is pulling using the string getString(R.string.testing) as the key. However, the key you used when you called "putString()" was "name". So you need to use "name" as your key for your getString() call.
Try:
String toPutInTextView = sharedPref.getString("name", "<default_value>");

application gets crashed while using shared preferences [duplicate]

Here, i am trying to call setText method but my application is getting crashed because of some initialization problem.
EditText edittext;
SharedPreferences settings;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image =(ImageView) findViewById(R.id.imageView1);
image.setImageResource(R.drawable.logo);
settings= getSharedPreferences(PREFS_NAME,Context.MODE_PRIVATE);
if(settings.contains("sharedString")){
String returnString=settings.getString("sharedString","Couldn't load the data");
edittext.setText(returnString);
}
}
edittext is not initialized. Initialize it in onCreate.
In onCreate you have
edittext.setText(returnString); // not initialized in onCreate
You have
edittext =(EditText)findViewById(R.id.edit_message); // initialized in sendMessage
in sendMessage. So you may be setting text to edittext even before it is initialized
Please try with the code.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image =(ImageView) findViewById(R.id.imageView1);
image.setImageResource(R.drawable.logo);
edittext = (EditText)findViewById(R.id.edittext);
settings= getBaseContext().getSharedPreferences(PREFS_NAME,Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("sharedString", "Shared Preference Data");
editor.commit();
String returnString=settings.getString("sharedString","Couldn't load the data");
edittext.setText(returnString);
}
Before to use the code first look about thee shared Preferences and their examples.
SharedPreference
SharedPreferences Example
Hope it should work. Please let me know.If it not working means tell me what you want to do actually.
its a very common mistake .. I should initialize the editText before calling a method on it by
edittext =(EditText)findViewById(R.id.edit_message);

I am unable to get Shared Preferences of other application

I am new to Android.I am trying access SharedPreferences of one application in another application.
But i am not getting those values.
My code was posted below.
Create.java in SharedPref1
package com.example.sharedpref1;
public class Create extends Activity implements OnClickListener{
EditText et1,et2;
Button btn;
String LogID,Pwd;
public SharedPreferences loginDetails;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.create);
et1 = (EditText)findViewById(R.id.etC1);
et2 = (EditText)findViewById(R.id.etC2);
btn = (Button)findViewById(R.id.bCreate);
loginDetails = getSharedPreferences("logid", MODE_WORLD_READABLE);
btn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.bCreate)
{
LogID = et1.getText().toString();
Pwd = et2.getText().toString();
Toast.makeText(getApplicationContext(), "User Profile Createad With\nUser ID: "+LogID +"\nPassword: "+Pwd, Toast.LENGTH_LONG).show();
SharedPreferences.Editor store = loginDetails.edit();
store.putString("logid", LogID);
store.putString("pass", Pwd);
store.commit();
finish();
}
}
}
Show.java in SharedPref2
package com.example.sharedpref2;
public class Show extends Activity implements OnClickListener{
EditText log,pwd;
Button back;
public SharedPreferences loginDetails;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.show);
log = (EditText)findViewById(R.id.etid);
pwd = (EditText)findViewById(R.id.etPwd);
back = (Button)findViewById(R.id.bBack);
back.setOnClickListener(this);
loginDetails = getSharedPreferences("logid", MODE_WORLD_READABLE);
log.setText(loginDetails.getString("logid", "defValue"));
pwd.setText(loginDetails.getString("pass", "defValue"));
}
}
I am getting values as below
I am trying access SharedPreferences of one application in another application.
This is a bad idea. Quoting the documentation for MODE_MULTI_PROCESS:
SharedPreference loading flag: when set, the file on disk will be checked for modification even if the shared preferences instance is already loaded in this process. This behavior is sometimes desired in cases where the application has multiple processes, all writing to the same SharedPreferences file. Generally there are better forms of communication between processes, though.
(emphasis added)
Moreover, the only way this could possibly work is if you make the SharedPreferences MODE_WORLD_READABLE, which means any app can get to those preferences. Programmers with talent would not do this, but would use other IPC mechanisms that would limit the communications to between the two applications and only with user permission, so as to not leak user data to others.
Finally, you do not have any code that will work across processes. getSharedPreferences() will get preferences for your own process. The only way I can think of to get a SharedPreferences from another process would require calling getSharedPreferences() on a Context created via createPackageContext(), and I haven't tried this, as I wouldn't dream of implementing what you are proposing.
If you need to share content between applications I would suggest using a content provider and not SharedPrefrences. In my experience SharedPrefernces is unreliable in these situations.
MODE_WORLD_READABLE is depracated in API level 17.
http://developer.android.com/reference/android/content/Context.html#MODE_WORLD_READABLE

Make and store string? [duplicate]

This question already has answers here:
Making data persistent in android
(2 answers)
Closed 10 years ago.
I got some help here today to make a string, which gets displayed after pressing the button:
public void addListenerOnButton() {
button1 = (Button) findViewById(R.id.buttoncalculate);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
EditText editText = (EditText)findViewById(R.id.editText1);
String text = editText.getText().toString();
Intent myIntent = new Intent(view.getContext(),Calculated.class);
myIntent.putExtra("mytext",text);
startActivity(myIntent);
}
});
And it gets displayed with:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.calculated);
mTextview = (TextView)findViewById(R.id.textView1);
mTextview.setText(getIntent().getStringExtra("mytext"));
}
But i noticed that that is only temporarily. As soon as i leave the app or go to an other activity, the string gets reset..
My question is: How can i store the local string to a real string and thus display it on other activities and even after the app gets closed?
Is it something with strings.xml?
Thanks
Is it something with strings.xml?
No - This is read only and used during compile.
How can i store the local string to a real string and thus display it on other activities and even after the app gets closed?
What you are talking about is persistent storage. You have 3 main options (there are others but as this is quite a broad topic I shall keep things simple):
Store it in a file
Save the string to a file and load it when the app starts or where ever you need it.
See this SO post on reading/writing text files Android write file
Use SharedPreferences
SO Post showing code on this android read/write user preferences
Probably the best answer for storing a simple string and easy to code. If you start your Activity and there is no intent passed in then you can load the string from SharedPreferences.
mTextview.setText(getIntent().getStringExtra("mytext"));
becomes
final String myString = getSharedPreferences("PREF_NAME", Context.MODE_PRIVATE).getString("SOME_STRING", "Default if not found");
mTextview.setText(myString);
The above is purely to demonstrate and probably needs tidying up and refining for your own needs.
Use a Database
Probably the worst option for you but worth thinking about. If you begin to have more than one String or complex option then SQLite is built into Android.
A good tutorial is found here http://www.vogella.com/articles/AndroidSQLite/article.html
I prefer to use Shared Preferences to store value.
MainActivity.java
public void addListenerOnButton() {
button1 = (Button) findViewById(R.id.buttoncalculate);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
EditText editText = (EditText)findViewById(R.id.editText1);
String text = editText.getText().toString();
SharedPreferences sp = getSharedPreferences("MyPrefs", MODE_PRIVATE);
Editor editor = sp.edit();
editor.putString("mytext", text);
editor.commit();
Intent myIntent = new Intent(view.getContext(),Calculated.class);
startActivity(myIntent);
}
});
Calculated.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.calculated);
mTextview = (TextView)findViewById(R.id.textView1);
mTextview.setText(getSharedPreferences("MyPrefs", MODE_PRIVATE).getString("mytext",null););
}

Custom Shared Preferences Android

I have set the Preferences in xml and I have the folowing Activity:
public class Preferencias extends PreferenceActivity {
//SharedPreferences prefs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
setContentView(R.layout.preferences);
Button bt=(Button)findViewById(R.id.selectPic);
TextView tv=(TextView) findViewById(R.id.textView1);
String def=getResources().getString(R.string.noDefinido);
tv.setText(PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("logo", def));
bt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setClassName(getApplicationContext(),
SDCardImagesActivity.class.getName());
startActivity(intent);
}
});
//habra que sacarlo de la red
String [] ofis ={"Venus", "Europa"};
ListPreference lp=new ListPreference(this);
lp.setValue("oficina");
lp.setEntries(ofis);
lp.setEntryValues(ofis);
lp.setTitle(R.string.oficina);
lp.setDefaultValue(ofis[1]);
getPreferenceScreen().addPreference(lp);
}
}
It works fine with the xml preferences but I also need to add a preference in code the reason of it is that the options of this ListPreference will come from the database (here I have the String array for now). The problem is the data changed for this preference is not persisted. When I make the changes I press back button I come back the value goes back to default value. How could I make sure this preference is saved too?
Thanks a lot
solved I included the preference without setting up its data then in code:
String [] ofis ={"Venus", "Europa"};
ListPreference lp=(ListPreference) getPreferenceManager().findPreference("oficina");
lp.setEntries(ofis);
lp.setEntryValues(ofis);
lp.setDefaultValue(ofis[1]);
works fine now

Categories

Resources