第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

如何在片段內(nèi)的 SharedPreferences 中獲取我的 pref_name 的值?

如何在片段內(nèi)的 SharedPreferences 中獲取我的 pref_name 的值?

白衣非少年 2021-06-15 10:08:06
我一直在嘗試從 SharedPreferences 作為字符串獲取一個(gè)鍵的值,以便我可以修改連接到片段的布局中的數(shù)據(jù)。這是我的 OneFragment.java 代碼public class OneFragment extends Fragment{private TextView mText;public OneFragment() {    // Required empty public constructor}@Overridepublic void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);}@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,                         Bundle savedInstanceState) {    // Inflate the layout for this fragment    View view = inflater.inflate(R.layout.fragment_one, container, false);    SharedPreferences prefs = getActivity().getSharedPreferences("EID", Context.MODE_PRIVATE);     String value = prefs.getString("EID", "0");    mText = (TextView) view.findViewById(R.id.textView2);    mText.setText(value); return view;  }}該應(yīng)用程序說它在打開時(shí)已停止。我正在調(diào)用來自主要活動(dòng)的片段。工作室怎么說:E/AndroidRuntime: FATAL EXCEPTION: main              Process: com.example.dell.tab2, PID: 3857              java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.dell.tab2/com.example.dell.tab2.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2548)                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)                  at android.app.ActivityThread.-wrap12(ActivityThread.java)                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
查看完整描述

2 回答

?
翻閱古今

TA貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超5個(gè)贊

如果您無法在 Fragment 中獲取該值,則可以從您的 Activity 中獲取該值。調(diào)用片段:


String value = ((YourActivityName)getActivity()).getValuePreference();

并在您的活動(dòng)中添加方法:


public String getValuePreference(){

    SharedPreferences preferences = getSharedPreferences("SharedPreferences", Context.MODE_PRIVATE);

    return preferences.getString("EID", "0");

}


查看完整回答
反對(duì) 回復(fù) 2021-06-17
?
心有法竹

TA貢獻(xiàn)1866條經(jīng)驗(yàn) 獲得超5個(gè)贊

試試這個(gè):


在片段中添加以下代碼


  Context context;


@Override

public void onAttach(Context context) {

    super.onAttach(context);

    this.context = context;

}

在onCreateView替換getActivity()用context


  SharedPreferences prefs = context.getSharedPreferences("EID", Context.MODE_PRIVATE);

 String value = prefs.getString("EID", "0");


查看完整回答
反對(duì) 回復(fù) 2021-06-17
  • 2 回答
  • 0 關(guān)注
  • 219 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)