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
}
}