【问题标题】:How to receive value from Listview and save it into sharedpreferences如何从 Listview 接收值并将其保存到 sharedpreferences
【发布时间】:2013-05-16 04:12:43
【问题描述】:

我使用 sharedpreferences 将值发送到数据中,一切正常,当我从一个类 (ListView) 中获取的一个 sharedpreferences 中接收值时,但是当我想从两个不同的 sharedpreferences 中接收值时我遇到了问题类,详细来说,这是我的代码

  1. 来自 login.java 的共享首选项:

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

在 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 加载的数据,是我的结构代码或其他什么错误..?

【问题讨论】:

  • 使用 getApplicationContext() 代替 this 或 getBaseContext()
  • @ρяσѕρєя K 还是不行
  • @ρяσѕρєя K 请看看我的更新...

标签: java android sharedpreferences


【解决方案1】:

当你在getstring中获得值时传递“”。

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

代替这个。

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

并尝试使用我的代码来实现共享首选项。

用于保存偏好。

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

祝你好运。

【讨论】:

    【解决方案2】:

    试试这个方法。

    1.来自 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.
    

    希望对你有帮助。

    【讨论】:

    • 通过您的代码POLIS 将仅在单击lv 项后保存。检查一下。
    • 是的..没错...那么如何解决呢?因为来自 POLIS 的值,点击后保存
    • 谢谢你的回答和你的线索说“因为来自 POLIS 的价值,点击后保存”让我意识到并知道我的错在哪里..我忘记输入这个代码:String POLIS = ( (TextView)view.findViewById(R.id.polis)).getText().toString();再一次..谢谢你:)
    【解决方案3】:

    我已经检查了您的代码及其工作伙伴。

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

    【讨论】:

      【解决方案4】:

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

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

      【讨论】:

        【解决方案5】:

        使用 getApplicationContext

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-10-15
          • 1970-01-01
          • 1970-01-01
          • 2013-06-08
          • 1970-01-01
          • 1970-01-01
          • 2019-10-04
          • 1970-01-01
          相关资源
          最近更新 更多