3

I want to store three strings as user preferences for my app. I have a nice layout already set up, it's just a matter of saving the strings to the SharedPreferences. I would also like to know how I can retrieve these strings in the next activity. Below is my current code, I would greatly appreciate it if someone could show me how I can add this functionality to the code. This is a roadblock in my app I have been trying to get past for a few days now.

Code for main activity:

package com.amritayalur.mypowerschool;



import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;



public class MyPowerSchoolActivity extends Activity {
Button buttonSubmit;
TextView textViewTitle;
TextView textViewDesc;
EditText editTextURL, editTextUser, editTextPass;


 String str;
 String username;
 String password;
 String url;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);


    buttonSubmit = (Button) findViewById(R.id.buttonSubmit);
    textViewTitle = (TextView) findViewById(R.id.textViewTitle);
    textViewDesc = (TextView) findViewById(R.id.textViewDesc);

    editTextURL = (EditText) findViewById(R.id.editTextURL);
    editTextUser = (EditText) findViewById(R.id.editTextUser);
    editTextPass = (EditText) findViewById(R.id.editTextPass);
    //Start TextView
    textViewTitle.setText("MyPowerSchool");


    //button listener
    buttonSubmit.setOnClickListener(new View.OnClickListener() {

         @Override
            public void onClick(View v) 
            {
                if (  ( !editTextURL.getText().toString().equals("")) && (
!editTextUser.getText().toString().equals("")) && (
!editTextPass.getText().toString().equals("") ) ) 
                {

                    url = editTextURL.getText().toString();
                    username = editTextUser.getText().toString();
                    password = editTextPass.getText().toString();


                    // TODO Auto-generated method stub
                    //Intent i = new Intent( MyPowerSchoolActivity.this,
creds.class);    


                   //startActivity(i);



                }
            };




});}}

4 Answers 4

6

Just set up these class variables in the Activities you want to use SharedPreferences:

public static String MY_PREFS = "MY_PREFS";
private SharedPreferences mySharedPreferences;
int prefMode = Activity.MODE_PRIVATE;

And then to store string values:

SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putString("key1", "value1");
editor.putString("key2", "value2");
editor.putString("key3", "value3");

editor.commit(); // persist the values

To read them in another Activity/class:

mySharedPreferences = getSharedPreferences(MY_PREFS, prefMode);
String string1 = mySharedPreferences.getString("key1", null);
String string2 = mySharedPreferences.getString("key2", null);

This is not hard to look up and find examples of. By going to the documentation in Android Developers you will find a link to this useful site on how to use data storage on Android phones.

Sign up to request clarification or add additional context in comments.

2 Comments

I'm getting a force close for this. Can I put it inside my OnClick method?
You can read the stack trace in Logcat to see better what causes the forced close (exception). If it's NullPointerException then try replace the 'null' as second argument in getString("key1", null) with "", like this: getString("key1", ""). Needless to say, you need to put and commit the values first before reading them. Yes, you can do putString/commit and getString inside methods.
2

Somehow define your preference fields names. It is common practive to do it via final static field. It can be done in your activity class in some separate class. Give them some uniq names.

public static final String MY_PARAM_1 = "com.amritayalur.mypowerschool.PARAM_1";
public static final String MY_PARAM_2 = "com.amritayalur.mypowerschool.PARAM_2";

Get shared preference instance

// "this" is your activity or context
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); 

To put your strings in preferenes you need to create an editor

SharedPreferences.Editor editor = prefs.edit();

Then put your values

editor.putString(MY_PARAM_1, "First string");
editor.putString(MY_PARAM_2, "Second string");

Then you are done, commit your changes

editor.commit();

To get your values back use the getString method

// specify default value in case if preferences are empty or current key is not set
prefs.getString(MY_PARAM_1, "default value");

Comments

1

You can add multiple values like this:

preferences.edit()
      .putLong(DAYS_LEFT, premiumStatus.getDaysLeft())
      .putString(KEY, premiumStatus.getKey())
      .putString(ID, premiumStatus.getId())
      .apply();

Comments

0

First setup shared preference. For this, set this line before on create :

  private Context mContext; 

then put this in oncreate :

                    mContext = this;   

Then store your value on SharedPreferece:

 SharedPreferences settings = 
PreferenceManager.getDefaultSharedPreferences(mcontext); 
SharedPreferences.Editor editor = settings.edit();

url = editTextURL.getText().toString();
username = editTextUser.getText().toString();
password = editTextPass.getText().toString();

editor.putString("kye1", url);
editor.putString("kye2", username);
editor.putString("kye3", password);

Then retrieve your Value from another class (or from any where ) :

SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mcontext); 
 String value1=settings.getString("key1",""); // for url
 String value2=settings.getString("key2",""); // for name
 String value3=settings.getString("key3",""); // for password

Then set this "value1/2/3" any where.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.