简体   繁体   中英

How to get value from SharedPrefarence to a fragment activity?

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

}

now I want to retrive value user id /KEY_ID into bellows fragment activity

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

    }


}

How do I get value for "int uid" from saved sharedprefarence?

create a class 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();
    }
        }

set username from anywhere in your project :-

AppPreference.setUserName(this, "username");

get username in anywhere in your project :-

String username = AppPreference.getUserName(this);

and if you have more than 1 data in shred preference and you want to clear all the from your preference then you can call a single method and data will be cleared :-

AppPreference.clearAllPreferences(this);

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

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

In order to use sharedpreference in a fragment, you have to use context, which is you activity. you can use this line to get value from sharedpreference:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM