在preference存储值之后它不是在TextView中设置 [英] After storing value in preference it is not setting in textview

查看:291
本文介绍了在preference存储值之后它不是在TextView中设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Android开发者。我创建一个应用程序,在我的应用我使用的 JSON解析,以获得国家的名字,所以当texTextViewtview用户点击(选择国家),与所有国家的名字警告对话框将会出现。

然后我可以选择任何国家的名字,它将在我的TextView集,并存入preference。

到这里效果很好,但问题是,如果我关闭应用程序,然后再次打开我在TextView中设置的消失了,再次显示选择国家。

任何帮助将是AP preciated ..

以下是我的代码片段code

MainActivity.java

  @覆盖
    保护无效的onCreate(捆绑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);
        新LoadAllStates()执行();
    }    类LoadAllStates扩展
            AsyncTask的<字符串,字符串的ArrayList<&HashMap的LT;字符串,字符串>>> {        @覆盖
        在preExecute保护无效(){
            super.on preExecute();
            pDialog =新ProgressDialog(MainActivity.this);
            pDialog.setMessage(请稍候...);
            pDialog.setIndeterminate(真);
            // pDialog.setIndeterminateDrawable(getResources()getDrawable(R.drawable.custom_progress));
            pDialog.setCancelable(真);
            pDialog.show();        }        保护的ArrayList<&HashMap的LT;字符串,字符串>> doInBackground(
                字符串参数... args){
            SH的ServiceHandler =新的ServiceHandler();            //制作到URL的请求和响应得到
            statedata =新的ArrayList<&HashMap的LT;字符串,字符串>>();
            字符串jsonStr = sh.makeServiceCall(STATE_URL,ServiceHandler.GET);            Log.d(回应:,>中+ jsonStr);            如果(jsonStr!= NULL){
                尝试{
                    JSONObject的jsonObj =新的JSONObject(jsonStr);
                    state_list = jsonObj.getJSONArray(COUNTRY_LIST);                    //通过所有联系人循环
                    的for(int i = 0; I< state_list.length();我++){
                        JSONObject的C = state_list.getJSONObject(I)                        //创建新的HashMap
                        HashMap的<字符串,字符串>地图=新的HashMap<字符串,字符串>();                        //将每个子节点的HashMap键=>值
                        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(地图);                    }
                }赶上(JSONException E){
                    e.printStackTrace();
                }
            }其他{
                Log.e(的ServiceHandler,无法从URL得到任何数据);
            }            返回statedata;
        }        保护无效onPostExecute(ArrayList的<&HashMap的LT;字符串,字符串>>的结果){            super.onPostExecute(结果);
            pDialog.dismiss();            arrallstates =新的String [statedata.size()];
            对于(INT指数= 0;指数 - LT; statedata.size();指数++){
                HashMap的<字符串,字符串>地图= statedata.get(指数);
                arrallstates [指数] = map.get(STATE_NAME);
            }            //传递arrConuntry数组ArrayAdapter<串GT; constroctor:
            adapterallstates =新ArrayAdapter<串GT;(MainActivity.this,
                    android.R.layout.simple_spinner_dropdown_item,arrallstates);
            spstate.setOnClickListener(新OnClickListener(){                @覆盖
                公共无效的onClick(查看W){
                    新AlertDialog.Builder(MainActivity.this)
                            .setTitle(选择)
                            .setAdapter(adapterallstates,
                                    新DialogInterface.OnClickListener(){                                        @覆盖
                                        公共无效的onClick(
                                                DialogInterface对话框,
                                                其中INT){                                            测试= adapterallstates
                                                    .getItem(其)的ToString();                                            SharedP.setStringToShared prefsForKey(的myKey,测试MainActivity.this);                                            的System.out.println(在preF whts+ SharedP.setStringToShared prefsForKey(的myKey,测试MainActivity.this));                                            的System.out.println(在preF GET whts+ SharedP.getStringFromShared prefsForKey(的myKey,MainActivity.this));                                            storeds = SharedP.getStringFromShared prefsForKey(的myKey,MainActivity.this);                                            Log.d(变量,SharedP.getStringFromShared prefsForKey(的myKey,MainActivity.this));
                                                                                        spstate.setText(storeds);                                             如果(spstate.getText()。长度()!= 0)
                                                {
                                                 的System.out.println(NotEMpty);
                                                }
                                                其他
                                                {
                                                    的System.out.println(空);                                                }                                            尝试{
                                                Statename的= state_list
                                                        .getJSONObject(所)
                                                        .getString(state_slug);
                                                stnm = state_list
                                                        .getJSONObject(所)
                                                        .getString(STATE_NAME);                                                Log.d(回应statenm:
                                                        >中+ Statename的);
                                            //新LoadAllStatesCity()
                                                        //。执行();                                                // Toast.makeText(getActivity(),
                                                // Statename的,
                                                // Toast.LENGTH_LONG).show();
                                            }赶上(JSONException E){
                                                // TODO自动生成捕
                                                //块
                                                e.printStackTrace();
                                            }                                            dialog.dismiss();
                                        }
                                    })创建()显示()。
                }
            });        }
    }


解决方案

请看看下面code:

设定值:

 共享preferences.Editor编辑= getShared preferences(MY_ preFS_NAME,MODE_PRIVATE).edit();
 editor.putString(yourtextvalueKey,yourvalue);
 editor.commit();

获取值:

 共享preferences preFS = getShared preferences(MY_ preFS_NAME,MODE_PRIVATE);
字符串文本= prefs.getString(yourtextvalueKey,NULL);如果(文字!= NULL){
textview.setText(文本);
}

注意

MY_ preFS_NAME :这是preference键。例如我的preFS两者同时设定和preferences获得价值将是一样的。

和试图在全球范围内宣布你的preference和的onCreate初始化()方法。

希望它会帮助你。

I am android developer. I am creating one app, in my app I am using json parsing to get state name, so when user click on texTextViewtview("Select State"), the alert dialog with all the state name will appear.

Then I can select any state name, and it will set in my TextView and also storing in preference.

Till here it works well, but the issue is if I close the app and again open the which I have set in my TextView is gone and again it shows "Select State"..

Any help would be appreciated..

Following is my snippet code

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

        }
    }

解决方案

Please look at the below code :

Setting Value :

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

Getting value :

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

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

Note :

MY_PREFS_NAME : It's preference key. e.g "myprefs" both will be same while setting and getting value by preferences.

And try to declare your your preference globally and initialize it in onCreate() method.

Hope it will help you.

这篇关于在preference存储值之后它不是在TextView中设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆