Java 如何从SharedPreference获取片段活动的值?

Java 如何从SharedPreference获取片段活动的值?,java,android,android-fragments,sharedpreferences,Java,Android,Android Fragments,Sharedpreferences,SharedPrefManager.java package com.xxxx.myapplication; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; public class SharedPrefManager { private static final String SHARED_PREF_NAME = "vo

SharedPrefManager.java

package com.xxxx.myapplication;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;

public class SharedPrefManager {

    private static final String SHARED_PREF_NAME = "volleyregisterlogin";  
    private static final String KEY_USERNAME = "keyusername";  
    private static final String KEY_EMAIL = "keyemail";  
    private static final String KEY_FULLNAME = "keyfullname";
    private static final String KEY_ID = "keyid";  
    private static SharedPrefManager mInstance;  
    private static Context ctx;

    private SharedPrefManager(Context context) {  
        ctx = context;  
    }  
    public static synchronized SharedPrefManager getInstance(Context context) {  
        if (mInstance == null) {  
            mInstance = new SharedPrefManager(context);  
        }  
        return mInstance;  
    }  

    //this method will store the user data in shared preferences  
    public void userLogin(UserGetterSetter user) {
        SharedPreferences sharedPreferences = ctx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();  
        editor.putInt(KEY_ID, user.getId());  
        editor.putString(KEY_USERNAME, user.getName());  
        editor.putString(KEY_EMAIL, user.getEmail());  
        editor.putString(KEY_FULLNAME, user.getFullName());
        editor.apply();  
    }  

    //this method will checker whether user is already logged in or not  
    public boolean isLoggedIn() {  
        SharedPreferences sharedPreferences = ctx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);  
        return sharedPreferences.getString(KEY_USERNAME, null) != null;  
    }  

    //this method will give the logged in user  
    public UserGetterSetter getUser() {
        SharedPreferences sharedPreferences = ctx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);  
        return new UserGetterSetter(
                sharedPreferences.getInt(KEY_ID, -1),  
                sharedPreferences.getString(KEY_USERNAME, null),  
                sharedPreferences.getString(KEY_EMAIL, null),  
                sharedPreferences.getString(KEY_FULLNAME, null)
        );  
    }  

    //this method will logout the user  
    public void logout() {  
        SharedPreferences sharedPreferences = ctx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);  
        SharedPreferences.Editor editor = sharedPreferences.edit();  
        editor.clear();  
        editor.apply();  
        ctx.startActivity(new Intent(ctx, Login.class));
    }  

    }  
UserGetterSetter.javauserMOdel

package com.xxxx.myapplication;

public class UserGetterSetter {

        private int id;
        private String name, email, fullName;

        public UserGetterSetter(int id, String name, String email, String fullName) {
            this.id = id;
            this.email = email;
            this.fullName = fullName;
            this.name = name;
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getEmail() {
            return email;
        }

        public void setEmail(String email) {
            this.email = email;
        }


        public String getFullName() {
            return fullName;
        }

        public void setFullName(String fullName) {
            this.fullName = fullName;
        }

}
现在我想将value user id/KEY\u id检索到活动中

exchangesFragment.java

package com.eworld.myapplication;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class ExchangesFrag extends Fragment {

    RecyclerView recyclerView;
    ExchangesAdapter adapter;
    List<ExchangesSetterGetter> listItems;
    SharedPreferences sharedPreferences;
    int uid;//get value for this uid from shared prefarences

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View exchanges=inflater.inflate(R.layout.exchanges_layout,container,false);
        recyclerView=exchanges.findViewById(R.id.rview);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        listItems=new ArrayList<>();


        loadData();

        return exchanges;
    }

    public void loadData() {
        StringRequest stringRequest=new StringRequest(Request.Method.GET, URLs.url+uid, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                try {
                    JSONObject jsonObject=new JSONObject(response);
                    JSONArray jsonArray=jsonObject.getJSONArray("data");


                    for (int i=0;i<jsonArray.length();i++){

                        JSONObject receive=jsonArray.getJSONObject(i);
                        ExchangesSetterGetter exchangesSetterGetter=new ExchangesSetterGetter(
                                receive.getString("exchangeFrom"),
                                receive.getString("exchangeTo"),
                                receive.getString("status"),
                                receive.getString("imgSend"),
                                receive.getString("imgReceive"),
                                receive.getString("sendCurrency"),
                                receive.getString("receiveCurrency"),
                                receive.getString("amount_send"),
                                receive.getString("amount_receive")



                        );

                        listItems.add(exchangesSetterGetter);
                    }

                    adapter=new ExchangesAdapter(listItems,getContext());
                    recyclerView.setAdapter(adapter);
                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getContext(),"error on volley",Toast.LENGTH_LONG).show();
            }
        });

        RequestQueue queue= Volley.newRequestQueue(getContext());
        queue.add(stringRequest);

    }


}

如何从保存的SharedPreference获取int-uid的值

在你的片段上,就在你想使用SharedReference代码的时候

SharedPrefManager.getInstance(context).getUser().getId()

为了在片段中使用SharedReference,您必须使用上下文,这是您的活动。 您可以使用此行从SharedReference获取值:

SharedPreferences sharedPreferences = this.getActivity().getSharedPreferences("this", 0);
view1 = sharedPreferences.getInt("cb1", 0);

创建类AppPreference:-

public class AppPrefrences {

            private static SharedPreferences mPrefs;
            private static SharedPreferences.Editor mPrefsEditor;

    public static String getUserName(Context ctx) {
            mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
            return mPrefs.getString("userName", "");
        }

        public static void setUserName(Context ctx, String value) {
            mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
            mPrefsEditor = mPrefs.edit();
            mPrefsEditor.putString("userName", value);
            mPrefsEditor.commit();
        }

public static void clearAllPreferences(Context ctx) {
        mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
        mPrefsEditor = mPrefs.edit();
        mPrefsEditor.clear();
        mPrefsEditor.commit();
    }
        }
从项目中的任何位置设置用户名:-

AppPreference.setUserName(this, "username");
String username = AppPreference.getUserName(this);
在项目中的任何位置获取用户名:-

AppPreference.setUserName(this, "username");
String username = AppPreference.getUserName(this);
如果您在“分解”首选项中有1个以上的数据,并且希望清除首选项中的所有数据,则可以调用单个方法,数据将被清除:-

AppPreference.clearAllPreferences(this);

您需要提供活动/应用程序上下文。什么是视图1??如果有任何疑问,请留下评论