Jak korzystać z SharedPreferences w Androidzie do przechowywania, pobierania i edytowania wartości [zamknięte]


599

Chcę zapisać wartość czasu i muszę ją pobrać i edytować. Jak mogę SharedPreferencesto zrobić?


Wdrożyłem opakowanie Generic SharedPreferences, spójrz: android-know-how-to.blogspot.co.il/2014/03/…
— TacB0sS

Uproszczone podejście byłoby za pomocą tej biblioteki: github.com/viralypatel/Android-SharedPreferences-Helper ... Extended szczegóły techniczne w moim odpowiedź tutaj ...
— AndroidMechanic - Wirusowe Patel

Odpowiedzi:


838

Aby uzyskać wspólne preferencje, użyj następującej metody:

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

Aby przeczytać preferencje:

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

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

Aby edytować i zapisać preferencje

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

Przykładowy katalog Android SDK zawiera przykład pobierania i przechowywania wspólnych preferencji. Znajduje się w:

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

Edytuj ==>

Zauważyłem, że ważne jest, aby również napisać różnicę między commit()i apply()tutaj.

commit()powrót truejeśli wartość zapisana pomyślnie inaczej false. Zapisuje wartości do SharedPreferences synchronicznie .

apply()został dodany w wersji 2.3 i nie zwraca żadnej wartości ani w przypadku sukcesu, ani niepowodzenia. Natychmiast zapisuje wartości do SharedPreferences, ale uruchamia asynchroniczne zatwierdzanie. Więcej szczegółów jest tutaj .


Więc następnym razem, gdy użytkownik uruchomi moją aplikację, zapisana wartość już tam jest i mogę ją pobrać ... prawda?
— Muhammad Maqsoodur Rehman

4
(Dla każdego, kto czyta powyższe) Tak, jest to arbitralne. W tym przykładzie po prostu zapisuje się bieżącą datę jako klucz „com.example.app.datetime”.
— MSpeed,

1
this.getSharedPreferencesdaje mi następujący błąd:The method getSharedPreferences(String, int) is undefined for the type MyActivity
— Si8

15
SharedPreferences.Editor.apply () został wprowadzony w Gingerbread w listopadzie 2010 r. (Po opublikowaniu tej odpowiedzi). W miarę możliwości używaj go zamiast commit (), ponieważ Apply () jest bardziej wydajny.
— UpLate

4
Editor.apply () wymaga interfejsu API poziomu 9 lub nowszego. poniżej użyj Editor.commit ()
— Lennart Rolland

283

Aby przechowywać wartości we wspólnych preferencjach:

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

Aby pobrać wartości z wspólnych preferencji:

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

17
Najbardziej podoba mi się ta odpowiedź, ponieważ korzysta z getDefaultSharedPreferences. Dla większości użytkowników uprości to, ponieważ te same preferencje są dostępne w całej aplikacji i nie musisz się martwić o nazewnictwo pliku preferencji. Więcej na ten temat tutaj: stackoverflow.com/a/6310080/1839500
— Dick Lucas

Zgadzam się ... Znalazłem to po wyciągnięciu włosów, próbując dowiedzieć się, dlaczego nie mogłem uzyskać dostępu do moich wspólnych preferencji z innej aktywności przy użyciu metody z zaakceptowanej odpowiedzi. Dzięki wielkie!
— You'reAGitForNotUsingGit

Jak mogę go użyć do zapisania i załadowania Map<DateTime, Integer>?
— Dmitry


164

Aby edytować dane zsharedpreference

 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();

Aby pobrać dane zsharedpreference

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);
  }*/
}

Edytować

Wziąłem ten fragment z próbki API Demo. Miał EditTexttam pudełko. W tym contextnie ma required.I am komentując to samo.


12
+1, ale użyj getPreferences (MODE_PRIVATE); zamiast getPreferences (0); dla czytelności.
— Key

Czym jest tutaj mSaved? Muszę zapisać 2 wartości ciągu.
— Muhammad Maqsoodur Rehman

Chciałbym również wiedzieć, czym jest mSaved. Nvm, myślę, że to editbox
— karlstackoverflow

1
co -1 oznacza w getInt?
— amr osama

1
Jest to wartość domyślna, która zostanie zwrócona, jeśli klucz (wybór-start) nie istnieje we wspólnych preferencjach. Może być dowolny i służy wyłącznie jako odniesienie.
— DeRagan

39

Pisać :

SharedPreferences preferences = getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_WORLD_WRITEABLE);
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();

Czytać :

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

MODE_WORLD_WRITEABLE jest przestarzałe.
— Christopher Smit

28

Najprostszy sposób:

Zapisać:

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

Aby pobrać:

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

Próbowałem tego między zajęciami i to nie działało. Czy w nazwie zmiennej należy zawrzeć strukturę pakietu?
— Gaʀʀʏ

Aby użyć tej struktury między działaniami, zastąp getPreferences (MODE_PRIVATE) PreferenManager.getDefaultSharedPreferences (twoją aktywnością)
— Lucian Novac

Użyj Apply () zamiast commit ()
— Vaibhav

18

Ustawianie wartości w preferencjach:

// MY_PREFS_NAME - a static String variable like: 
//public static final String MY_PREFS_NAME = "MyPrefsFile";
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
 editor.putString("name", "Elena");
 editor.putInt("idName", 12);
 editor.commit();

Pobierz dane z preferencji:

SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); 
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
  String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
  int idName = prefs.getInt("idName", 0); //0 is the default value.
}

więcej informacji:

Korzystanie z preferencji wspólnych

Wspólne preferencje


Co to jest MyPrefsFile? Plik XML działania preferencji?
— Martin Erlic,

17

Singleton Shared Preferences Class. może w przyszłości pomóc innym.

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();
    }
}

Wystarczy zadzwonić SharedPref.init()na MainActivityraz

SharedPref.init(getApplicationContext());

Aby zapisać dane

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.

Aby odczytać dane

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.

15

Do przechowywania informacji

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();

Aby zresetować preferencje

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

12

Jeśli tworzysz dużą aplikację z innymi programistami w swoim zespole i zamierzasz wszystko dobrze zorganizować bez rozproszonego kodu lub różnych instancji SharedPreferences, możesz zrobić coś takiego:

//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);
    }
}

W swojej działalności możesz w ten sposób zapisać SharedPreferences

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

i możesz w ten sposób odzyskać swoje SharedPreferences

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

12

W dowolnej aplikacji istnieją domyślne preferencje, do których można uzyskać dostęp za pośrednictwem PreferenceManagerinstancji i powiązanej z nią metody getDefaultSharedPreferences(Context).

Za pomocą SharedPreferenceinstancji można uzyskać wartość int dowolnej preferencji za pomocą getInt (klucz String, int defVal) . Preferencją, która nas interesuje w tym przypadku, jest przeciwna.

W naszym przypadku możemy zmodyfikować SharedPreferenceinstancję w naszym przypadku za pomocą funkcji edit () i użyć opcji putInt(String key, int newVal)Zwiększyliśmy liczbę naszych aplikacji, które trwają dłużej niż aplikacja i są odpowiednio wyświetlane.

Aby dodatkowo to zilustrować, uruchom ponownie i ponownie aplikuj, zauważysz, że liczba ta wzrośnie za każdym razem, gdy ponownie uruchomisz aplikację.

PreferencesDemo.java

Kod:

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

Kod:

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

8

Proste rozwiązanie, w jaki sposób przechowywać wartość logowania SharedPreferences.

Możesz rozszerzyć MainActivityklasę lub inną klasę, w której będziesz przechowywać „wartość czegoś, co chcesz zachować”. Umieść to w klasach pisarzy i czytelników:

public static final String GAME_PREFERENCES_LOGIN = "Login";

Oto odpowiednio InputClasswejście i OutputClassklasa wyjścia.

// 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();

Teraz możesz użyć go w innym miejscu, na przykład w innej klasie. Poniżej znajduje 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);

8

Przechowuj w SharedPreferences

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

Pobierz w SharedPreferences

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

Uwaga: „temp” to nazwa wspólnych preferencji, a „nazwa” to wartość wejściowa. jeśli wartość nie zostanie zakończona, zwróci null


Bardzo dobry i łatwy w użyciu. Ale tutaj jest Context.MODE_PRIVATE nie getApplicationContext (). MODE_PRIVATE
— Maria Gheorghe

7

Edytować

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

Czytać

SharedPreferences pref = getSharedPreferences("YourPref", MODE_PRIVATE);
value= pref.getString("yourValue", "");

6

Podstawową ideą SharedPreferences jest przechowywanie rzeczy w pliku XML.

  1. Zadeklaruj ścieżkę do pliku xml. (Jeśli nie masz tego pliku, Android go utworzy. Jeśli masz ten plik, Android będzie miał do niego dostęp).

    SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
  2. Zapisz wartość we Wspólnych preferencjach

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

    preference_file_keyto nazwa udostępnionych plików uprzywilejowane. I 1010101jest to wartość trzeba przechowywać.

    apply()w końcu należy zapisać zmiany. Jeśli pojawi się błąd z apply(), zmień go na commit(). Więc to zdanie alternatywne brzmi

    prefs.edit().putLong("preference_file_key", 1010101).commit();
  3. Czytaj z preferencji wspólnych

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

    lspbędzie, -1jeśli preference_file_keynie ma wartości. Jeśli „plik_ preferencji_klucz” ma wartość, zwróci jej wartość.

Cały kod do pisania to

    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.

Kod do odczytu to

    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

Editor.apply () wymaga interfejsu API poziomu 9 lub nowszego. poniżej użyj Editor.commit ()
— Lennart Rolland

6

Możesz zapisać wartość za pomocą tej metody:

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();
    }

Za pomocą tej metody możesz uzyskać wartość z SharedPreferences:

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

Oto prefKeyklucz użyty do zapisania określonej wartości. Dzięki.


Co z booleanami?
— Yousha Aleayoub

zapisz, używając tej linii: editor.putString (klucz, wartość); użyj tej linii: Boolean yourLocked = prefs.getBoolean („zablokowany”, false);
— Md. Sajedul Karim

6
editor.putString("text", mSaved.getText().toString());

Tutaj mSavedmoże być dowolny TextViewlub EditTextskąd możemy wyodrębnić ciąg. możesz po prostu podać ciąg. Tutaj tekst będzie kluczem, który przechowuje wartość uzyskaną z mSaved( TextViewlub EditText).

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

Ponadto nie ma potrzeby zapisywania pliku preferencji przy użyciu nazwy pakietu, tj. „Com.example.app”. Możesz podać swoje preferowane imię. Mam nadzieję że to pomoże !


5

Istnieje wiele sposobów, w jakie ludzie zalecają korzystanie z SharedPreferences . Zrobiłem tutaj projekt demo . Kluczowym punktem w przykładzie jest użycie ApplicationContext i pojedynczego obiektu sharedpreferences . To pokazuje, jak korzystać z SharedPreferences z następującymi funkcjami: -

  • Korzystanie z klasy singelton w celu uzyskania dostępu / aktualizacji SharedPreferences
  • Nie ma potrzeby przekazywania kontekstu zawsze do odczytu / zapisu SharedPreferences
  • Używa Apply () zamiast commit ()
  • Apply () jest asynchronicznym zapisem, nic nie zwraca, najpierw aktualizuje wartość w pamięci, a zmiany zapisywane są na dysku później asynchronicznie.
  • commit () jest synchronicznym zapisem, zwraca true / false na podstawie wyniku. Zmiany są zapisywane na dysku synchronicznie
  • działa na wersjach Androida 2.3+

Przykład użycia jak poniżej: -

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

Pobierz kod źródłowy tutaj, a szczegółowe API można znaleźć tutaj na developer.android.com


Hej, mam pytanie dotyczące wspólnych preferencji. Czy masz coś przeciwko temu? stackoverflow.com/questions/35713822/…
— Ruchir Baronia

5

Najlepsza praktyka w historii

Utwórz interfejs o nazwie PreferenceManager :

// 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);

}

Jak używać z Aktywnością / Fragmentem :

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

Uwaga: zamień klucz SharedPreference na SP_TITLE .

Przykłady:

Przechowuj ciąg w shareperence :

setString("my_key", "my_value");

Pobierz ciąg z shareperence :

String strValue = getString("my_key");

Mam nadzieję, że to ci pomoże.


Czy używam tego samego współużytkowanego obiektu preferencji do przechowywania wszystkiego, czy też tworzę nowe wspólne obiekty preferencji dla każdego innego elementu danych?
— Ruchir Baronia,

@Ruchir Baronia, nie trzeba tworzyć różnych obiektów, przy okazji nie trzeba inicjować obiektu wspólnych preferencji. Możesz zapisać powyżej. Daj mi znać, jeśli będzie to wymagane z mojej strony.
— Hiren Patel

Ok, dzięki. czy możesz mi z tym pomóc? stackoverflow.com/questions/35235759/…
— Ruchir Baronia

@Ruchir Baronia, możesz anulować wątek. Mam nadzieję, że to ci pomoże.
— Hiren Patel

Och, przepraszam, zadałem złe pytanie. Chciałem o to zapytać, chodzi o wspólne preferencje :) stackoverflow.com/questions/35244256/issue-with-if-statement/...
— Ruchir Baronia

5

Aby przechowywać wartości we wspólnych preferencjach:

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

Aby pobrać wartości z wspólnych preferencji:

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

4

zapisać

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

wycofać:

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

wartość domyślna to: Wartości do zwrócenia, jeśli ta preferencja nie istnieje.

w niektórych przypadkach możesz zmienić „ to ” za pomocą getActivity () lub getApplicationContext ()


Hej, mam pytanie dotyczące wspólnych preferencji. Czy masz coś przeciwko temu? stackoverflow.com/questions/35713822/…
— Ruchir Baronia

Tak, zrobiłem ... :)
— Ruchir Baronia

3

Piszę klasę pomocnika dla wspólnych preferencji:

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

}

3

Zastosuj ten przykład prosty, przejrzysty i sprawdzony

<?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();
         }
      });
   }

}

2

Korzystając z tej prostej biblioteki , oto jak wykonywać połączenia do SharedPreferences ..

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

2

Chciałem tutaj dodać, że większość fragmentów tego pytania będzie miała coś w rodzaju MODE_PRIVATE podczas korzystania z SharedPreferences. Cóż, MODE_PRIVATE oznacza, że ​​wszystko, co napiszesz w tej wspólnej preferencji, może być odczytane tylko przez twoją aplikację.

Bez względu na klucz przekazywany do metody getSharedPreferences (), android tworzy plik o tej nazwie i przechowuje w nim dane preferencji. Pamiętaj również, że getSharedPreferences () powinno być używane, gdy zamierzasz mieć wiele plików preferencji dla aplikacji. Jeśli zamierzasz używać jednego pliku preferencji i przechowywać w nim wszystkie pary klucz-wartość, użyj metody getSharedPreference (). To dziwne, dlaczego wszyscy (w tym ja) po prostu używają smaku getSharedPreferences (), nawet nie rozumiejąc różnicy między powyższymi dwoma.

Poniższy samouczek wideo powinien pomóc https://www.youtube.com/watch?v=2PcAQ1NBy98


2

Prosta i bezproblemowa biblioteka :: „Android-SharedPreferences-Helper”

Lepiej późno niż wcale: stworzyłem bibliotekę „Android-SharedPreferences-Helper”, aby zmniejszyć złożoność i wysiłek związany z używaniem SharedPreferences. Zapewnia także rozszerzoną funkcjonalność. Kilka rzeczy, które oferuje to:

  • Inicjalizacja i konfiguracja jednej linii
  • Łatwy wybór, czy użyć preferencji domyślnych, czy niestandardowego pliku preferencji
  • Wstępnie zdefiniowane (domyślne typy danych) i konfigurowalne (jakie możesz wybrać) wartości domyślne dla każdego typu danych
  • Możliwość ustawienia innej wartości domyślnej do jednorazowego użytku za pomocą dodatkowego parametru
  • Możesz zarejestrować i wyrejestrować OnSharedPreferenceChangeListener w taki sam sposób, jak w przypadku klasy domyślnej
dependencies {
    ...
    ...
    compile(group: 'com.viralypatel.sharedpreferenceshelper', name: 'library', version: '1.1.0', ext: 'aar')
}

Deklaracja obiektu SharedPreferencesHelper: (zalecane na poziomie klasy)

SharedPreferencesHelper sph; 

Tworzenie wystąpienia obiektu SharedPreferencesHelper: (zalecane w metodzie onCreate ())

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

Wpisywanie wartości do wspólnych preferencji

Dość proste! W przeciwieństwie do domyślnego sposobu (podczas korzystania z klasy SharedPreferences) NIE będziesz musiał dzwonić .edit()i .commit()zawsze.

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);

Otóż ​​to! Twoje wartości są przechowywane we wspólnych preferencjach.

Pobieranie wartości z wspólnych preferencji

Ponownie, tylko jedno proste wywołanie metody z nazwą klucza.

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");

Ma wiele innych rozszerzonych funkcji

Sprawdź szczegóły rozszerzonej funkcjonalności, instrukcji użytkowania i instalacji itp. Na stronie repozytorium GitHub .


Czy używam tego samego współużytkowanego obiektu preferencji do przechowywania wszystkiego, czy też tworzę nowe wspólne obiekty preferencji dla każdego innego elementu danych?
— Ruchir Baronia,

Powinieneś używać tego samego jak najwięcej. Taki jest sens tworzenia tej biblioteki.
— AndroidMechanic - Viral Patel

Hej, mam pytanie dotyczące wspólnych preferencji. Czy masz coś przeciwko temu? stackoverflow.com/questions/35713822/...
— Ruchir Baronia

2
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.

musisz użyć SharedPreferences w AdapterClass lub innym. tym razem po prostu skorzystaj z tej deklaracji i użyj tego samego tyłka powyżej.

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

//here context is your application context

dla wartości ciągu lub wartości logicznej

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

pobierz dane tak samo jak powyżej

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

2

2. dla Przechowywania we wspólnej preferencji

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

2. dla pobierania tego samego zastosowania

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

1

Tutaj utworzyłem klasę Pomocnika, aby używać preferencji w Androidzie.

To jest klasa pomocnicza:

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();

}

}

1

Do przechowywania i pobierania zmiennych globalnych w sposób funkcjonalny. Aby przetestować, upewnij się, że masz elementy Textview na swojej stronie, usuń komentarz z dwóch wierszy kodu i uruchom. Następnie skomentuj ponownie dwie linie i uruchom.
Tutaj identyfikatorem TextView jest nazwa użytkownika i hasło.

W każdej klasie, w której chcesz jej użyć, dodaj te dwie procedury na końcu. Chciałbym, aby ta procedura była procedurami globalnymi, ale nie wiem jak. To działa.

Zmienne są dostępne wszędzie. Przechowuje zmienne w „MyFile”. Możesz to zmienić na swój sposób.

Nazywasz to za pomocą

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

zmienna nazwa użytkownika zostanie wypełniona „frankami”, a hasło „! 2 # 4%”. Nawet po ponownym uruchomieniu są dostępne.

i odzyskujesz go za pomocą

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

poniżej całego kodu mojego grid.java

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

    }

poniżej znajdziesz elementy widoku tekstu

<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" />

1

Stworzyłem klasę pomocnika, aby ułatwić moje życie. Jest to klasa ogólna i ma wiele metod, które są powszechnie stosowane w aplikacjach, takich jak Preferencje wspólne, Ważność e-maila, Format daty i godziny. Skopiuj tę klasę do swojego kodu i uzyskaj dostęp do jej metod tam, gdzie potrzebujesz.

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

}
Korzystając z naszej strony potwierdzasz, że przeczytałeś(-aś) i rozumiesz nasze zasady używania plików cookie i zasady ochrony prywatności.
Licensed under cc by-sa 3.0 with attribution required.