我加入了
。public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewholder>
當嘗試時
SharedPreferences mySharedPrefData = getSharedPreferences("mySharedPrefData", MODE_PRIVATE);
我得到一個錯誤:
非靜態方法'getSharedPreferences(java.lang.String, int)'不能從靜態背景關系中被參考。
我嘗試了一些替代方法
Context.getSharedPreferences("mySharedPrefData",MODE_PRIVATE)
并且
this.getSharedPreferences("mySharedPrefData",MODE_PRIVATE)
并且將mySharedPrefData宣告為static
靜態SharedPreference mySharedPrefData
但是,所有的人都拋出了錯誤。
問題:我如何從mySharedPrefData獲得資料到MyAdapter類中?
uj5u.com熱心網友回復:
為了使用sharedPreferences,你需要有活動,所以這里有很多的選擇:
如果你使用片段,那么你需要活動來獲得applicationContext。
你可以通過在你的片段物件上呼叫requireActivity()來獲得一個活動。
然后通過這行代碼獲得對你的資料的 SharedPreferences 參考。
Context context = requireActivity().getApplicationContext()。
SharedPreferences sharedPref = context.getSharedPreferences(
"mySharedPrefData", Context.MODE_PRIVATE)。)
- 然后你可以在初始化配接器時通過配接器建構式發送這個sharedPref參考。 所以你的配接器構造器代碼應該是這樣的:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewholder> {
SharedPreferences myShared ;
public MyAdapter (SharedPreferences shared){
myShared = shared ;
}
從現在開始,你可以使用myShared變數來訪問你的配接器中的共享首選項。
N.B:如果你不使用片段并直接在你的主活動中初始化你的配接器,那么你可以跳過requireActivity部分,你的共享首選項代碼將如下所示
Context context = getApplicationContext();
SharedPreferences sharedPref = context.getSharedPreferences(
"mySharedPrefData", Context.MODE_PRIVATE)。)
Update
- 由于存在一些混淆,讓我澄清一下,你應該在你的活動中使用
getApplicationContext()呼叫,假設你在活動中的onCreate方法中初始化你的配接器,那么你的MainActivity代碼可能看起來像這樣:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
...
Context context = getApplicationContext();
SharedPreferences sharedPref = context.getSharedPreferences(
"mySharedPrefData", Context.MODE_PRIVATE)。)
MyAdapter myAdapter = new myAdapter(sharedPref);
...
}
}
N.B : 三個點(...)意味著我不關心你寫在這里的代碼。
Update
- 如果你沒有編輯配接器建構式引數的權限,那么給它做一個setter怎么樣。
MyAdapter.java
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewholder> {
SharedPreferences myShared ;
public MyAdapter (SomeOtherParameter){...}。
public void setMyShared(SharedPreferences shared){
myShared = shared ;
}
}
- 然后在初始化你的配接器后,你將共享偏好設定為它
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
...
Context context = getApplicationContext();
SharedPreferences sharedPref = context.getSharedPreferences(
"mySharedPrefData", Context.MODE_PRIVATE)。)
MyAdapter myAdapter = new myAdapter(SomeOtherParameter);
myAdapter.setMyShared(sharedPref);
...
}
}
N.B : 如果你使用上面的代碼,那么在任何情況下都不要在配接器建構式中使用myShared物件以避免NullPointerException
。轉載請註明出處,本文鏈接:https://www.uj5u.com/net/310122.html
標籤:
上一篇:Linq查詢運算式中的空值檢查
