1

I need to have some information saved, what I have used in the past is sharedpreferences...

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("Data", (Data));
editor.commit();

So I would do something like this to save the Data, however for this project I am using the public class Tab3 extends View implements OnTouchListener type of class and Im not sure if thats why this isnt working but its not I cant use the Shared Prefences onTouch I get an error on getSharedPreferences saying "The method getSharedPreferences(String, int) is undefined for the type Tab3" what do I need to do in order to save this data in some way so I can use it later on in my app?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Michael Zeuner
  • 1,736
  • 3
  • 15
  • 23

2 Answers2

3

You need a context to get access to shared preferences. The best way is to create MyApplication as a descendant of Application class, instantiate there the preferences and use them in the rest of your application as MyApplication.preferences:

public class MyApplication extends Application {
    public static SharedPreferences preferences;

    @Override
    public void onCreate() {
        super.onCreate();

        preferences = getSharedPreferences( getPackageName() + "_preferences", MODE_PRIVATE);

For example, if you need access to your preferences somewhere else, you may call this to read preferences:

String str = MyApplication.preferences.getString( KEY, DEFAULT );

Or you may call this to save something to the preferences:

MyApplication.preferences.edit().putString( KEY, VALUE ).commit();

(don't forget to call commit() after adding or changing preferences!)

lenik
  • 23,228
  • 4
  • 34
  • 43
  • could you edit this question to show me how I would save somthing using this then also how I would call it back? that would be great thanks! – Michael Zeuner May 18 '12 at 23:51
  • here is my code files , I am still very confussed on what I have done wrong, maybe this will help more... http://www.mediafire.com/?ztirv21vkjk2i8r , http://www.mediafire.com/?jchkydzjazwwfze , and http://www.mediafire.com/?llwi1r4zyvr0icy – Michael Zeuner May 19 '12 at 13:40
  • in your `SectionManager.java` you are supposed to use same `MyApplication.preferences` as in your other files. right now you have two different preferences, no wonder if you write to the one, the other stays as it was before. – lenik May 19 '12 at 14:46
  • I changed it to that and "DataInfo" it still gets passed through as "Unknown"? here is the file, make sure I did what you ment. http://www.mediafire.com/?8148t4u9z5r8iiu – Michael Zeuner May 19 '12 at 16:49
  • looks like you use different KEY argument for `putString` and for `getString`, which is 'Data' and 'DataInfo'. Also, the value you save is the string 'Unknow', which may easily be confused with 'Unknown' -- please change it to something different as well as the KEY mentioned above. – lenik May 19 '12 at 17:01
1

I'd do what lenik says but don't make them static, lazy init them instead.

public class MyApplication extends Application {
    public SharedPreferences preferences;

    public SharedPreferences getSharedPrefs(){
         if(preferences == null){
              preferences = getSharedPreferences( getPackageName() + "_preferences", MODE_PRIVATE);
         }
         return preferences;
    }

Then in your view:

 MyApplication app = (MyApplication) getContext().getApplicationContext();
 SharedPreferences settings = app.getSharedPrefs();

As eric says this Application class needs to be declared in your manifest:

<application android:name=".MyApplication" 
       android:icon="@drawable/icon" 
       android:label="@string/app_name">

Reference:

getApplicationContext()

Android Global Vars


edit

(From your comment) the issue is that you aren't actually saving any data, this line doesn't make sense you aren't actually saving a variable:

 editor.putString("Data", (Data));

Here is an example of the above in use:

MyApplication app = (MyApplication) getContext().getApplicationContext();
SharedPreferences settings = app.getSharedPrefs();
String str = settings.getString("YourKey", null);

And to save something to the preferences:

settings.edit().putString("YourKey", "valueToSave").commit();

A more specific example of using in a custom View would be:

public class MyView extends View {

   SharedPreferences settings;

     // Other constructors that you may use also need the init() method

     public MyView(Context context){
         super(context);
         init();
     }

      private void init(){
         MyApplication app = (MyApplication) getContext().getApplicationContext();
         settings = app.getSharedPrefs();
      }

      private void someMethod(){ // or onTouch() etc
          settings.edit().putString("YourKey", "valueToSave").commit(); //Save your data
      }

      private void someOtherMethod(){
          String str = settings.getString("YourKey", null); //Retrieve your data
      }

}
Community
  • 1
  • 1
Blundell
  • 75,855
  • 30
  • 208
  • 233
  • Great! so how will I save stuff to this then call it back later now? – Michael Zeuner May 18 '12 at 23:35
  • @MichaelZeuner just like you have written in your question, once you have the instance of sharedpreferences use it however you want – Blundell May 18 '12 at 23:38
  • Im still a bit confused what I have to save it is `MyApplication app = (MyApplication) getContext().getApplicationContext(); SharedPreferences settings = app.getSharedPrefs(); SharedPreferences.Editor editor = settings.edit(); editor.putString("Data", (Data)); editor.commit();` then to call it back I have `MyApplication app = (MyApplication) getContext().getApplicationContext(); SharedPreferences settings = app.getSharedPrefs(); Data = (settings.getString("Data", "unKnown"));` what have I done wrong? – Michael Zeuner May 18 '12 at 23:49
  • @Blundell you missed the whole point. if you don't make them static, you won't be able to access preferences from the places where there's no `context` around, which is the whole purpose of this exercise -- to make preferences available everywhere. – lenik May 19 '12 at 01:09
  • @lenik He wanted SharedPreferences in a `View` class. Here you **always** have a context. – Blundell May 19 '12 at 08:00
  • @MichaelZeuner You haven't dont anything wrong just check (Log out) what you are saving and what it retrieves. I have edited the answer – Blundell May 19 '12 at 08:10
  • @Blundell so, instead of simple, elegant solution, which works 100% if the time, you offer the one which is quite cumbersome and, as you are aware, breaks as soon as he departs from using `View`. don't you think it's a cruel thing to do with a beginner? – lenik May 19 '12 at 11:04
  • @lenik Your solution is untestable (unit tests) and in the real world would never be used in production code. His question was specific to `View` so I gave him the best answer available, afar from being cumbersome it is quite elegant and can be in any Android custom component – Blundell May 19 '12 at 11:12