在优先存储值后,它不在textview中设置

时间:2015-11-05 08:12:12

标签: android json sharedpreferences textview android-alertdialog

我是android开发者。我正在创建一个应用程序,在我的应用程序中,我使用 json解析来获取状态名称,因此当用户单击texTextViewtview("选择状态")时,所有的警报对话框州名称将出现。

然后我可以选择任何州名,它将在我的TextView中设置并优先存储。

直到这里它运作良好,但问题是如果我关闭应用程序并再次打开我在TextView中设置的已经消失并再次显示"选择状态" ..

任何帮助将不胜感激..

以下是我的代码段

MainActivity.java

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        //spcountry=(TextView)rootView.findViewById(R.id.spinnercountry);
        spstate=(TextView)findViewById(R.id.feedbackspinnerstates);
        spcity=(TextView)findViewById(R.id.feedbackspinnercitys);




        new LoadAllStates().execute();


    }

    class LoadAllStates extends
            AsyncTask<String, String, ArrayList<HashMap<String, String>>> {



        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Please wait..");
            pDialog.setIndeterminate(true);
            // pDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.custom_progress));
            pDialog.setCancelable(true);
            pDialog.show();

        }

        protected ArrayList<HashMap<String, String>> doInBackground(
                String... args) {
            ServiceHandler sh = new ServiceHandler();

            // Making a request to url and getting response
            statedata = new ArrayList<HashMap<String, String>>();
            String jsonStr = sh.makeServiceCall(STATE_URL, ServiceHandler.GET);

            Log.d("Response: ", "> " + jsonStr);

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);
                    state_list = jsonObj.getJSONArray(COUNTRY_LIST);

                    // looping through All Contacts
                    for (int i = 0; i < state_list.length(); i++) {
                        JSONObject c = state_list.getJSONObject(i);

                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        map.put(STATE_SLG, c.getString(STATE_SLG));
                        map.put(STATE_ID, c.getString(STATE_ID));
                        map.put(STATE_NAME, c.getString(STATE_NAME));

                        statedata.add(map);

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            }

            return statedata;
        }

        protected void onPostExecute(ArrayList<HashMap<String, String>> result) {

            super.onPostExecute(result);
            pDialog.dismiss();

            arrallstates = new String[statedata.size()];
            for (int index = 0; index < statedata.size(); index++) {
                HashMap<String, String> map = statedata.get(index);
                arrallstates[index] = map.get(STATE_NAME);
            }

            // pass arrConuntry array to ArrayAdapter<String> constroctor :
            adapterallstates = new ArrayAdapter<String>(MainActivity.this,
                    android.R.layout.simple_spinner_dropdown_item, arrallstates);
            spstate.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View w) {


                    new AlertDialog.Builder(MainActivity.this)
                            .setTitle("Select")
                            .setAdapter(adapterallstates,
                                    new DialogInterface.OnClickListener() {



                                        @Override
                                        public void onClick(
                                                DialogInterface dialog,
                                                int which) {



                                            test=adapterallstates
                                                    .getItem(which).toString();

                                            SharedP.setStringToSharedPrefsForKey("MyKey", test, MainActivity.this);

                                            System.out.println("whts in pref"+SharedP.setStringToSharedPrefsForKey("MyKey", test, MainActivity.this));

                                            System.out.println("whts in pref get"+SharedP.getStringFromSharedPrefsForKey("MyKey", MainActivity.this));

                                            storeds=SharedP.getStringFromSharedPrefsForKey("MyKey", MainActivity.this);

                                            Log.d("Tag", SharedP.getStringFromSharedPrefsForKey("MyKey", MainActivity.this));
                                                                                        spstate.setText(storeds); 

                                             if( spstate.getText().length() != 0) 
                                                {
                                                 System.out.println("NotEMpty");
                                                }
                                                else
                                                {
                                                    System.out.println("EMpty");

                                                }

                                            try {
                                                statename = state_list
                                                        .getJSONObject(which)
                                                        .getString("state_slug");
                                                stnm = state_list
                                                        .getJSONObject(which)
                                                        .getString(STATE_NAME);

                                                Log.d("Response statenm: ",
                                                        "> " + statename);
                                            //  new LoadAllStatesCity()
                                                        //.execute();

                                                // Toast.makeText(getActivity(),
                                                // statename,
                                                // Toast.LENGTH_LONG).show();
                                            } catch (JSONException e) {
                                                // TODO Auto-generated catch
                                                // block
                                                e.printStackTrace();
                                            }

                                            dialog.dismiss();
                                        }
                                    }).create().show();
                }
            });

        }
    }

1 个答案:

答案 0 :(得分:1)

请查看以下代码:

设置值

 SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
 editor.putString("yourtextvalueKey", "yourvalue");
 editor.commit();

获取价值

SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); 
String text= prefs.getString("yourtextvalueKey", null);

if(text != null){
textview.setText(text);
}

注意

MY_PREFS_NAME:这是首选键。例如"myprefs"在设置和获取偏好值时都会相同。

尝试在全局范围内声明您的偏好,并使用onCreate()方法初始化它。

希望它会对你有所帮助。