如何从SharedPrefarence到零碎活动中获取价值?

时间:2019-05-21 05:42:21

标签: 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 = "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.java(userMOdel)

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;
        }

}

现在我想将用户ID / KEY_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);

    }


}

如何从已保存的sharedprefarence中获取“ int uid”的值?

3 个答案:

答案 0 :(得分: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.clearAllPreferences(this);

答案 1 :(得分:-1)

在您的片段上,仅当您想使用sharedPreference的代码

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

答案 2 :(得分:-1)

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

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