Android 共享首选项 [英] Android SharedPreference

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

问题描述

我正在制作一个记分卡,显示游戏中 4 名玩家的得分,当用户按下按钮时,将插入一个新行.我这样做:

Hi I am working on a scorecard showing 4 players' score in a game, and when the user press a button, a new row would be inserted. I do this by:

   private void makeTag(String P1Score, String P2Score, String P3Score, String P4Score, String slot)
   {
      // originalQuery will be null if we're modifying an existing search
      String originalScore = SavedSlots.getString(slot, null);

      // get a SharedPreferences.Editor to store new slot/scores
      SharedPreferences.Editor preferencesEditor = SavedSlots.edit();
      preferencesEditor.putString(slot, P1Score, P2Score, P3Score, P4Score); // to store
      preferencesEditor.apply(); // store the updated preferences

然后在putString下提示错误说:

The method putString(String, String) in the type SharedPreferences.Editor is not  
applicable for the arguments (String, String, String, String, String).

好像一次只能存储2个变量?(即插槽和 P1Score).

It seems that can only store 2 variables at one time? (i.e slot and P1Score).

有 4 个玩家,我想保存他们各自的分数,我该怎么做?

There are 4 players and I would like to save for their respective scores, how can I do so?

推荐答案

putString 只需要两个参数:

  • 第一个参数取key"
  • 第二个参数取值"

你应该使用:

private void makeTag(String P1Score, String P2Score, String P3Score, String P4Score, String slot)
{
    // originalQuery will be null if we're modifying an existing search


    //* For Save your score//

    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
    SharedPreferences.Editor preferencesEditor = SavedSlots.edit();

    preferencesEditor.putString("slot1", "P1Score") // to store
    preferencesEditor.putString("slot2", "P2Score") // to store
    preferencesEditor.putString("slot3", "P3Score") // to store
    preferencesEditor.putString("slot4"," P4Score") // to store
    preferencesEditor.commit(); // store the updated preferences

为了得到你的分数.

String  palyer1 = settings.getString("slot1", "notfound);
String  palyer2 = settings.getString("slot2", "notfound);
String  palyer3 = settings.getString("slot3", "notfound);
String  palyer4 = settings.getString("slot4", "notfound);

更多信息:http://developer.android.com/guide/topics/data/data-storage.html

这篇关于Android 共享首选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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