如何从Listview接收值并将其保存到共享首选项中

时间:2013-05-16 04:12:44

标签: java android sharedpreferences

当我从一个类(ListView)获取的一个共享偏好中接收到值时,我正在使用共享偏好将值发送到数据中,一切正常,但当我想从两个共享偏好中接收来自不同的共享偏好时我遇到问题class,详情,这是我的代码

    来自login.java的
  1. sharedpreferences:

            SharedPreferences values = PreferenceManager.getDefaultSharedPreferences(LoginActivity.this);
        SharedPreferences.Editor editor = values.edit();
        editor.putString("etUser", strUser);
        editor.putString("key",KEY);
        editor.commit();
    
  2. 在EpolicyListPolis.java中的

    ,我从登录类接收值并发送新值:

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

    ,当我想从登录类和EpolicyListPolis接收值时,我遇到了问题,因为我收到的值都没有,这就是我收到它的方式:

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

    是我从两个sharedPreferences接收值的方法是错误的吗?如果是的话,我希望有人可以告诉我,我的错是什么。

    更新这里我将我的代码封装在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();
            }
    
            }
        }
    

    这是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());
                }
    

    我仍然不明白,为什么当我想运行PPViewerEpolicy时,没有从url加载的数据,我在结构代码或其他任何方面都错了..?

5 个答案:

答案 0 :(得分:2)

当你在getstring中获得值pass“。

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

instaed of this。

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

并尝试使用我的代码来实现sharepreferences。

保存偏好。

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

获取价值。

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

use.best运气。

答案 1 :(得分:1)

尝试这种方式。

1.haredprefences 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。在EpolicyListPolis.java中

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

然后在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);

请注意:您只能使用一个SharedPreferences来存储和检索应用程序中的值。 PREFS_NAME这是您的共享首选项名称。在此首选项中,您在整个应用程序中的任何类中所做的任何更改都会在整个应用程序中发生。

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

我希望这会对你有所帮助。

答案 2 :(得分:1)

我检查了你的代码及其工作人员。

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

答案 3 :(得分:0)

确定尝试使用,如果您遇到任何问题,请告诉我。

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


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

答案 4 :(得分:0)

使用getApplicationContext

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