2017-01-10 14 views
0

共有環境設定をMeghdar.javaに設定したいと思っていますが、これは自分のコードですが動作しません。私のクラスの共有環境設定の使用方法

public class Meghdar { 

private final Context context; 
SharedPreferences sp; 
String Text; 

public Meghdar(Context context) { 
    super(); 
    this.context = context; 
    sp = context.getApplicationContext().getSharedPreferences("AppPreferences", Activity.MODE_PRIVATE); 

    Text = sp.getString ("text",null); 
}} 
+0

なぜあなたは、このためのアプリケーションコンテキストが必要です。 –

+0

このクラスのコンテキストをどうやって取得しているのですか?このクラスのコンストラクタをどこで呼びますか? –

+0

コンテキストはここでどのように役割を果たしていますか? –

答えて

0

次のようにするために変更します。これに

sp = context.getSharedPreferences("AppPreferences", Context.MODE_PRIVATE); 
0

変更を:

public class Meghdar { 

    SharedPreferences sp; 
    String text; 

    public Meghdar(Context context) { 
     super(); 
     sp = context.getSharedPreferences("AppPreferences", Context.MODE_PRIVATE); 

     text = sp.getString("text", ""); 
    } 
} 
+0

'context.MODE_PRIVATE'の代わりに' Context.MODE_PRIVATE'を使います。これは静的フィールドなので、クラス参照を介してアクセスする必要があります。 –

0

だけ(getApplicationContextを削除する)

コンテキストはgetActivityとgetApplicationContextのためです。

同時に両​​方を使用しないでください。それは三つの方法については、この

sp = context.getSharedPreferences("AppPreferences",context.MODE_PRIVATE);

0

例のようにする必要があり、あなたのコード内の

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);

public static SharedPreferences getPreferences(Context c){ 
    if (settings == null) { 
     settings = PreferenceManager.getDefaultSharedPreferences(c.getApplicationContext()); 
    } 
    return settings; 
} 
public static void save(int ndx, String val) { 
    SharedPreferences st = settings; 
    SharedPreferences.Editor editor = st.edit(); 
    editor.putString(CTBASE + ndx, val); 
    editor.commit(); 

} 
public static String get(int ndx) { 
    return settings.getString(CTBASE + ndx, DEFVAL); 
} 
0

おかげでたくさんの私はそれを変更するが、それは動作しません。 。 私もこのコードを使用して、私のMainActivity.java 多分エラーここにあること(これ強制停止)を参照してください

String a = editTextM.getText().toString(); 
       sharedPreferences = getApplicationContext().getSharedPreferences ("userB", 0); 
       editor = sharedPreferences.edit(); 
       editor.putString ("text", a); 
       editor.commit(); 
       Toast.makeText (getApplicationContext(), "با موفقیت ذخیره شد.", Toast.LENGTH_LONG).show(); 
       finish(); 
       startActivity (getIntent()); 
+0

誰も私を助けることができないのですか? – REZA

関連する問題