共享preference不保存值(解决) [英] Shared Preference not saving value(Solved)

查看:139
本文介绍了共享preference不保存值(解决)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚学建立在Android的一些应用。出于好奇,我使用共享preferences有一个小而奇怪的问题。如果有人能帮助我解决这个问题,我将非常感激他们。不管怎么说,在这里不用的问题。我有2个活动。 1.活动1:只包含一个按钮,将让你的下一个活动。 2.活动2:由包括复选框(simple_list_item_checked或simple_list_multi_choice_item)一个列表视图的

我的问题是:我打开我的应用程序,击中了我的第一个活动的屏幕上的按钮,这让我感动到第二个活动。我的列表视图检查的项目。我打后退按钮在我的手机,去的第一个活动,再preSS按钮上我的活动1的屏幕,这需要我到列表中了。现在,我刚刚离开我的列表项检查(我不会改变任何东西,已经被选中previously)。现在,我再次打回按钮,在我的手机,回到活动之一。现在,当我再次preSS按钮上我的活动一个屏幕。它把我带回到列表视图,但令人惊讶的没有被选中。这里要说明一点,我也设置和检索我的共享preference。

我的问题在一个单一的线是:如果我不改变的值在清单,而我在那活动,然后回到主要活动,并返回到相同的检查清单的活动,我共享preference不会加载什么被先前保存。这是共享preference正常行为或者是在编码的问题。

我只是想知道如何preference值保存和检索和多长时间一个preference保存价值?我的意思是preference保存价值的生命周期。

第二个问题:还有,我想知道活动的生命周期一件事。当我在第二活动在上面的例子中所解释的。现在我preSS home键了,现在我去后台任务,并明确所有任务(应用程序)运行。现在,我的问题是活动的生命周期哪个状态之后还是什么将是最后的活动周期之前,我清除后台我所有的应用程序?请人帮我出这一点。感谢所有创造性的开发出有提前。希望有人能解决我的问题。

 公共类Secondact扩展ListActivity {
    ListView控件列表;
    共享preferences preF;
     INT POS,itemposition,positionvalue;
     布尔boolval,校验值;
     共享preferences.Editor编辑;
     @覆盖
        保护无效的onCreate(包savedInstanceState){
            super.onCreate(savedInstanceState);
          //的setContentView(R.layout.secondact);
            Toast.makeText(getApplicationContext(),的onCreate,50).show();

            表= getListView();

           的String [] family_array = this.getResources()getStringArray(R.array.family)。
           ArrayAdapter<字符串>适配器=新的ArrayAdapter<字符串>(这一点,android.R.layout.simple_list_item_multiple_choice,family_array);
           list.setAdapter(适配器);
           list.setChoiceMode(1);
           preF = preferenceManager.getDefaultShared preferences(getApplicationContext());
         POS = pref.getInt(itempos,POS);
             boolval = pref.getBoolean(boolvalue,真正的);
            list.setItemChecked(POS,boolval);
            Toast.makeText(getApplicationContext(),加载的数据产品编号:+ POS,50).show();

           list.setOnItemClickListener(新OnItemClickListener(){

            @覆盖
            公共无效onItemClick(适配器视图<>母公司视图中查看,
                    INT位置,长的id){
                // TODO自动生成方法存根


                POS =位置;
                list.setItemChecked(POS,真正的);
                preF = preferenceManager.getDefaultShared preferences(getApplicationContext());
                编辑= pref.edit();
                editor.putInt(itempos,POS);
                editor.putBoolean(boolvalue,list.isItemChecked(POS));
                editor.commit();
            }
        });

}

    @覆盖
    保护无效的onPause(){
        // TODO自动生成方法存根
        super.onPause();
        preF = preferenceManager.getDefaultShared preferences(getApplicationContext());
     编辑= pref.edit();
        editor.putInt(itempos,POS);
        editor.putBoolean(boolvalue,list.isItemChecked(POS));
        editor.commit();
    // Toast.makeText(getApplicationContext(),暂停,50).show();

    }

    @覆盖
    保护无效onResume(){
        // TODO自动生成方法存根
        super.onResume();
        preF = preferenceManager.getDefaultShared preferences(getApplicationContext());
         POS = pref.getInt(itempos,POS);
         boolval = pref.getBoolean(boolvalue,真正的);
        list.setItemChecked(POS,boolval);
        //Toast.makeText(getApplicationContext(),RESUME,50).show();

    }

    @覆盖
    保护无效的onDestroy(){
        // TODO自动生成方法存根
        super.onDestroy();
        preF = preferenceManager.getDefaultShared preferences(getApplicationContext());
         编辑= pref.edit();
        editor.putInt(itempos,POS);
        editor.putBoolean(boolvalue,list.isItemChecked(POS));
        editor.commit();
        Toast.makeText(getApplicationContext(),消灭,50).show();
        Toast.makeText(getApplicationContext(),数据保存的条目NO:+ POS,50).show();

    }

    @覆盖
    保护无效onRestart(){
        // TODO自动生成方法存根
        super.onRestart();
        preF = preferenceManager.getDefaultShared preferences(getApplicationContext());
     POS = pref.getInt(itempos,POS);
         boolval = pref.getBoolean(boolvalue,真正的);
        list.setItemChecked(POS,boolval);
        //Toast.makeText(getApplicationContext(),重新启动,50).show();

    }

    @覆盖
    保护无效的onSaveInstanceState(包savedInstanceState){
        // TODO自动生成方法存根

        savedInstanceState.putInt(itempositionno,positionvalue);
        savedInstanceState.putBoolean(校验值,真正的);
        Toast.makeText(getApplicationContext(),ONSAVEINSTANCE,50).show();
        list.setItemChecked(POS,校验值);
        super.onSaveInstanceState(savedInstanceState);
    }

    @覆盖
    保护无效onRestoreInstanceState(包savedInstanceState){
        // TODO自动生成方法存根

        POS = savedInstanceState.getInt(itempositionno,POS);
         校验值= savedInstanceState.getBoolean(校验值,真正的);
        list.setItemChecked(POS,校验值);
        Toast.makeText(getApplicationContext(),ONRESTOREINSTANCE,50).show();
        super.onRestoreInstanceState(savedInstanceState);
    }
}
 

解决方案:

好了,对于那些谁从共享preference不保持活动交换机上的价值同样的问题的痛苦。这片逻辑的伎俩,

设置在这样sp.getInt列表视图你行的默认值(为CheckedValue,传为默认的viz.Listitem.getCheckedItemPosition的提早检查行的位置());

这将节省整个应用程序的生命周期和/或活动的生命周期的检查值。

注意确保清除您的共享preference前提交(),以避免您的应用程序的繁忙的内存使用情况。

最后,非常感谢谁回答这个问题,所有的开发人员立即。

解决方案
  

我只是想知道如何preference值保存和   检索和多长时间一个preference保存价值?我的意思是   生命周期中的preference保存的价值。

一个单行回复您的单行的问题 -

  • 它被保存在整个应用程序,除非你自己清楚它的生命周期。

为了获得共享preferences:

 共享preferences preFS = this.getShared preferences(
      com.example.app,Context.MODE_PRIVATE);
 

阅读preferences:

 字符串dateTimeKey =com.example.app.datetime;

//使用采用新日期的默认值()
长L = prefs.getLong(da​​teTimeKey,新的日期()的getTime());
 

编辑和保存preferences

为编辑(清除)的 -

 共享preferences.Editor编辑器= prefs.edit();
    editor.clear();
    editor.commit();
 

为了节省的 -

 日期DT = getSomeDate();
。prefs.edit()putLong(da​​teTimeKey,dt.getTime())提交();
 

读 - <一个href="http://stackoverflow.com/questions/3624280/how-to-use-shared$p$pferences-in-android-to-store-fetch-and-edit-values">how-to-use-shared$p$pferences-in-android-to-store-fetch-and-edit-values.

  

其中的活性生命周期状态之后或会是怎样的   最后一个活动的生命周期之前,我清除了我所有的应用程序   背景是什么?

取决于您的要求。无需遵循最后一个活动的生命周期来做到这一点。例如 - 当用户从应用程序注销,涉及到用户preferences都是没有用的,只是后注销按钮preSS可以清除独立的生命周期。

I am just learning to build some applications in Android. Out of curiosity, I have a small and weird problem using Shared Preferences. If someone can help me addressing this issue , I would be most thankful to them. Anyways,here goes the problem. I have 2 Activities. 1. Activity 1 : Consists of just one button that will get you to the next activity. 2. Activity 2 : Consists of a listview with checkbox (simple_list_item_checked or simple_list_multi_choice_item).

My question is: I open my application, hit the button on my first activity screen, this moves me to the second activity. I check an item in the listview. I hit the back button on my phone, go to the first activity, again press the button on my activity 1 screen, this takes me to the list again. Now I just leave my list item checked(I don't change anything that is already checked previously). Now again, I hit back button on my phone, get back to activity one. Now again when I press the button on my activity one screen. It takes me back to the listview but SURPRISINGLY nothing is checked. To note a point here, I had also set and retrieved my shared preference.

MY QUESTION IN A SINGLE LINE IS : If I don't change a value in the check list while I'm in that Activity and then go back to the Main Activity, and get back to the same check list activity, my shared preference does not load what has been saved earlier. Is this the normal behavior of Shared Preference or is it a problem in the coding.

I would just like to know how preference values are saved and retrieved and how long does a preference save a value ? I mean the lifecycle of the saved value in preference.

MY SECOND QUESTION : Also, I would like to know one more thing in activity life cycle. When I am in the second activity as explained in the above example. Now I press the home button , now I go to the background tasks and clear all the tasks(Apps) that are running . Now, my question is which state of activity life cycle is followed or what will be the final activity lifecycle before i clear all my apps from the background ? Please someone help me out on this. Thanks to all those creative developers out there in advance. Hope someone can solve my issue.

public class Secondact extends ListActivity {
    ListView list;
    SharedPreferences pref;
     int pos,itemposition,positionvalue;
     boolean boolval,checkvalue;
     SharedPreferences.Editor editor;
     @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
          // setContentView(R.layout.secondact);
            Toast.makeText(getApplicationContext(), "ONCREATE", 50).show();

            list=getListView();

           String[] family_array=this.getResources().getStringArray(R.array.family);
           ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice,family_array);
           list.setAdapter(adapter);
           list.setChoiceMode(1);
           pref=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
         pos=pref.getInt("itempos", pos);
             boolval=pref.getBoolean("boolvalue", true);
            list.setItemChecked(pos, boolval);
            Toast.makeText(getApplicationContext(), "DATA LOADED ITEM NO:"+pos, 50).show();

           list.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // TODO Auto-generated method stub


                pos=position;
                list.setItemChecked(pos, true);
                pref=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                editor=pref.edit();
                editor.putInt("itempos", pos);
                editor.putBoolean("boolvalue", list.isItemChecked(pos));
                editor.commit();
            }
        });

}

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        pref=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
     editor=pref.edit();
        editor.putInt("itempos", pos);
        editor.putBoolean("boolvalue", list.isItemChecked(pos));
        editor.commit();
    //  Toast.makeText(getApplicationContext(), "PAUSE", 50).show();

    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        pref=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
         pos=pref.getInt("itempos", pos);
         boolval=pref.getBoolean("boolvalue", true);
        list.setItemChecked(pos, boolval);
        //Toast.makeText(getApplicationContext(), "RESUME", 50).show();

    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        pref=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
         editor=pref.edit();
        editor.putInt("itempos", pos);
        editor.putBoolean("boolvalue", list.isItemChecked(pos));
        editor.commit();
        Toast.makeText(getApplicationContext(), "DESTROY", 50).show();
        Toast.makeText(getApplicationContext(), "DATA SAVED ITEM NO:"+pos, 50).show();

    }

    @Override
    protected void onRestart() {
        // TODO Auto-generated method stub
        super.onRestart();
        pref=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
     pos=pref.getInt("itempos", pos);
         boolval=pref.getBoolean("boolvalue", true);
        list.setItemChecked(pos, boolval);
        //Toast.makeText(getApplicationContext(), "RESTART", 50).show();

    }

    @Override
    protected void onSaveInstanceState(Bundle savedInstanceState) {
        // TODO Auto-generated method stub

        savedInstanceState.putInt("itempositionno", positionvalue);
        savedInstanceState.putBoolean("checkvalue", true);
        Toast.makeText(getApplicationContext(), "ONSAVEINSTANCE", 50).show();
        list.setItemChecked(pos, checkvalue);
        super.onSaveInstanceState(savedInstanceState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        // TODO Auto-generated method stub

        pos=savedInstanceState.getInt("itempositionno", pos);
         checkvalue=savedInstanceState.getBoolean("checkvalue", true);
        list.setItemChecked(pos, checkvalue);
        Toast.makeText(getApplicationContext(), "ONRESTOREINSTANCE", 50).show();
        super.onRestoreInstanceState(savedInstanceState);
    }
}

SOLUTION

Alright, for those who are suffering from the same problem of the shared preference not maintaining the value on activity switch. This piece of logic does the trick,

Set your default value of your row in the listview like this sp.getInt("CheckedValue",pass the position of the ealier checked row as the default one viz.Listitem.getCheckedItemPosition());

This will save the checked value throughout your application's life cycle and/or activity life cycle.

NOTE Make sure to clear your sharedpreference before commit() so as to avoid the hectic memory usage of your app.

Finally, A big Thanks to all those developers who responded to this question immediately.

解决方案

I would just like to know how preference values are saved and retrieved and how long does a preference save a value ? I mean the lifecycle of the saved value in preference.

A single line reply to your single line question -

  • It is saved throughout the life-cycle of the application unless you yourself clear it.

To obtain shared preferences:

SharedPreferences prefs = this.getSharedPreferences(
      "com.example.app", Context.MODE_PRIVATE);

To read preferences:

String dateTimeKey = "com.example.app.datetime";

// use a default value using new Date()
long l = prefs.getLong(dateTimeKey, new Date().getTime()); 

To edit and save preferences

In order to edit(clear) -

SharedPreferences.Editor editor = prefs.edit();
    editor.clear();
    editor.commit();

In order to save -

Date dt = getSomeDate();
prefs.edit().putLong(dateTimeKey, dt.getTime()).commit();

Read - how-to-use-sharedpreferences-in-android-to-store-fetch-and-edit-values.

Which state of activity life cycle is followed or what will be the final activity life-cycle before I clear all my apps from the background ?

Depends on your requirement. No need to follow final activity life-cycle to do this. For example - When the user logs out from the application, preferences related to the user are of no use and can be cleared independent of the life-cycle just after the log out button press.

这篇关于共享preference不保存值(解决)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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