source

Android에서 Shared Preferences를 사용하여 값을 저장, 가져오기 및 편집하는 방법

factcode 2023. 7. 3. 23:22
반응형

Android에서 Shared Preferences를 사용하여 값을 저장, 가져오기 및 편집하는 방법

시간 값을 저장하고 싶은데 검색하고 편집해야 합니다.을 어떻게 합니까?SharedPreferences이걸 하기 위해서요?

공유 환경설정을 얻으려면 활동에서 다음 방법을 사용합니다.

SharedPreferences prefs = this.getSharedPreferences(
      "com.example.app", Context.MODE_PRIVATE);

기본 설정 읽기

String dateTimeKey = "com.example.app.datetime";

// use a default value using new Date()
long l = prefs.getLong(dateTimeKey, new Date().getTime()); 

환경설정 편집 및 저장 방법

Date dt = getSomeDate();
prefs.edit().putLong(dateTimeKey, dt.getTime()).apply();

Android sdk의 샘플 디렉터리에는 공유 기본 설정을 검색하고 저장하는 예제가 포함되어 있습니다.위치:

<android-sdk-home>/samples/android-<platformversion>/ApiDemos directory

편집==>

나는 알아차렸다, 차이점을 쓰는 것이 중요합니다.commit()그리고.apply()여기도 마찬가지야.

commit() 답례의true값이 성공적으로 저장된 경우 그렇지 않은 경우false값을 공유 기본 설정에 동기화하여 저장합니다.

apply() 2.3에 추가되었으며 성공 또는 실패에 대한 값을 반환하지 않습니다.값을 공유 환경설정에 즉시 저장하지만 비동기 커밋을 시작합니다.자세한 내용은 여기에 있습니다.

공유 기본 설정에 값을 저장하는 방법

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Name","Harneet");
editor.apply();

공유 기본 설정에서 값을 검색하는 방법

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = preferences.getString("Name", "");
if(!name.equalsIgnoreCase(""))
{
    name = name + "  Sethi";  /* Edit the value here*/
}

데이터를 편집하려면 다음과 같이 하십시오.sharedpreference

 SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
 editor.putString("text", mSaved.getText().toString());
 editor.putInt("selection-start", mSaved.getSelectionStart());
 editor.putInt("selection-end", mSaved.getSelectionEnd());
 editor.apply();

데이터를 검색하려면sharedpreference

SharedPreferences prefs = getPreferences(MODE_PRIVATE); 
String restoredText = prefs.getString("text", null);
if (restoredText != null) 
{
  //mSaved.setText(restoredText, TextView.BufferType.EDITABLE);
  int selectionStart = prefs.getInt("selection-start", -1);
  int selectionEnd = prefs.getInt("selection-end", -1);
  /*if (selectionStart != -1 && selectionEnd != -1)
  {
     mSaved.setSelection(selectionStart, selectionEnd);
  }*/
}

편집

API 데모 샘플에서 이 스니펫을 가져왔습니다.그것은 있었습니다.EditText거기에 있는 상자. 이점에서.context필요하지 않습니다.저도 같은 의견입니다.

쓰기:

SharedPreferences preferences = getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Authentication_Id",userid.getText().toString());
editor.putString("Authentication_Password",password.getText().toString());
editor.putString("Authentication_Status","true");
editor.apply();

읽는 방법:

SharedPreferences prfs = getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_PRIVATE);
String Astatus = prfs.getString("Authentication_Status", "");

가장 쉬운 방법:

저장 방법:

getPreferences(MODE_PRIVATE).edit().putString("Name of variable",value).commit();

검색 방법:

your_variable = getPreferences(MODE_PRIVATE).getString("Name of variable",default value);

Singleton 공유 기본 설정 클래스입니다.그것은 미래에 다른 사람들에게 도움이 될 수도 있습니다.

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;

public class SharedPref
{
    private static SharedPreferences mSharedPref;
    public static final String NAME = "NAME";
    public static final String AGE = "AGE";
    public static final String IS_SELECT = "IS_SELECT";

    private SharedPref()
    {

    }

    public static void init(Context context)
    {
        if(mSharedPref == null)
            mSharedPref = context.getSharedPreferences(context.getPackageName(), Activity.MODE_PRIVATE);
    }

    public static String read(String key, String defValue) {
        return mSharedPref.getString(key, defValue);
    }

    public static void write(String key, String value) {
        SharedPreferences.Editor prefsEditor = mSharedPref.edit();
        prefsEditor.putString(key, value);
        prefsEditor.commit();
    }

    public static boolean read(String key, boolean defValue) {
        return mSharedPref.getBoolean(key, defValue);
    }

    public static void write(String key, boolean value) {
        SharedPreferences.Editor prefsEditor = mSharedPref.edit();
        prefsEditor.putBoolean(key, value);
        prefsEditor.commit();
    }

    public static Integer read(String key, int defValue) {
        return mSharedPref.getInt(key, defValue);
    }

    public static void write(String key, Integer value) {
        SharedPreferences.Editor prefsEditor = mSharedPref.edit();
        prefsEditor.putInt(key, value).commit();
    }
}

간단히 전화하기SharedPref.init()MainActivity한번만

SharedPref.init(getApplicationContext());

데이터 쓰기

SharedPref.write(SharedPref.NAME, "XXXX");//save string in shared preference.
SharedPref.write(SharedPref.AGE, 25);//save int in shared preference.
SharedPref.write(SharedPref.IS_SELECT, true);//save boolean in shared preference.

데이터 읽기

String name = SharedPref.read(SharedPref.NAME, null);//read string in shared preference.
int age = SharedPref.read(SharedPref.AGE, 0);//read int in shared preference.
boolean isSelect = SharedPref.read(SharedPref.IS_SELECT, false);//read boolean in shared preference.

정보 저장 방법

SharedPreferences preferences = getSharedPreferences(PREFS_NAME,Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("username", username.getText().toString());
editor.putString("password", password.getText().toString());
editor.putString("logged", "logged");
editor.commit();

기본 설정을 재설정하려면

SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.commit();

팀의 다른 개발자와 함께 대규모 응용프로그램을 만들 때 코드가 흩어져 있거나 공유 기본 설정 인스턴스가 다를 필요 없이 모든 것이 잘 구성되도록 하려면 다음과 같은 작업을 수행할 수 있습니다.

//SharedPreferences manager class
public class SharedPrefs {

    //SharedPreferences file name
    private static String SHARED_PREFS_FILE_NAME = "my_app_shared_prefs";

    //here you can centralize all your shared prefs keys
    public static String KEY_MY_SHARED_BOOLEAN = "my_shared_boolean";
    public static String KEY_MY_SHARED_FOO = "my_shared_foo";

    //get the SharedPreferences object instance
    //create SharedPreferences file if not present


    private static SharedPreferences getPrefs(Context context) {
        return context.getSharedPreferences(SHARED_PREFS_FILE_NAME, Context.MODE_PRIVATE);
    }

    //Save Booleans
    public static void savePref(Context context, String key, boolean value) {
        getPrefs(context).edit().putBoolean(key, value).commit();       
    }

    //Get Booleans
    public static boolean getBoolean(Context context, String key) {
        return getPrefs(context).getBoolean(key, false);
    }

    //Get Booleans if not found return a predefined default value
    public static boolean getBoolean(Context context, String key, boolean defaultValue) {
        return getPrefs(context).getBoolean(key, defaultValue);
    }

    //Strings
    public static void save(Context context, String key, String value) {
        getPrefs(context).edit().putString(key, value).commit();
    }

    public static String getString(Context context, String key) {
        return getPrefs(context).getString(key, "");
    }

    public static String getString(Context context, String key, String defaultValue) {
        return getPrefs(context).getString(key, defaultValue);
    }

    //Integers
    public static void save(Context context, String key, int value) {
        getPrefs(context).edit().putInt(key, value).commit();
    }

    public static int getInt(Context context, String key) {
        return getPrefs(context).getInt(key, 0);
    }

    public static int getInt(Context context, String key, int defaultValue) {
        return getPrefs(context).getInt(key, defaultValue);
    }

    //Floats
    public static void save(Context context, String key, float value) {
        getPrefs(context).edit().putFloat(key, value).commit();
    }

    public static float getFloat(Context context, String key) {
        return getPrefs(context).getFloat(key, 0);
    }

    public static float getFloat(Context context, String key, float defaultValue) {
        return getPrefs(context).getFloat(key, defaultValue);
    }

    //Longs
    public static void save(Context context, String key, long value) {
        getPrefs(context).edit().putLong(key, value).commit();
    }

    public static long getLong(Context context, String key) {
        return getPrefs(context).getLong(key, 0);
    }

    public static long getLong(Context context, String key, long defaultValue) {
        return getPrefs(context).getLong(key, defaultValue);
    }

    //StringSets
    public static void save(Context context, String key, Set<String> value) {
        getPrefs(context).edit().putStringSet(key, value).commit();
    }

    public static Set<String> getStringSet(Context context, String key) {
        return getPrefs(context).getStringSet(key, null);
    }

    public static Set<String> getStringSet(Context context, String key, Set<String> defaultValue) {
        return getPrefs(context).getStringSet(key, defaultValue);
    }
}

활동에서 공유 환경설정을 이 방법으로 저장할 수 있습니다.

//saving a boolean into prefs
SharedPrefs.savePref(this, SharedPrefs.KEY_MY_SHARED_BOOLEAN, booleanVar);

공유 기본 설정을 검색할 수 있습니다.

//getting a boolean from prefs
booleanVar = SharedPrefs.getBoolean(this, SharedPrefs.KEY_MY_SHARED_BOOLEAN);

프로그램이든 는해 프 그 기 환 정 경 이 설 니 본 있 수PreferenceManagergetDefaultSharedPreferences(Context).

SharedPreference인스턴스 1은 getInt(String 키, intdefVal)를 사용하여 임의 기본 설정의 int 값을 검색할 수 있습니다.우리가 이 경우에 관심이 있는 선호도는 반대입니다.

우리의 경우, 우리는 수정할 수 있습니다.SharedPreference하고 edit을 합니다.putInt(String key, int newVal)우리는 애플리케이션을 초과하는 애플리케이션에 대한 카운트를 늘렸고 그에 따라 표시했습니다.

이를 추가로 데모하고 다시 시작한 후 응용 프로그램을 다시 시작할 때마다 카운트가 증가한다는 것을 알 수 있습니다.

기본 설정Demo.java

코드:

package org.example.preferences;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.TextView;

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

        // Get the app's shared preferences
        SharedPreferences app_preferences = 
        PreferenceManager.getDefaultSharedPreferences(this);

        // Get the value for the run counter
        int counter = app_preferences.getInt("counter", 0);

        // Update the TextView
        TextView text = (TextView) findViewById(R.id.text);
        text.setText("This app has been started " + counter + " times.");

        // Increment the counter
        SharedPreferences.Editor editor = app_preferences.edit();
        editor.putInt("counter", ++counter);
        editor.commit(); // Very important
    }
}

main.xml

코드:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:orientation="vertical"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent" >

        <TextView
            android:id="@+id/text"  
            android:layout_width="fill_parent" 
            android:layout_height="wrap_content" 
            android:text="@string/hello" />
</LinearLayout>

공유 기본 설정에 값을 저장하는 방법

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sp.edit();
editor.putString("Name","Jayesh");
editor.commit();

공유 기본 설정에서 값을 검색하는 방법

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String name = sp.getString("Name", ""); // Second parameter is the default value.

하는 방법에 대한 방법은 다음과 같습니다.SharedPreferences.

확할수있다니를 할 수 .MainActivity"지키고 싶은 것의 가치"를 저장할 클래스 또는 다른 클래스.작성자 및 독서자 클래스에 입력합니다.

public static final String GAME_PREFERENCES_LOGIN = "Login";

여기서InputClass 및 는입이고력고▁isOutputClass각각 출력 클래스입니다.

// This is a storage, put this in a class which you can extend or in both classes:
//(input and output)
public static final String GAME_PREFERENCES_LOGIN = "Login";

// String from the text input (can be from anywhere)
String login = inputLogin.getText().toString();

// then to add a value in InputCalss "SAVE",
SharedPreferences example = getSharedPreferences(GAME_PREFERENCES_LOGIN, 0);
Editor editor = example.edit();
editor.putString("value", login);
editor.commit();

이제 다른 교실처럼 다른 곳에서 사용할 수 있습니다.은 다은입니다.OutputClass.

SharedPreferences example = getSharedPreferences(GAME_PREFERENCES_LOGIN, 0);
String userString = example.getString("value", "defValue");

// the following will print it out in console
Logger.getLogger("Name of a OutputClass".class.getName()).log(Level.INFO, userString);

공유 기본 설정에 저장

SharedPreferences preferences = getSharedPreferences("temp", getApplicationContext().MODE_PRIVATE);
Editor editor = preferences.edit();
editor.putString("name", name);
editor.commit();

공유 기본 설정으로 가져오기

SharedPreferences preferences=getSharedPreferences("temp", getApplicationContext().MODE_PRIVATE);
String name=preferences.getString("name",null);

참고: "temp"는 공유 기본 설정 이름이고 "name"은 입력 값입니다.값이 종료되지 않으면 null을 반환합니다.

편집

SharedPreferences pref = getSharedPreferences("YourPref", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString("yourValue", value);
editor.commit();

읽어주세요

SharedPreferences pref = getSharedPreferences("YourPref", MODE_PRIVATE);
value= pref.getString("yourValue", "");
editor.putString("text", mSaved.getText().toString());

여기서,mSaved아무 것이나 될 수 있습니다TextView또는EditText우가끈 을추수 you서. 문자열을.단순히 문자열을 지정할 수 있습니다.여기서 텍스트는 다음에서 얻은 값을 유지하는 키입니다.mSaved(TextView또는EditText).

SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);

또한 "com.example.app"과 같은 패키지 이름을 사용하여 기본 설정 파일을 저장할 필요가 없습니다.원하는 이름을 직접 언급할 수 있습니다.이것이 도움이 되길 바랍니다!

공유 기본 설정의 기본 개념은 XML 파일에 항목을 저장하는 것입니다.

  1. xml 파일 경로를 선언합니다. (이 파일이 없으면 Android가 생성합니다.)이 파일이 있으면 Android에서 액세스할 수 있습니다.)

    SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
    
  2. 공유 기본 설정에 값 쓰기

    prefs.edit().putLong("preference_file_key", 1010101).apply();
    

    그자리의 preference_file_key공유 기본 설정 파일의 이름입니다. 리고그.1010101저장해야 하는 값입니다.

    apply()마지막으로 변경 사항을 저장합니다.▁▁you▁get에서 오류가 발생하면,apply()로 변경합니다.commit() 이 문장은 래서이대체장은그문▁is그입니다.

    prefs.edit().putLong("preference_file_key", 1010101).commit();
    
  3. 공유 기본 설정에서 읽기

    SharedPreferences sp = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
    long lsp = sp.getLong("preference_file_key", -1);
    

    lsp▁▁be 될 것입니다.-1한다면preference_file_key값이 없습니다.이 'preference_file_key'의 경우에는 이 값을 합니다.

쓰기 위한 전체 코드는 다음과 같습니다.

    SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);    // Declare xml file
    prefs.edit().putLong("preference_file_key", 1010101).apply();    // Write the value to key.

읽기 코드는 다음과 같습니다.

    SharedPreferences sf = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);    // Declare xml file
    long lsp = sp.getLong("preference_file_key", -1);    // Read the key and store in lsp

다음 방법을 사용하여 값을 저장할 수 있습니다.

public void savePreferencesForReasonCode(Context context,
    String key, String value) {
    SharedPreferences sharedPreferences = PreferenceManager
    .getDefaultSharedPreferences(context);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString(key, value);
    editor.commit();
    }

이 방법을 사용하면 Shared Preferences(공유 기본 설정)에서 값을 얻을 수 있습니다.

public String getPreferences(Context context, String prefKey) {
  SharedPreferences sharedPreferences = PreferenceManager
 .getDefaultSharedPreferences(context);
 return sharedPreferences.getString(prefKey, "");
}

여기서prefKey는 특정 값을 저장하는 데 사용한 키입니다.감사해요.

보호하기 위해

PreferenceManager.getDefaultSharedPreferences(this).edit().putString("VarName","your value").apply();

검색할 항목:

String name = PreferenceManager.getDefaultSharedPreferences(this).getString("VarName","defaultValue");

기본값은 : 이 기본 설정이 없는 경우 반환할 값입니다.

경우에 따라 getActivity() 또는 getApplicationContext()를 사용하여 "이것"을 변경할 수 있습니다.

공유 환경설정을 사용하는 방법에는 여러 가지가 있습니다.저는 여기서 데모 프로젝트를 만들었습니다.샘플의 핵심은 ApplicationContext & 단일 공유 기본 설정 개체를 사용하는 것입니다.다음 기능을 사용하여 Shared Preference를 사용하는 방법을 보여줍니다.

  • 싱글턴 클래스를 사용하여 공유 환경설정 액세스/업데이트
  • 공유 기본 설정 읽기/쓰기를 위해 컨텍스트를 항상 전달할 필요 없음
  • commit() 대신 apply()를 사용합니다.
  • apply(적용)는 비동기식 저장이며, 아무것도 반환하지 않으며, 먼저 메모리의 값을 업데이트하고 나중에 비동기식으로 디스크에 변경 사항을 기록합니다.
  • commit()는 synchronus save이며 결과에 따라 true/false를 반환합니다.변경 사항이 디스크에 동기화되어 기록됨
  • Android 2.3 이상 버전에서 작동합니다.

아래와 같은 사용 예:-

MyAppPreference.getInstance().setSampleStringKey("some_value");
String value= MyAppPreference.getInstance().getSampleStringKey();

여기에서 소스 코드 가져오기 및 자세한 API는 developer.android.com 에서 확인할 수 있습니다.

최고의 작업 방식

기본 설정 관리자를 사용하여 이름이 지정된 인터페이스 생성:

// Interface to save values in shared preferences and also for retrieve values from shared preferences
public interface PreferenceManager {

    SharedPreferences getPreferences();
    Editor editPreferences();

    void setString(String key, String value);
    String getString(String key);

    void setBoolean(String key, boolean value);
    boolean getBoolean(String key);

    void setInteger(String key, int value);
    int getInteger(String key);

    void setFloat(String key, float value);
    float getFloat(String key);

}

활동/조각함께 사용하는 방법:

public class HomeActivity extends AppCompatActivity implements PreferenceManager{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout_activity_home);
    }

    @Override
    public SharedPreferences getPreferences(){
        return getSharedPreferences("SP_TITLE", Context.MODE_PRIVATE);
    }

    @Override
    public SharedPreferences.Editor editPreferences(){
        return getPreferences().edit();
    }

    @Override
    public void setString(String key, String value) {
        editPreferences().putString(key, value).commit();
    }

    @Override
    public String getString(String key) {
        return getPreferences().getString(key, "");
    }

    @Override
    public void setBoolean(String key, boolean value) {
        editPreferences().putBoolean(key, value).commit();
    }

    @Override
    public boolean getBoolean(String key) {
        return  getPreferences().getBoolean(key, false);
    }

    @Override
    public void setInteger(String key, int value) {
        editPreferences().putInt(key, value).commit();
    }

    @Override
    public int getInteger(String key) {
        return getPreferences().getInt(key, 0);
    }

    @Override
    public void setFloat(String key, float value) {
        editPreferences().putFloat(key, value).commit();
    }

    @Override
    public float getFloat(String key) {
        return getPreferences().getFloat(key, 0);
    }
}

참고: Shared Preference 키를 SP_TITLE로 대체합니다.

예:

공유 환경에 문자열 저장:

setString("my_key", "my_value");

sharepeer에서 문자열 가져오기:

String strValue = getString("my_key");

이것이 당신에게 도움이 되기를 바랍니다.

공유 선호도를 위해 도우미 클래스를 작성합니다.

import android.content.Context;
import android.content.SharedPreferences;

/**
 * Created by mete_ on 23.12.2016.
 */
public class HelperSharedPref {

Context mContext;

public HelperSharedPref(Context mContext) {
    this.mContext = mContext;
}

/**
 *
 * @param key Constant RC
 * @param value Only String, Integer, Long, Float, Boolean types
 */
public void saveToSharedPref(String key, Object value) throws Exception {
    SharedPreferences.Editor editor = mContext.getSharedPreferences(key, Context.MODE_PRIVATE).edit();
    if (value instanceof String) {
        editor.putString(key, (String) value);
    } else if (value instanceof Integer) {
        editor.putInt(key, (Integer) value);
    } else if (value instanceof Long) {
        editor.putLong(key, (Long) value);
    } else if (value instanceof Float) {
        editor.putFloat(key, (Float) value);
    } else if (value instanceof Boolean) {
        editor.putBoolean(key, (Boolean) value);
    } else {
        throw new Exception("Unacceptable object type");
    }

    editor.commit();
}

/**
 * Return String
 * @param key
 * @return null default is null
 */
public String loadStringFromSharedPref(String key) throws Exception {
    SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
    String restoredText = prefs.getString(key, null);

    return restoredText;
}

/**
 * Return int
 * @param key
 * @return null default is -1
 */
public Integer loadIntegerFromSharedPref(String key) throws Exception {
    SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
    Integer restoredText = prefs.getInt(key, -1);

    return restoredText;
}

/**
 * Return float
 * @param key
 * @return null default is -1
 */
public Float loadFloatFromSharedPref(String key) throws Exception {
    SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
    Float restoredText = prefs.getFloat(key, -1);

    return restoredText;
}

/**
 * Return long
 * @param key
 * @return null default is -1
 */
public Long loadLongFromSharedPref(String key) throws Exception {
    SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
    Long restoredText = prefs.getLong(key, -1);

    return restoredText;
}

/**
 * Return boolean
 * @param key
 * @return null default is false
 */
public Boolean loadBooleanFromSharedPref(String key) throws Exception {
    SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
    Boolean restoredText = prefs.getBoolean(key, false);

    return restoredText;
}

}

공유 기본 설정에 값을 저장하는 방법

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sp.edit();
editor.putString("Name","Jayesh");
editor.commit();

공유 기본 설정에서 값을 검색하는 방법

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String name = sp.getString("Name", "");

이 예제를 사용하여 간단하고 명확하게 확인합니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.sairamkrishna.myapplication" >

   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >

      <activity
         android:name=".MainActivity"
         android:label="@string/app_name" >

         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>

      </activity>

   </application>
</manifest>
public class MainActivity extends AppCompatActivity {
   EditText ed1,ed2,ed3;
   Button b1;

   public static final String MyPREFERENCES = "MyPrefs" ;
   public static final String Name = "nameKey";
   public static final String Phone = "phoneKey";
   public static final String Email = "emailKey";

   SharedPreferences sharedpreferences;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      ed1=(EditText)findViewById(R.id.editText);
      ed2=(EditText)findViewById(R.id.editText2);
      ed3=(EditText)findViewById(R.id.editText3);

      b1=(Button)findViewById(R.id.button);
      sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

      b1.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            String n  = ed1.getText().toString();
            String ph  = ed2.getText().toString();
            String e  = ed3.getText().toString();

            SharedPreferences.Editor editor = sharedpreferences.edit();

            editor.putString(Name, n);
            editor.putString(Phone, ph);
            editor.putString(Email, e);
            editor.commit();
            Toast.makeText(MainActivity.this,"Thanks",Toast.LENGTH_LONG).show();
         }
      });
   }

}

간단한 라이브러리를 사용하여 공유 기본 설정으로 전화를 거는 방법은 다음과 같습니다.

TinyDB tinydb = new TinyDB(context);

tinydb.putInt("clickCount", 2);

tinydb.putString("userName", "john");
tinydb.putBoolean("isUserMale", true); 

tinydb.putList("MyUsers", mUsersArray);
tinydb.putImagePNG("DropBox/WorkImages", "MeAtlunch.png", lunchBitmap);

//These plus the corresponding get methods are all Included

여기에 Shared Preferences를 사용할 때 이 질문에 대한 대부분의 스니펫에 MODE_PRIVATE와 같은 내용이 포함된다는 점을 추가하고 싶습니다.MODE_PRIVATE는 이 공유 환경설정에 기록한 내용을 응용프로그램에서만 읽을 수 있다는 것을 의미합니다.

어떤 키를 사용하여 getSharedPreferences() 메서드를 가져오든, Android는 해당 이름의 파일을 만들고 기본 설정 데이터를 저장합니다.또한 getSharedPreferences()는 응용 프로그램에 대한 여러 기본 설정 파일을 사용하려는 경우에 사용됩니다.단일 기본 설정 파일을 사용하고 모든 키-값 쌍을 저장하려면 getSharedPreference() 메서드를 사용합니다.왜 나를 포함한 모든 사람들이 위의 두 가지 차이를 이해하지 못한 채 getSharedPreferences() 맛을 사용하는지 이상합니다.

다음 비디오 튜토리얼은 https://www.youtube.com/watch?v=2PcAQ1NBy98 에 도움이 될 것입니다.

간편하고 간편한 :: "Android-Shared Preferences-Helper" 라이브러리

늦더라도 안 하는 것보다는 낫습니다.사용의 복잡성과 노력을 줄이기 위해 "Android-Shared Preferences-Helper" 라이브러리를 만들었습니다.SharedPreferences또한 일부 확장 기능도 제공합니다.다음과 같은 몇 가지 기능을 제공합니다.

  • 한 줄의 초기화 및 설정
  • 기본 환경설정 또는 사용자 정의 환경설정 파일을 사용할지 쉽게 선택
  • 각 데이터 유형에 대해 미리 정의된(데이터 유형 기본값) 및 사용자 정의 가능한(선택 가능한) 기본값
  • 추가 매개 변수만 사용하여 단일 사용에 대해 서로 다른 기본값을 설정할 수 있는 기능
  • 기본 클래스와 마찬가지로 OnSharedPreferenceChangeListener를 등록 및 등록 취소할 수 있습니다.
dependencies {
    ...
    ...
    compile(group: 'com.viralypatel.sharedpreferenceshelper', name: 'library', version: '1.1.0', ext: 'aar')
}

공유 우선권 선언도우미 개체: (클래스 수준에서 권장)

SharedPreferencesHelper sph; 

공유 기본 설정 인스턴스화도우미 개체: (Create() 메서드에서 권장됨)

// use one of the following ways to instantiate
sph = new SharedPreferencesHelper(this); //this will use default shared preferences
sph = new SharedPreferencesHelper(this, "myappprefs"); // this will create a named shared preference file
sph = new SharedPreferencesHelper(this, "myappprefs", 0); // this will allow you to specify a mode

공유 환경설정에 값 넣기

아주 간단합니다!기본 방식(공유 기본 설정 클래스 사용 시)과 달리 전화를 걸 필요가 없습니다..edit()그리고..commit()언제나

sph.putBoolean("boolKey", true);
sph.putInt("intKey", 123);
sph.putString("stringKey", "string value");
sph.putLong("longKey", 456876451);
sph.putFloat("floatKey", 1.51f);

// putStringSet is supported only for android versions above HONEYCOMB
Set name = new HashSet();
name.add("Viral");
name.add("Patel");
sph.putStringSet("name", name);

바로 그거야!값은 공유 환경설정에 저장됩니다.

공유 환경설정에서 값 가져오기

다시 한 번, 키 이름을 가진 간단한 메서드 호출 하나.

sph.getBoolean("boolKey");
sph.getInt("intKey");
sph.getString("stringKey");
sph.getLong("longKey");
sph.getFloat("floatKey");

// getStringSet is supported only for android versions above HONEYCOMB
sph.getStringSet("name");

다른 많은 확장 기능이 있습니다.

GitHub Repository 페이지에서 확장 기능, 사용 및 설치 지침 등의 세부 정보를 확인합니다.

나는 내 삶을 쉽게 만들기 위해 도우미 클래스를 만들었습니다.이 클래스는 일반 클래스이며 공유 기본 설정, 전자 메일 유효성, 날짜 시간 형식과 같은 앱에서 일반적으로 사용되는 많은 메서드가 있습니다.이 클래스를 코드에 복사하여 필요한 곳이면 어디서나 해당 메서드에 액세스할 수 있습니다.

 import android.app.AlertDialog;
 import android.app.ProgressDialog;
 import android.content.Context;
 import android.content.DialogInterface;
 import android.content.SharedPreferences;
 import android.support.v4.app.FragmentActivity;
 import android.view.inputmethod.InputMethodManager;
 import android.widget.EditText;
 import android.widget.Toast;

 import java.text.ParseException;
 import java.text.SimpleDateFormat;
 import java.util.Date;
 import java.util.Random;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 import java.util.regex.PatternSyntaxException;

/**
* Created by Zohaib Hassan on 3/4/2016.
*/
 public class Helper {

private static ProgressDialog pd;

public static void saveData(String key, String value, Context context) {
    SharedPreferences sp = context.getApplicationContext()
            .getSharedPreferences("appData", 0);
    SharedPreferences.Editor editor;
    editor = sp.edit();
    editor.putString(key, value);
    editor.commit();
}

public static void deleteData(String key, Context context){
    SharedPreferences sp = context.getApplicationContext()
            .getSharedPreferences("appData", 0);
    SharedPreferences.Editor editor;
    editor = sp.edit();
    editor.remove(key);
    editor.commit();

}

public static String getSaveData(String key, Context context) {
    SharedPreferences sp = context.getApplicationContext()
            .getSharedPreferences("appData", 0);
    String data = sp.getString(key, "");
    return data;

}




public static long dateToUnix(String dt, String format) {
    SimpleDateFormat formatter;
    Date date = null;
    long unixtime;
    formatter = new SimpleDateFormat(format);
    try {
        date = formatter.parse(dt);
    } catch (Exception ex) {

        ex.printStackTrace();
    }
    unixtime = date.getTime();
    return unixtime;

}

public static String getData(long unixTime, String formate) {

    long unixSeconds = unixTime;
    Date date = new Date(unixSeconds);
    SimpleDateFormat sdf = new SimpleDateFormat(formate);
    String formattedDate = sdf.format(date);
    return formattedDate;
}

public static String getFormattedDate(String date, String currentFormat,
                                      String desiredFormat) {
    return getData(dateToUnix(date, currentFormat), desiredFormat);
}




public static double distance(double lat1, double lon1, double lat2,
                              double lon2, char unit) {
    double theta = lon1 - lon2;
    double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2))
            + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2))
            * Math.cos(deg2rad(theta));
    dist = Math.acos(dist);
    dist = rad2deg(dist);
    dist = dist * 60 * 1.1515;
    if (unit == 'K') {
        dist = dist * 1.609344;
    } else if (unit == 'N') {
        dist = dist * 0.8684;
    }
    return (dist);
}

/* ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: */
/* :: This function converts decimal degrees to radians : */
/* ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: */
private static double deg2rad(double deg) {
    return (deg * Math.PI / 180.0);
}

/* ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: */
/* :: This function converts radians to decimal degrees : */
/* ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: */
private static double rad2deg(double rad) {
    return (rad * 180.0 / Math.PI);
}

public static int getRendNumber() {
    Random r = new Random();
    return r.nextInt(360);
}

public static void hideKeyboard(Context context, EditText editText) {
    InputMethodManager imm = (InputMethodManager) context
            .getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
}

public static void showLoder(Context context, String message) {
    pd = new ProgressDialog(context);

    pd.setCancelable(false);
    pd.setMessage(message);
    pd.show();
}

public static void showLoderImage(Context context, String message) {
    pd = new ProgressDialog(context);
    pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    pd.setCancelable(false);
    pd.setMessage(message);
    pd.show();
}

public static void dismissLoder() {
    pd.dismiss();
}

public static void toast(Context context, String text) {

    Toast.makeText(context, text, Toast.LENGTH_LONG).show();
}
/*
     public static Boolean connection(Context context) {
    ConnectionDetector connection = new ConnectionDetector(context);
    if (!connection.isConnectingToInternet()) {

        Helper.showAlert(context, "No Internet access...!");
        //Helper.toast(context, "No internet access..!");
        return false;
    } else
        return true;
}*/

public static void removeMapFrgment(FragmentActivity fa, int id) {

    android.support.v4.app.Fragment fragment;
    android.support.v4.app.FragmentManager fm;
    android.support.v4.app.FragmentTransaction ft;
    fm = fa.getSupportFragmentManager();
    fragment = fm.findFragmentById(id);
    ft = fa.getSupportFragmentManager().beginTransaction();
    ft.remove(fragment);
    ft.commit();

}

public static AlertDialog showDialog(Context context, String message) {
    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setMessage(message);

    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int id) {
            // TODO Auto-generated method stub

        }
    });

    return builder.create();
}

public static void showAlert(Context context, String message) {
    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setTitle("Alert");
    builder.setMessage(message)
            .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.dismiss();
                }
            }).show();
}

public static boolean isURL(String url) {
    if (url == null)
        return false;

    boolean foundMatch = false;
    try {
        Pattern regex = Pattern
                .compile(
                        "\\b(?:(https?|ftp|file)://|www\\.)?[-A-Z0-9+&#/%?=~_|$!:,.;]*[A-Z0-9+&@#/%=~_|$]\\.[-A-Z0-9+&@#/%?=~_|$!:,.;]*[A-Z0-9+&@#/%=~_|$]",
                        Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
        Matcher regexMatcher = regex.matcher(url);
        foundMatch = regexMatcher.matches();
        return foundMatch;
    } catch (PatternSyntaxException ex) {
        // Syntax error in the regular expression
        return false;
    }
}

public static boolean atLeastOneChr(String string) {
    if (string == null)
        return false;

    boolean foundMatch = false;
    try {
        Pattern regex = Pattern.compile("[a-zA-Z0-9]",
                Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
        Matcher regexMatcher = regex.matcher(string);
        foundMatch = regexMatcher.matches();
        return foundMatch;
    } catch (PatternSyntaxException ex) {
        // Syntax error in the regular expression
        return false;
    }
}

public static boolean isValidEmail(String email, Context context) {
    String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
    CharSequence inputStr = email;
    Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(inputStr);
    if (matcher.matches()) {
        return true;
    } else {
        // Helper.toast(context, "Email is not valid..!");

        return false;
    }
}

public static boolean isValidUserName(String email, Context context) {
    String expression = "^[0-9a-zA-Z]+$";
    CharSequence inputStr = email;
    Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(inputStr);
    if (matcher.matches()) {
        return true;
    } else {
        Helper.toast(context, "Username is not valid..!");
        return false;
    }
}

public static boolean isValidDateSlash(String inDate) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy");
    dateFormat.setLenient(false);
    try {
        dateFormat.parse(inDate.trim());
    } catch (ParseException pe) {
        return false;
    }
    return true;
}

public static boolean isValidDateDash(String inDate) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd-mm-yyyy");
    dateFormat.setLenient(false);
    try {
        dateFormat.parse(inDate.trim());
    } catch (ParseException pe) {
        return false;
    }
    return true;
}

public static boolean isValidDateDot(String inDate) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd.mm.yyyy");
    dateFormat.setLenient(false);
    try {
        dateFormat.parse(inDate.trim());
    } catch (ParseException pe) {
        return false;
    }
    return true;
}

}
SharedPreferences.Editor editor = getSharedPreferences("identifier", 
MODE_PRIVATE).edit();
//identifier is the unique to fetch data from your SharedPreference.


editor.putInt("keyword", 0); 
// saved value place with 0.
//use this "keyword" to fetch saved value again.
editor.commit();//important line without this line your value is not stored in preference   

// fetch the stored data using ....

SharedPreferences prefs = getSharedPreferences("identifier", MODE_PRIVATE); 
// here both identifier will same

int fetchvalue = prefs.getInt("keyword", 0);
// here keyword will same as used above.
// 0 is default value when you nothing save in preference that time fetch value is 0.

AdapterClass 또는 기타 항목에서 SharedPreferences를 사용해야 합니다.그 시간은 이 선언문을 사용하고 위에서 같은 엉덩이를 사용합니다.

SharedPreferences.Editor editor = context.getSharedPreferences("idetifier", 
Context.MODE_PRIVATE).edit();
SharedPreferences prefs = context.getSharedPreferences("identifier", Context.MODE_PRIVATE);

//here context is your application context

문자열 또는 부울 값의 경우

editor.putString("stringkeyword", "your string"); 
editor.putBoolean("booleankeyword","your boolean value");
editor.commit();

위와 동일한 데이터 가져오기

String fetchvalue = prefs.getString("keyword", "");
Boolean fetchvalue = prefs.getBoolean("keyword", "");

2.공유 선호 저장용

SharedPreferences.Editor editor = 
getSharedPreferences("DeviceToken",MODE_PRIVATE).edit();
                    editor.putString("DeviceTokenkey","ABABABABABABABB12345");
editor.apply();

2.동일한 용도의 검색에 사용됩니다.

    SharedPreferences prefs = getSharedPreferences("DeviceToken", 
 MODE_PRIVATE);
  String deviceToken = prefs.getString("DeviceTokenkey", null);

안드로이드에서 기본 설정을 사용할 도우미 클래스를 만들었습니다.

다음은 도우미 클래스입니다.

public class PrefsUtil {

public static SharedPreferences getPreference() {
    return PreferenceManager.getDefaultSharedPreferences(Applicatoin.getAppContext());
}

public static void putBoolean(String key, boolean value) {
    getPreference().edit().putBoolean(key, value)
            .apply();
}

public static boolean getBoolean(String key) {
    return getPreference().getBoolean(key, false);
}

public static void putInt(String key, int value) {

    getPreference().edit().putInt(key, value).apply();

}

public static void delKey(String key) {

    getPreference().edit().remove(key).apply();

}

}

전역 변수를 함수 방식으로 저장하고 검색합니다.테스트하려면 페이지에 텍스트 보기 항목이 있는지 확인하고 코드에서 두 줄의 주석을 제거한 후 실행합니다.그런 다음 두 줄을 다시 설명하고 실행합니다.
여기서 TextView의 ID는 사용자 이름과 암호입니다.

사용할 모든 클래스에서 마지막에 이 두 가지 루틴을 추가합니다.저는 이 루틴이 글로벌 루틴이 되길 원하지만, 방법을 모르겠습니다.효과가 있습니다.

변수는 어디에서나 사용할 수 있습니다.변수를 "내 파일"에 저장합니다.당신은 당신의 방식으로 그것을 바꿀 수 있습니다.

다음을 사용하여 호출합니다.

 storeSession("username","frans");
 storeSession("password","!2#4%");***

변수 사용자 이름은 "frans"로 채워지고 암호는 "!2#4%"로 채워집니다.다시 시작한 후에도 사용할 수 있습니다.

그리고 당신은 그것을 사용하여 검색합니다.

 password.setText(getSession(("password")));
 usernames.setText(getSession(("username")));

내 그리드의 전체 코드 아래.

    package nl.yentel.yenteldb2;
    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 android.widget.TextView;

    public class Grid extends AppCompatActivity {
    private TextView usernames;
    private TextView password;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_grid);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) 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();
            }
        });
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

      ***//  storeSession("username","frans.eilering@gmail.com");
        //storeSession("password","mijn wachtwoord");***
        password = (TextView) findViewById(R.id.password);
        password.setText(getSession(("password")));
        usernames=(TextView) findViewById(R.id.username);
        usernames.setText(getSession(("username")));
    }

    public void storeSession(String key, String waarde) { 
        SharedPreferences pref = getApplicationContext().getSharedPreferences("MyFile", MODE_PRIVATE);
        SharedPreferences.Editor editor = pref.edit();
        editor.putString(key, waarde);
        editor.commit();
    }

    public String getSession(String key) {
//http://androidexample.com/Android_SharedPreferences_Basics/index.php?view=article_discription&aid=126&aaid=146
        SharedPreferences pref = getApplicationContext().getSharedPreferences("MyFile", MODE_PRIVATE);
        SharedPreferences.Editor editor = pref.edit();
        String output = pref.getString(key, null);
        return output;
    }

    }

아래에서 텍스트 보기 항목을 찾을 수 있습니다.

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="usernames"
    android:id="@+id/username"
    android:layout_below="@+id/textView"
    android:layout_alignParentStart="true"
    android:layout_marginTop="39dp"
    android:hint="hier komt de username" />

 <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="password"
    android:id="@+id/password"
    android:layout_below="@+id/user"
    android:layout_alignParentStart="true"
    android:hint="hier komt het wachtwoord" />

언급URL : https://stackoverflow.com/questions/3624280/how-to-use-sharedpreferences-in-android-to-store-fetch-and-edit-values

반응형