退出应用后节省的变量?变量、节省

由网友(黑色瞳孔里的一抹悲伤)分享简介:我想一些变量保存,当我关闭我的应用程序,并(在游戏中的统计数据)打开应用程序后,加载它们我怎样才能做到这一点?编辑:在这里,我的code:的TextView的test1;字符串punkte =15;@覆盖公共无效的onCreate(包savedInstanceState){super.onCreate(savedI...

我想一些变量保存,当我关闭我的应用程序,并(在游戏中的统计数据)打开应用程序后,加载它们

我怎样才能做到这一点?

编辑:在这里,我的code:

 的TextView的test1;
字符串punkte =15;

@覆盖
公共无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.main);

    共享preferences节省= getShared preferences(punkte,0);
    。save.edit()putString(分数,punkte);

    共享preferences加载= getShared preferences(punkte,0);
    串点= load.getString(得分,0);

    TEST1 =(TextView中)findViewById(R.id.test1);
    test1.setText(分);

    }
 

解决方案

您应该使用共享prefences 。它们是相当简单的使用和将存储在应用程序数据中的变量。只要用户从不点击为您的应用程序的设置清除数据,他们将永远存在。

通向Golang的捷径

下面是一个code样本。

要访问的变量:

 共享preferences米preFS = getShared preferences(标签,0);
字符串mString = M prefs.getString(标签,default_value_if_variable_not_found);
 

要编辑的变量,并提交(店)其中:

 共享preferences.Editor mEditor = M prefs.edit();
mEditor.putString(标签,value_of_variable).commit();
 

请确保两个标签字段的比赛!

I want some variables to be saved, when I shut down my app and to load them after opening the app (for statistics in a game)

How can I do this?

EDIT: Here my code:

TextView test1;
String punkte = "15";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    SharedPreferences save = getSharedPreferences(punkte, 0);
    save.edit().putString("score", punkte);

    SharedPreferences load = getSharedPreferences(punkte, 0);
    String points = load.getString("score", "0");

    test1 = (TextView) findViewById(R.id.test1);
    test1.setText(points);

    }    

解决方案

You should be using SharedPrefences. They are quite simple to use and will store the variables in the application data. As long as the user never hits "Clear Data" in the settings for your application, they will always be there.

Here is a code sample.

To access variables:

SharedPreferences mPrefs = getSharedPreferences("label", 0);
String mString = mPrefs.getString("tag", "default_value_if_variable_not_found");

To edit the variables and commit (store) them:

SharedPreferences.Editor mEditor = mPrefs.edit();
mEditor.putString("tag", value_of_variable).commit();

Make sure both "tag" fields match!

阅读全文

相关推荐

最新文章