1

Ich kann nicht arbeiten, wie in einer anderen Klasse geteilt Präferenzen zu verwenden, dieWelcher Kontext für gemeinsame Einstellungen in einer anderen Klasse?

hier kein Fragment oder irgendetwas ist, ist mein Hauptaktivitätscode:

public class MainActivity extends AppCompatActivity { 

    Backgrounds backs; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     backs = new Backgrounds(this); 
     bg = (LinearLayout) findViewById(R.id.background); 
     bg.setBackgroundColor(getResources().getColor(backs.getBackground())); 
     } 
} 

Und hier eine Klasse meines Hintergrunds ist:

public class Backgrounds { 
    Integer colors[] = { 
      R.color.red, 
      R.color.pink, 
      R.color.purple, 
    }; 

    private context; 
    SharedPreferences sharedPref = context.getSharedPreferences("file", 0); 
    SharedPreferences.Editor editor = sharedPref.edit(); 
    int i = sharedPref.getInt("background", -1); 
    public Backgrounds(Context context) 
    { 
     this.context = context 
    } 
    public int getBackground() 
    { 
     i++; 
     try{ 
      editor.putInt("factIndex", i); 
      editor.commit(); 
      return colors[i]; 
     }catch (Exception e){ 
      i = 0; 
      editor.putInt("factIndex", i); 
      editor.commit(); 
      return colors[i]; 
     } 
    } 
} 

Ich habe diese vielen Möglichkeiten ausprobiert. Ich bin fast sicher, dass es ein Problem mit dem Kontext Teil des Codes ist, wie ich diesen Fehler:

Verursacht durch: java.lang.NullPointerException: Der Versuch, virtuelle Methode ‚aufzurufen android.content.SharedPreferences android.content.Context .getSharedPreferences (java.lang.String, int) 'auf einem Nullobjekt Referenz

Ich habe es auch versucht mit context.getApplicationContext(), aber der Fehler war ähnlich. Ich dachte es könnte sein, weil ich das Assing des Backs-Objekts in onCreate() verschieben musste, aber das funktioniert immer noch nicht. Ich habe das Projekt gereinigt und Dateien mit Gradle synchronisiert, aber das Programm stürzt immer noch ab, bevor es lädt. Der Code funktioniert perfekt beim Entfernen von SharedPrefrences.

+0

An dem Punkt, Sie 'sharedPref' zuweisen machen,' context' ist 'null'. Verschieben Sie die Zuordnung von 'sharedPref' und' editor' zum Konstruktor – Bene

Antwort

1

Sie verwenden den context vor dem Empfang es außerhalb Konstruktor bedeuten oder sagen, bevor Konstruktor tun noch ausgeführt werden, so dass es wie

SharedPreferences sharedPref ; 
    SharedPreferences.Editor editor; 
    int i = sharedPref.getInt("background", -1); 

    // before this , you cannot use the context reference ,it will be null 
    public Backgrounds(Context context) 
    { 
     this.context = context 
     // receive the context here and now you can safely use it 
     sharedPref = context.getSharedPreferences("file", 0) 
     editor = sharedPref.edit() 
    } 
+1

Danke. Dies funktioniert, obwohl diejenigen, die ich empfehle, die Definitionen nach dem Konstruktor nicht funktionieren –

1

Ihre Bewegen Sie diesen Code

SharedPreferences sharedPref = context.getSharedPreferences("file", 0); 
SharedPreferences.Editor editor = sharedPref.edit(); 

nach

SharedPreferences sharedPref; 
SharedPreferences.Editor editor 
public Backgrounds(Context context) 
{ 
    this.context = context 
    sharedPref = context.getSharedPreferences("file", 0); 
    editor = sharedPref.edit(); 
} 

weil seine hier initialing. davor ist es null.

+0

Me. Probieren Sie es aus, der Konstruktor wird immer noch als zweiter aufgerufen. Es spielt keine Rolle, wo Sie Member-Variablen platzieren. – Bene

+0

Es war mein Tippfehler! – Piyush

3

Dies ist für Common-Klasse für Preference.

public class Preference { 
    private final static String PREF_FILE = "PREF"; 

    /** 
    * Set a string shared preference 
    * 
    * @param key - Key to set shared preference 
    * @param value - Value for the key 
    */ 
    public static void setSharedPreferenceString(Context context, String key, String value) { 
     SharedPreferences settings = context.getSharedPreferences(PREF_FILE, 0); 
     SharedPreferences.Editor editor = settings.edit(); 
     editor.putString(key, value); 
     editor.apply(); 
    } 

    /** 
    * Set a integer shared preference 
    * 
    * @param key - Key to set shared preference 
    * @param value - Value for the key 
    */ 
    public static void setSharedPreferenceInt(Context context, String key, int value) { 
     SharedPreferences settings = context.getSharedPreferences(PREF_FILE, 0); 
     SharedPreferences.Editor editor = settings.edit(); 
     editor.putInt(key, value); 
     editor.apply(); 
    } 

    /** 
    * Set a Boolean shared preference 
    * 
    * @param key - Key to set shared preference 
    * @param value - Value for the key 
    */ 
    public static void setSharedPreferenceBoolean(Context context, String key, boolean value) { 
     SharedPreferences settings = context.getSharedPreferences(PREF_FILE, 0); 
     SharedPreferences.Editor editor = settings.edit(); 
     editor.putBoolean(key, value); 
     editor.apply(); 
    } 

    /** 
    * Get a string shared preference 
    * 
    * @param key  - Key to look up in shared preferences. 
    * @param defValue - Default value to be returned if shared preference isn't found. 
    * @return value - String containing value of the shared preference if found. 
    */ 
    public static String getSharedPreferenceString(Context context, String key, String defValue) { 
     SharedPreferences settings = context.getSharedPreferences(PREF_FILE, 0); 
     return settings.getString(key, defValue); 
    } 

    /** 
    * Get a integer shared preference 
    * 
    * @param key  - Key to look up in shared preferences. 
    * @param defValue - Default value to be returned if shared preference isn't found. 
    * @return value - String containing value of the shared preference if found. 
    */ 
    public static int getSharedPreferenceInt(Context context, String key, int defValue) { 
     SharedPreferences settings = context.getSharedPreferences(PREF_FILE, 0); 
     return settings.getInt(key, defValue); 
    } 

    /** 
    * Get a boolean shared preference 
    * 
    * @param key  - Key to look up in shared preferences. 
    * @param defValue - Default value to be returned if shared preference isn't found. 
    * @return value - String containing value of the shared preference if found. 
    */ 
    public static boolean getSharedPreferenceBoolean(Context context, String key, boolean defValue) { 
     SharedPreferences settings = context.getSharedPreferences(PREF_FILE, 0); 
     return settings.getBoolean(key, defValue); 
    } 
} 

dies ist die Nutzung für Get und Set Preference

Preference.setSharedPreferenceString(this, "Key", "Value") 
Preference.getSharedPreferenceString(this, "Key", "default_Value") 

Sie können überall in der Anwendung verwenden.

1

Nicht speichern Kontext als ein Feld ist es ein potenzielles Speicherleck. Der beste Weg, es ist wie @Shanmugavel GK unten geschrieben habe, eine statische Methoden erstellen oder mindestens

this.context = context.getApplicationContext(); 
Verwandte Themen