【问题标题】:How to save a int with SharedPreferences?如何使用 SharedPreferences 保存 int?
【发布时间】:2014-10-29 18:04:26
【问题描述】:

我查阅了很多关于如何保存 int 变量的教程,但找不到适合我的好例子。我的代码如下所示:

package com.example.countryclicker;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity; 
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;


public class MainActivity extends ActionBarActivity {
    int exp,level,count,totalCount;
    Button mainButton;
    TextView current,total;
    SharedPreferences pref;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mainButton = (Button) findViewById(R.id.button1);
        current = (TextView) findViewById(R.id.TcurrentCount);
        total =  (TextView) findViewById(R.id.TtotalCount);
        mainButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                count+=1;
                current.setText("Your current count is "+ count);
                totalCount = count;
                total.setText("Your total count is " + totalCount);
            }
        });
    }  


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

所以,我有一个整数计数器,每次单击按钮时都会增加,但我希望每当该用户单击该按钮时,程序将一个值保存为其他整数,并且即使用户关闭该值仍将保留应用程序。

【问题讨论】:

    标签: java xml sharedpreferences android


    【解决方案1】:

    将以下代码放入按钮的onClick() 方法中。

     SharedPreferences sharedPref = getActivity()
                                    .getPreferences(Context.MODE_PRIVATE);
                            SharedPreferences.Editor editor = sharedPref.edit();
        editor.putInt("variableName", count);
        editor.commit();
    

    【讨论】:

      【解决方案2】:

      如果我理解正确,您需要做的是:

      • 点击按钮时,先从共享首选项中获取int值,如果不存在则创建
      • 将值加一
      • 再次将此值保存到 SharedPreferences

      所以它会转化为类似的东西:

      @Override
      public void onClick(View v) {
          // TODO Auto-generated method stub
          int totalCount = mySharedPreferences.getInt("INT_KEY", -1);
          if(totalCount == -1) {
             totalCount = 0; //initialize the total count value to 0
          }
          count += 1;
          totalCount += 1;
          SharedPreferences.Editor editor = mySharedPreferences.edit();
          editor.putInt("INT_KEY", totalCount);
          editor.commit();
          current.setText("Your current count is "+ count);
          total.setText("Your total count is " + totalCount);
      }
      

      为了提高效率,请在启动应用程序时从SharedPreferences 获取totalCount 值,并在完成活动之前将其保存到SharedPreferences

      您可以阅读SharedPreferences 类的android 文档以获取更多信息。

      【讨论】:

      • 是的,这正是我需要的
      • 我在 totalCount = pref.getInt("INT_KEY", totalCount);或 SharedPreferences.Editor editor = pref.edit();
      • 它没有指定,只是运行时错误,在eclipse中是可以的
      • 好吧,这个错误是什么?它有一个堆栈跟踪,那么它说明了什么?
      • 10-30 10:10:37.823: E/AndroidRuntime(1216): java.lang.NullPointerException: 尝试调用接口方法'int android.content.SharedPreferences.getInt(java.lang.String , int)' 在空对象引用 10-30 10:10:37.823: E/AndroidRuntime(1216): at com.example.countryclicker_v2.MainActivity$1.onClick(MainActivity.java:34) 10-30 10:10: 37.823:E/AndroidRuntime(1216):在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-13
      • 1970-01-01
      • 1970-01-01
      • 2014-07-14
      • 2017-10-06
      相关资源
      最近更新 更多