bahman72313
جمعه 04 اردیبهشت 1394, 22:47 عصر
سلام دوستان من می خوام یک متد استاتیک ایجاد کرده و درونش از SharedPreferences ها استفاده کنم اما متاسفانه نمیدونم چرا از getSharedPreferences ایراد می گیره:
public static void func1(String str1, String str2)
{
SharedPreferences preferences = getSharedPreferences("tanzimat", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
...
...
}
کد زیر رو امتحان کردم و ایراد نگرفت اما برنامه کرش میکنه:
public static void func1(String str1, String str2)
{
SharedPreferences preferences = G.context.getSharedPreferences("tanzimat", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
...
...
}
tux-world
جمعه 04 اردیبهشت 1394, 23:10 عصر
من یه کلاس برای این کار نوشتم ازش به صورت استاتیک استفاده میکنم. میزارمش اینجا شما هم ازش استفاده کنید
import android.content.Context;
import android.content.SharedPreferences;
/**
* Shared Preferences Class, simple save and get data from android SharedPreferences
*
* @author mahdi pishguy
* @update Thursday, January 22, 2015
*/
public class SP {
private static SP _singletonInstance;
private SP() {}
public static synchronized SP getInstance() {
if (_singletonInstance == null)
_singletonInstance = new SP();
return _singletonInstance;
}
private SharedPreferences getPrefs() {
return getBaseContext().getSharedPreferences("Tsms", Context.MODE_PRIVATE);
}
public String getString(SharedPrefsTypes propertyName) {
return getPrefs().getString(propertyName.toString(), "");
}
public int getInt(SharedPrefsTypes propertyName) {
return getPrefs().getInt(propertyName.toString(), 0);
}
public long getLong(SharedPrefsTypes propertyName) {
return getPrefs().getLong(propertyName.toString(), 0);
}
public boolean getBoolean(SharedPrefsTypes propertyName) {
return getPrefs().getBoolean(propertyName.toString(), false);
}
public boolean getBoolean(SharedPrefsTypes propertyName, boolean value) {
return getPrefs().getBoolean(propertyName.toString(), value);
}
public void setString(SharedPrefsTypes propertyName, String value) {
getPrefs().edit().putString(propertyName.toString( ), value).commit();
}
public void setInt(SharedPrefsTypes propertyName, int value) {
getPrefs().edit().putInt(propertyName.toString(), value).commit();
}
public void setLong(SharedPrefsTypes propertyName, Long value) {
getPrefs().edit().putLong(propertyName.toString(), value).commit();
}
public void setBoolean(SharedPrefsTypes propertyName, boolean value) {
getPrefs().edit().putBoolean(propertyName.toString (), value).commit();
}
public enum SharedPrefsTypes {
LOGIN
}
}
طریقه استفاده :
برای ست کردن
SP.getInstance().setBoolean(SP.SharedPrefsTypes.LO GIN,true);
برای گت کردن
String sgn = SP.getInstance().getBoolean(SP.SharedPrefsTypes.LO GIN);
vBulletin® v4.2.5, Copyright ©2000-1403, Jelsoft Enterprises Ltd.