How to pass sharedpreferences from one activity to another activity? - android

I have two activities in my project one activity is MainActivity and another is
Main2activity, In Main2activity I'm taking input from the user and storing it in SharedPreference, Now I want to pass this data to MainActivity and display that data to the user.
The code for Main2activity is
package com.example.to_doapp;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.EditText;
import java.io.Serializable;
import java.util.ArrayList;
public class Main2Activity extends AppCompatActivity {
public void BackMain ( View view )
{
Intent intent = new Intent( getApplicationContext() ,MainActivity.class ) ;
SharedPreferences sharedPreferences = this.getSharedPreferences( "com.example.to_doapp;", Context.MODE_PRIVATE);
EditText editText = ( EditText) findViewById( R.id.editText3) ;
String s = editText.getText().toString();
sharedPreferences.edit().putString("task" , s ) .apply();
//intent.putStringArrayListExtra("key",arr);
startActivity(intent);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
}
code foe Mainactivity is
package com.example.to_doapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.io.Serializable;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
public void onclick (View view){
Intent intent = new Intent(getApplicationContext(), Main2Activity.class );
startActivity(intent);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
Intent intent = getIntent();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I want to know how to pass sharedpreferences and how to display that data to user in listview.
Thank you for help in advance.

You can use SharedPreferences getString() method in your second activity.
Here is the documentation: https://developer.android.com/reference/android/content/SharedPreferences.html#getString(java.lang.String,%20java.lang.String)

SharedPreferences sharedPreferences = this.getSharedPreferences( "com.example.to_doapp;", Context.MODE_PRIVATE);
sharedPreferences.getString("task", "");
You can use the above code to get the data from shared preference any time until it is cleared.
But i would suggest you create a class for the same and carry out all the Preference related task in the same

The simplest way is:
Set SharedPref:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
Editor editor = prefs.edit();
editor.putString(PREF_NAME, "someValue");
editor.commit();
Get SharedPref:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
String yourValue = prefs.getString(PREF_NAME, "");

No need to pass SharedPreferences . you get any activity or fragment on SharedPreferences value..
SharedPreferences shared = getSharedPreferences("Your SharedPreferences name", MODE_PRIVATE);
String data= shared.getString("key", "");
Note : key should be same as edit or save data time used. also SharedPreferences name
same.

When you add a shared preference for the app, it can be accessed from anywhere within the app.
SharedPreferences shared = PreferenceManager.getDefaultSharedPreferences(getContext());
String data= shared.getString("nameOfValue", "");

I am sharing you easiest way to set and get sharedpreference data :
First make a class for Shared Preference like that :
public class MySharedPreferences {
private static String MY_PREFS = "MyPrefs";
private static String IS_LOGGED_IN = "is_logged_in";
private static String USERNAME_ID = "username"
public static MySharedPreferences instance;
private Context context;
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
public static MySharedPreferences getInstance(Context context) {
if (instance == null)
instance = new MySharedPreferences(context);
return instance;
}
private MySharedPreferences(Context context) {
this.context = context;
sharedPreferences = context.getSharedPreferences(MY_PREFS, Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
}
public void deleteAllSharePrefs(Context context){
this.context = context;
sharedPreferences = context.getSharedPreferences(MY_PREFS,Context.MODE_PRIVATE);
editor.clear().commit();
}
public Boolean getIsLoggedIn(boolean b) {
return sharedPreferences.getBoolean(IS_LOGGED_IN, false);
}
public void setIsLoggedIn(Boolean isLoggedIn) {
editor.putBoolean(IS_LOGGED_IN, isLoggedIn);
editor.commit();
}
public String getUsername() {
return sharedPreferences.getString(USERNAME_ID, "");
}
public void setUsername(String username) {
editor.putString(USERNAME_ID, username);
editor.commit();
}
then where you want to set SharedPreference :
public void BackMain ( View view ){
EditText editText = ( EditText) findViewById( R.id.editText3) ;
MySharedPreferences.getInstance(Main2Activity.this).setUsername(editText.getText().toString());
Intent intent = new Intent( getApplicationContext() ,MainActivity.class )
startActivity(intent);
}
Now, get SharedPreference in your Second Activity:
MySharedPreferences.getInstance(ACTIVITYNAME.this).getUsername();
or in Fragment :
MySharedPreferences.getInstance(getActivity()).getUsername();
or in Adapter :
MySharedPreferences.getInstance(context).getUsername();

Related

Sharedprefrences not saving?

When i try to save a variable to shared preferences then call it in an editext it is not being saved? I've been looking around for hours but i cannot find anything on it. I know that sharedPrefrences acts like a dictionary in a way but other than that i don't understand why this is not working :(
package com.example.gatorblocks;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.wearable.activity.WearableActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class block1Settings extends WearableActivity{
private TextView mTextView;
Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_block1_settings);
configureBackButton();
configureColor();
Button addTextButton = (Button) findViewById(R.id.Apply);
TextView simpleEditText = findViewById(R.id.simpleEditText);
SharedPreferences prefs = getSharedPreferences("classes.txt", 0);
simpleEditText.setText(prefs.getString("classes1","1-1")); //set textbox to equal current class
final EditText vEditText = (EditText) findViewById(R.id.simpleEditText);
mTextView = (TextView) findViewById(R.id.text);
// Enables Always-on
setAmbientEnabled();
addTextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String enteredText = vEditText.getText().toString(); //sets the array value of block to the editText
test(enteredText);
}
});
}
private void configureColor() {
Button Block1 = (Button) findViewById(R.id.colorButton);
Block1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(block1Settings.this, colorBlock1.class));
overridePendingTransition(R.anim.slide_in_right,R.anim.slide_out_left);
}
});
}
private void configureBackButton(){
Button backbutton = (Button) findViewById(R.id.backButton);
backbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(block1Settings.this, classes.class));
overridePendingTransition(R.anim.slide_in_left,R.anim.slide_out_right);
finish();
}
});
}
public void test(String enteredText){
SharedPreferences pref = getSharedPreferences("classes.txt", 0);
SharedPreferences.Editor editor = pref.edit();
editor.putString("class1", enteredText);
editor.apply();
}
}
How did you get data from SharedPreferences which is not saved? You saved data using key class1 and want to get it by classes1 which is not correct way. You have to use same key. Try using
SharedPreferences prefs = getSharedPreferences("classes.txt", 0);
simpleEditText.setText(prefs.getString("class1","1-1"));

SharedPreference is not working in checkbox

I want to fill the TextView of another activity based on preference on checkBox event but its working please help me to sort the issue..It is forcefully stopping.Please help in the if else statement part .what we need to write in activity 2 to select based on the checkBox in activity 1
Activity 1:
package com.example.rajatanurag.shoppingsites;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
public class Book extends AppCompatActivity {
Button b1,b2;
public static CheckBox cb1,cb2,cb3;
TextView tv1,tv2,tv3;
SharedPreferences sp1;
ImageView iv1,iv2,iv3;
String x,y,z;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book);
b1=(Button)findViewById(R.id.b1);
b2=(Button)findViewById(R.id.b2);
cb1=(CheckBox)findViewById(R.id.cb1);
cb2=(CheckBox)findViewById(R.id.cb2);
cb3=(CheckBox)findViewById(R.id.cb3);
tv1=(TextView)findViewById(R.id.tv4);
tv2=(TextView)findViewById(R.id.tv2);
tv3=(TextView)findViewById(R.id.tv3);
iv1=(ImageView)findViewById(R.id.iv1);
iv2=(ImageView)findViewById(R.id.iv2);
iv3=(ImageView)findViewById(R.id.iv3);
sp1=getSharedPreferences("SHOPPING",MODE_PRIVATE);
}
public void OnClick1(View view)
{
SharedPreferences.Editor editor = sp1.edit();
if(cb1.isChecked()==true) {
editor.putString("price1", tv1.getText().toString());
editor.putBoolean("x",true);
}
if(cb2.isChecked()==true)
{
editor.putString("price2",tv2.getText().toString());
editor.putBoolean("y",true);
}
if(cb3.isChecked()==true)
{
editor.putString("price3",tv3.getText().toString());
editor.putBoolean("z",true);
}
editor.commit();
Intent i=new Intent(this,MyCart.class);
startActivity(i);
}
}
2.Activity
package com.example.rajatanurag.shoppingsites;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MyCart extends AppCompatActivity {
SharedPreferences sp1;
TextView tv4,tv5,tv6;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_cart);
tv4=(TextView)findViewById(R.id.tv4);
sp1=getSharedPreferences("SHOPPING",MODE_PRIVATE);
if(Book.cb1.isChecked()==true){
String price11 = sp1.getString("price1", "");
tv4.setText(price11);
}
if(Book.cb1.isChecked()==true){
String price21=sp1.getString("price2","");
tv5.setText(price21);
}
if(Book.cb1.isChecked()==true){
String price31=sp1.getString("price3","");
tv6.setText(price31);
}
}
}
You shouldn't be using static variables for view members because you might get memory leaks. Also the views you are referencing are destroyed when activity is destroyed, so they are not accessible in your second activity. You can send checkboxes checked values as intent extras.
Put this in your Activity 1 in OnClick1() method:
Intent i=new Intent(this,MyCart.class);
i.putExtra("cb1", cb1.isChecked());
i.putExtra("cb2", cb2.isChecked());
i.putExtra("cb3", cb3.isChecked());
startActivity(i);
This is how you get values in Activity 2 (in onCreate() method):
Intent intent = getIntent();
if(intent.getBooleanExtra("cb1", false)){
String price11 = sp1.getString("price1", "");
tv4.setText(price11);
}
if(intent.getBooleanExtra("cb2", false)){
String price21=sp1.getString("price2","");
tv5.setText(price21);
}
if(intent.getBooleanExtra("cb3", false)){
String price31=sp1.getString("price3","");
tv6.setText(price31);
}
public void OnClick1(View view)
{
if(view.getID() == R.id.cb1)
{
if(cb1.isChecked())
editor.putBoolean("x",true);
else
editor.putBoolean("x",false);
}
}
In your second activity
sp1=getSharedPreferences("SHOPPING",MODE_PRIVATE);
boolean isChecked = sp1.getBoolean("x", false);
if(isChecked){
String price11 = sp1.getString("price1", "");
tv4.setText(price11);
}

Not saving String value in sharedPreferences

I am trying to save a string in sharedPreferences. I don't know what I did wrong but it doesn't save the String value.
this is the code
here I am saving String value "phone". notice its Fragment page
package com.world.bolandian.watchme;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.gson.Gson;
public class LoginFragment extends Fragment implements Listen {
Button loginBtn;
ServerRequest ser;
Connector c;
LoginCommunicationThread loginT;
private LoginUser logUser;
EditText phone,password;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_login, container, false);
}
public void setInterface(Connector c){
this.c=c;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ser=new ServerRequest();
ser.addServerName(Params.SERVER_URL);
ser.addServletName(Params.LOGIN_SERVLET);
ser.setResponse(this);
loginT = new LoginCommunicationThread(ser);
phone = (EditText)getActivity().findViewById(R.id.userTxt);
password = (EditText)getActivity().findViewById(R.id.passwordTxt);
loginBtn = (Button) getActivity().findViewById(R.id.loginBtn);
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//save phone number in sharedpreferences
SharedPreferences pref = getActivity().getPreferences(0);
SharedPreferences.Editor edt = pref.edit();
edt.putString("PHONE",String.valueOf(phone.getText()));
edt.commit();
Context context = getActivity();
PreferenceManager.getDefaultSharedPreferences(context).edit().putString("PHONE", String.valueOf(phone.getText()));
logUser = new LoginUser(phone.getText().toString(),password.getText().toString());
if (phone.getText().toString() == null)
{
Toast.makeText(getActivity(),"Please enter phone number", Toast.LENGTH_LONG).show();
}
if(password.getText().toString() == null)
{
Toast.makeText(getActivity(),"Please enter password", Toast.LENGTH_LONG).show();
}
else {
Gson g = new Gson();
String ans = g.toJson(logUser, LoginUser.class);
login(logUser);
}
}
});
}
public void login (LoginUser user)
{
LoginCommunicationThread con;
ServerRequest ser = new ServerRequest();
ser.setResponse(this);
Gson gson = new Gson();
String send = gson.toJson(user,LoginUser.class);
ser.addParamaters(Params.USER,send);
ser.addServerName(Params.SERVER_URL);
ser.addServletName(Params.LOGIN_SERVLET);
con = new LoginCommunicationThread(ser);
con.start();
}
#Override
public void good() {
Toast.makeText(getActivity(), "Welcome", Toast.LENGTH_LONG).show();
Intent i = new Intent(getActivity(),MainActivity.class);
startActivity(i);
}
#Override
public void notGood() {
Toast.makeText(getActivity(),"Wrong password or phone",Toast.LENGTH_LONG).show();
}
#Override
public void notGoodServerEroorr() {
Toast.makeText(getActivity(), "Connection Error please try again", Toast.LENGTH_LONG);
}
}
Here i extract the value "PHONE" but i keep getting null. for some reason it doesnt get the value and the default is null (This page is Activity)
package com.world.bolandian.watchme;
import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TabHost;
import android.widget.TextView;
import com.google.gson.Gson;
public class MainActivity extends Activity implements Listen {
private LockAndUnLock sendnotf;
TextView status;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
status = (TextView)findViewById(R.id.status);
TabHost tabHost = (TabHost) findViewById(R.id.tabHost);
tabHost.setup();
TabHost.TabSpec tabspec = tabHost.newTabSpec("main");
tabspec.setContent(R.id.main);
tabspec.setIndicator("Main");
tabHost.addTab(tabspec);
tabspec = tabHost.newTabSpec("gps");
tabspec.setContent(R.id.GPS);
tabspec.setIndicator("GPS");
tabHost.addTab(tabspec);
tabspec = tabHost.newTabSpec("info");
tabspec.setContent(R.id.INFO);
tabspec.setIndicator("Info");
tabHost.addTab(tabspec);
}
public void Lock (View view)
{
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(this);
String phone = sharedPreferences.getString("PHONE", null);
PreferenceManager.getDefaultSharedPreferences(this).getString("PHONE",
null);
sendnotf = new LockAndUnLock(phone,1); // 1 = true = lock
Gson g = new Gson();
String ans=g.toJson(sendnotf, LockAndUnLock.class);
sendLockAndUnlock(sendnotf);
if (status.getVisibility() != View.VISIBLE) {
status.setVisibility(View.VISIBLE);
}
status.setText("LOCKED");
status.setTextColor(Color.RED);
}
public void UnLock (View view)
{
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String phone = sharedPreferences.getString("PHONE",null);
sendnotf = new LockAndUnLock(phone,0); // 0 = false = unlock
Gson g = new Gson();
String ans=g.toJson(sendnotf, LockAndUnLock.class);
sendLockAndUnlock(sendnotf);
if (status.getVisibility() != View.VISIBLE) {
status.setVisibility(View.VISIBLE);
}
status.setText("OPEN");
status.setTextColor(Color.GREEN);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void good() {
}
#Override
public void notGood() {
}
#Override
public void notGoodServerEroorr() {
}
public void sendLockAndUnlock(LockAndUnLock sendnotf){
RegisterCommunicationThread con;
ServerRequest ser = new ServerRequest();
ser.setResponse(this);
Gson gson = new Gson();
String send = gson.toJson(sendnotf, LockAndUnLock.class);
ser.addParamaters(Params.LOCKANDUNLOCK,send);
ser.addServerName(Params.SERVER_URL);
ser.addServletName(Params.LOCKANDUNLOCK_SERVLET);
con = new RegisterCommunicationThread(ser);
con.start();
}
}
Problem is with different shared preferences objects. According to official documentation:
getPreferences (int mode)
Added in API level 1 Retrieve a SharedPreferences object for accessing
preferences that are private to this activity. This simply calls the
underlying getSharedPreferences(String, int) method by passing in this
activity's class name as the preferences name.
My suggestion is to use special entity for handling shared preferences. In your case it may look like following code
public class SharedPreferencesManager {
private static final String PREFERENCES_NAME = "your_name";//name for xml file
private final SharedPreferences sharedPreferences;
public SharedPreferencesManager(Context context) {
sharedPreferences = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE);
}
public String getPhone() {
return sharedPreferences.getString("PHONE", null);
}
public void savePhone(#NonNull String phone) {
sharedPreferences.edit().putString("PHONE", phone).apply(); //or commit for blocking save
}
}
Then replace all your direct call to SharedPreferences in Activity, Fragment with above object.

How do you save the data of an int, and then edit the number onclick of a button?

I am trying to have it so when you click one of the answeers (Q1A1 or Q1A2) it will add a number of points to the testScore int so I can then later call that in a later class so the score they got would be posted there. Thanks to anyone who helps in advance!
here's my code,
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
public class Test extends Activity implements OnClickListener
{
TextView Q1A1;
TextView Q1A2;
TextView test;
public static final String PREFS_NAME = "MyPrefsFile";
public static final int testScore = 0;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
Q1A1 = (TextView) findViewById(R.id.Q1A1);
Q1A2 = (TextView) findViewById(R.id.Q1A2);
Q1A1.setOnClickListener(this);
Q1A2.setOnClickListener(this);
test = (TextView) findViewById(R.id.test);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
test.setText(settings.getString("YourScore", "No Score"));
}
public void onClick(View v)
{
switch(v.getId())
{
case R.id.Q1A1:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("YourScore", (testScore + 10));
editor.commit();
//Intent FinalScore = new Intent(this, FinalScore.class);
//startActivity(FinalScore);
break;
case R.id.Q1A2:
break;
}
}
}
thanks for the help
You are are saving your score as an int but calling it as a string.
Change
test.setText(settings.getString("YourScore" , "No Score"));
To
test.setText(""+settings.getInt("YourScore" , 0));

Saving values at exit of an application

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.

Categories

Resources