简体   繁体   中英

How to receive value from Listview and save it into sharedpreferences

I was using sharedpreferences for send value into data, everything okay, when I receive values from one sharedpreferences that taken from one class(ListView), but I face the problem when I want to receive values from two sharedpreferences that taken from different class, for detail, this is my code

  1. sharedpreferences from login.java:

      SharedPreferences values = PreferenceManager.getDefaultSharedPreferences(LoginActivity.this); SharedPreferences.Editor editor = values.edit(); editor.putString("etUser", strUser); editor.putString("key",KEY); editor.commit(); 

in EpolicyListPolis.java, I receive values from login class and send new values :

SharedPreferences text = PreferenceManager.getDefaultSharedPreferences(EpolicyListPolis.this);
        SharedPreferences.Editor editor = text.edit();
        editor.putString("POLIS", POLIS);
        editor.commit();

in PPViewerEpolicy.java, when I want to receive values from login class and EpolicyListPolis, I have a problem, because values that I receive is nothing, this is how I receive it:

SharedPreferences values = PreferenceManager.getDefaultSharedPreferences(this);
    strUser = values.getString("etUser", "null");
    KEY = values.getString("key", "null");

    SharedPreferences text = PreferenceManager.getDefaultSharedPreferences(this);
    POLIS= text.getString("POLIS", "null"); 

is my method to receive value from two sharedPreferences is wrong..? if yes, I hope somebody can tell me where is my fault.

UPDATE here I enclosure my code in EpolicyListPolis.java

public class EpolicyListPolis extends ListActivity {
    static String PEMEGANG="PEMEGANG";
    static String POLIS="POLIS";
    static String STATUS="STATUS";
    static String TERTANGGUNG="TERTANGGUNG";
    String KEY, strUser;
    List NasabahList= new ArrayList();
    private ProgressDialog Dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle(R.string.Nomor_Polis);

        setContentView(R.layout.epolicy_list_polis);


        SharedPreferences settings = getSharedPreferences("PREFS_NAME", 0);
        strUser= settings.getString("etUser", null);
        KEY = settings.getString("key", null);

        new NasabahAsyncTask().execute();
    }
public class NasabahAsyncTask extends AsyncTask<Void, Void, String>{
    String url = ("http://www.example.com"+strUser+"&k="+KEY);
    public NasabahAsyncTask() {
        this.url=url;
        // TODO Auto-generated constructor stub
    }

    protected void onPreExecute() {
        super.onPreExecute();   
        Dialog = ProgressDialog.show(EpolicyListPolis.this, "", "Loading");
    }

@Override
protected String doInBackground(Void... params) {
    String result="";
    try {
        result=Connection.get(url);
    }catch (Exception e){
        result=" ";
        Log.d("test viewer",e.getMessage());
    }
    return result;
}

@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);
    fetchResponse(result.replace("\n", "").trim());

    ListAdapter adapter = new SimpleAdapter(
            EpolicyListPolis.this, NasabahList, R.layout.epolicy_polis_listitem,
            new String[] {POLIS, PEMEGANG, TERTANGGUNG, STATUS}, new int [] {R.id.polis, R.id.pemegang, R.id.tertanggung, R.id.status});

        setListAdapter(adapter);
    Dialog.dismiss();
    ListView lv = getListView();

    lv.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            SharedPreferences settings = getSharedPreferences("PREFS_NAME", 0);
            SharedPreferences.Editor editor = settings.edit();
            editor.putString("POLIS", POLIS);
            editor.commit();


            Intent in = new Intent(EpolicyListPolis.this, KategoriNomorPolis.class);

            startActivity(in);
        }
    });}
}
private void fetchResponse(String result) {
    // TODO Auto-generated method stub
    if (!result.equals("")) {
        try {
            JSONArray jsonArray = new JSONArray(result);
            for (int i = 0; i < jsonArray.length(); i++) {

                JSONObject jsonObject = jsonArray.getJSONObject(i);
                HashMap<String, String> map = new HashMap<String, String>();
                if (jsonObject.has("PEMEGANG")) 
                    map.put("PEMEGANG", jsonObject.get("PEMEGANG").toString());
                if (jsonObject.has("POLIS")) 
                    map.put("POLIS", jsonObject.get("POLIS").toString());
                if (jsonObject.has("STATUS")) 
                    map.put("STATUS", jsonObject.get("STATUS").toString());
                if (jsonObject.has("TERTANGGUNG")) 
                    map.put("TERTANGGUNG", jsonObject.get("TERTANGGUNG").toString());
                NasabahList.add(map);
                System.out.println("json oke");
}
        }catch (JSONException e) {

            e.printStackTrace();
        }

        }
    }

This is PPViewerEpolicy.java:

 public class PPViewerEpolicy extends ListActivity {
    String strUser,KEY,POLIS;
    static final String[] PP= new String[] {
        "Nama Lengkap",
        "gelar",
        "Warga Negara",
        "Usia",
        "Status",
        "Jenis Kelamin",
        "Agama"};

private ProgressDialog dialog;
private ArrayList<PPVariabel> listPP;
    ListView list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        SharedPreferences settings = getSharedPreferences("PREFS_NAME", 0);
        strUser = settings.getString("etUser", null);
        KEY= settings.getString("key", null);
        POLIS= settings.getString("POLIS", null);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.pplist);
        listPP= new ArrayList<PPVariabel>();
        new PemegangPolis().execute();
    }

    public class PemegangPolis extends AsyncTask<Void, Void, String>{

        String url="http://www.example.com"+strUser+"&k="+KEY+"&p"+POLIS;

        public PemegangPolis (){
            this.url=url;
        }

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();

            dialog = ProgressDialog.show(PPViewerEpolicy.this, "", "Please wait");
        }


        @Override
        protected String doInBackground(Void... params) {
            // TODO Auto-generated method stub
                        String result = "";
                        try {
                            result = Connection.get(url);
                        } catch (Exception e) {
                            // TODO: handle exception
                            result = "";

                        }

                        return result;
                    }

                    @Override
                    protected void onPostExecute(String result) {
                        // TODO Auto-generated method stub
                        super.onPostExecute(result);

                        fetchResponse(result.replace("\n", "").trim());
                        dialog.dismiss();
                    }
                }

    private void fetchResponse(String result) {
        // TODO Auto-generated method stub
        if (!result.equals("")) {
            try {
                JSONObject jsonObject = new JSONObject(result);
                PPVariabel varpp = null;
                JSONObject pp = jsonObject.getJSONObject("pp");
                for (int i=0; i<pp.length();i++){
                varpp= new PPVariabel(pp.optString("nama_pmg"),
                        pp.optString("pendidikan_pmg"),
                        pp.optString("warga_pmg"),
                        pp.optString("usia_pmg"),
                        pp.optString("status_marital_pmg"),
                        pp.optString("kelamin_pmg"),
                        pp.optString("agama_pmg"),
                        pp.optString("tujuan_pmg"),
                        pp.optString("tujuana_pmg"),
                        pp.optString("penghasilan_pmg"),
                        pp.optString("pendanaan_pmg"),
                        pp.optString("pendanaana_pmg"),
                        pp.optString("bidang_industria_pmg"),
                        pp.optString("hubungan_pmg_ttg"));

                        listPP.add(varpp);
                        System.out.println("json parser done cynnn");

                        list=(ListView)findViewById(android.R.id.list);

                        setListAdapter(new PPViewerAdapter(this, listPP,PP));
                }
            }

            catch (Exception e) {
                Log.d("TEST CHART", e.getMessage());
            }

I still don't understand, why when I want to run PPViewerEpolicy, there's no data that loaded from url, am I wrong in structure code or anything else..?

when u get the value pass "" in getstring.

strValue = values.getString(key,"");

instaed of this.

 KEY = values.getString("key", "null");

and try to my code.to implement sharepreferences.

For save prefernces.

SharedPreferences preferences = myContext.getSharedPreferences("name_Pref", myContext.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString(key, value);
        editor.commit();

for get the value.

String strValue = "";
        @SuppressWarnings("static-access")
        SharedPreferences preferences = myContext.getSharedPreferences("name_Pref", myContext.MODE_PRIVATE);
        strValue = preferences.getString(key,"");

use.best luck.

try this way.

1.sharedprefences from login.java :

SharedPreferences settings = getSharedPreferences("PREFS_NAME", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("etUser", strUser);
editor.putString("key",KEY);
editor.commit();

2 . in EpolicyListPolis.java

SharedPreferences settings = getSharedPreferences("PREFS_NAME", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("POLIS", POLIS);
editor.commit();

then in PPViewerEpolicy.java

SharedPreferences settings = getSharedPreferences("PREFS_NAME", 0);
String etUser1 = settings.getString("etUser", null);
String key1 = settings.getString("key", null);
String polis1 = settings.getString("POLIS", null);

Note that: You can use only one SharedPreferences to store and retrive values throuhout the application. PREFS_NAME this is your shared preference name. In this preference whatever changes you made in any class from your whole application it will occur throughout the application.

getString("etUser", null); //this will return null if etUser not exist in your shared preference.

I hope this will help you.

I have checked your code and its working dude.

     TesingMultiple acativity 

    SharedPreferences values = PreferenceManager
            .getDefaultSharedPreferences(TesingMultiple.this);
    SharedPreferences.Editor editor = values.edit();
    editor.putString("etUser", "arj");
    editor.putString("key", "arjk");
    editor.commit();

    SharedPreferences text = PreferenceManager
            .getDefaultSharedPreferences(TesingMultiple.this);
    SharedPreferences.Editor editor1 = text.edit();
    editor1.putString("POLIS", "polis");
    editor1.commit();

    Intent i = new Intent(ctx, Test123.class);
    startActivity(i);

    Test123 actvity // for displaying shared preference

    SharedPreferences values = PreferenceManager
            .getDefaultSharedPreferences(this);
    String strUser = values.getString("etUser", "null");
    String KEY = values.getString("key", "null");

    SharedPreferences text = PreferenceManager
            .getDefaultSharedPreferences(this);
    String POLIS = text.getString("POLIS", "null");

    System.out.println("strUser" + strUser + "KEY" + KEY + "  " + "POLIS"
            + POLIS);

Ok Try to use then let me know if you are getting any problem.

strUser = values.getString("etUser", null);
    KEY = values.getString("key", null);


    POLIS= text.getString("POLIS", null);

使用getApplicationContext

SharedPreferences values = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

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