亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

GetSharedPreferences 獲取會話 ID

GetSharedPreferences 獲取會話 ID

回首憶惘然 2023-06-04 11:26:30
我在登錄用戶 ID 和適配器 Java 訪問中有一個獲取共享首選項,但紅線顯示失敗getActivity()。適配器.java代碼public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {     View view = LayoutInflater.from(context).inflate(R.layout.siparisitemlayout,parent,false);    getSharedPreferences = new GetSharedPreferences(getActivity());    kurye_id=getSharedPreferences.getSession().getString("id",null);     return new ViewHolder(view );}獲取共享首選項代碼public GetSharedPreferences(Activity activity){    this.activity=activity;}public SharedPreferences getSession(){    sharedPreferences = activity.getApplicationContext().getSharedPreferences("",0);    return  sharedPreferences;}public void setSession(String id,String username){    sharedPreferences = activity.getApplicationContext().getSharedPreferences("",0);    SharedPreferences.Editor editor = sharedPreferences.edit();    editor.putString("id",id);    editor.putString("username",username);    editor.commit();}
查看完整描述

1 回答

?
料青山看我應如是

TA貢獻1772條經驗 獲得超8個贊

不要在那里使用getActivity()....使用context。


像這樣更改您的代碼:


 getSharedPreferences = new GetSharedPreferences(context);

首先還要檢查:GetSharedPreferences 類是否具有用于活動的參數化構造函數?


從適配器獲取 SharedPreferences 字符串值


通過構造函數在適配器中傳遞調用活動的上下文,然后使用該上下文:


  Context context;

    public ConversationsAdapter(Context context,ConversationsAdapter.ConversationOnClickHandler conversationOnClickHandler) {

       this.context=context;

       mConversationOnClickHandler = conversationOnClickHandler;

    }

現在在你的適配器中你可以這樣做:


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

String id= preferences.getString("id_key", "default_value");


查看完整回答
反對 回復 2023-06-04
  • 1 回答
  • 0 關注
  • 154 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號