2016-07-16 7 views
0

私の最初のアクティビティーと2番目のアクティビティーに置かれたフラグメントの間の共有優先順位を使用しようとしています。コードは私がこれまで行ってきたことを示していますが、コンテキストを取得するのに問題があります。私も何をしているのかと思っています。おかげフラグメントとアクティビティー間の共有プリファレンスの使用

ヌルオブジェクトに ')android.content.Context android.content.Context.getApplicationContext(' 仮想メソッドを呼び出す試み 参照

READのPREFS

sharedPreferences = getSharedPreferences("alexcz", MODE_PRIVATE); 
String drawableString = sharedPreferences.getString("PARTICLE_TYPE", "null") 

書き込みプレフ

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     View view = inflater.inflate(R.layout.fragment_particle_type, container, false); 

     white_blur = (ImageButton)view.findViewById(R.id.white_blur); 
     green_blur = (ImageButton)view.findViewById(R.id.green_blur); 
     orange_blur = (ImageButton)view.findViewById(R.id.orange_blur); 
     pink_blur = (ImageButton)view.findViewById(R.id.pink_blur); 
     yellow_blur = (ImageButton)view.findViewById(R.id.yellow_blur); 
     blue_blur = (ImageButton)view.findViewById(R.id.blue_blur); 

     main main = new main(); 
     Context context = main.getApplicationContext(); 

     sharedPref = context.getSharedPreferences("alexcz", main.MODE_PRIVATE); 
     editor = sharedPref.edit(); 

editor.putString("PARTICLE_TYPE", "white_blur"); 

     setOnClickListeners(); 
     return view; 
    } 
+0

あなたは実際にどこにでも書いているわけではありません。あなたは 'editor'を使っていません。 – Vucko

答えて

3

はこれを行うことはありません:main main = new main();。代わりに:

Context context = getActivity().getApplicationContext(); 

フラグメントの内側にあるapplicationContextにアクセスする場合は、あなたがコンストラクタを使ってAndroidのアクティビティを初期化すると、すべてがうんざりしてしまいます。ただしないでください。ただ、これらの行を置き換えるthis question

0

を参照してください:

main main = new main(); 
Context context = main.getApplicationContext(); 
sharedPref = context.getSharedPreferences("alexcz", main.MODE_PRIVATE); 

で:

sharedPref = getActivity().getSharedPreferences("alexcz", getActivity().MODE_PRIVATE); 
editor = sharedPref.edit(); 

getActivity().MODE_PRIVATEinstance経由staticメンバーにアクセスするための警告が表示されます。

関連する問題