【问题标题】:How do you save the data of an int, and then edit the number onclick of a button?你如何保存一个int的数据,然后编辑一个按钮的onclick数字?
【发布时间】:2012-02-26 13:22:06
【问题描述】:

我正在尝试拥有它,因此当您单击其中一个答案(Q1A1 或 Q1A2)时,它将为 testScore int 添加一些分数,以便我稍后可以在以后的课程中调用它,这样他们得到的分数就会在那里张贴。感谢任何提前提供帮助的人!
这是我的代码,

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

public class Test extends Activity implements OnClickListener 

{

    TextView Q1A1;
    TextView Q1A2;
    TextView test;

    public static final String PREFS_NAME = "MyPrefsFile";
    public static final int testScore = 0;

    @Override
public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test);
        Q1A1 = (TextView) findViewById(R.id.Q1A1);
        Q1A2 = (TextView) findViewById(R.id.Q1A2);
        Q1A1.setOnClickListener(this);
        Q1A2.setOnClickListener(this);
        test = (TextView) findViewById(R.id.test);




        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        test.setText(settings.getString("YourScore", "No Score"));


    }

    public void onClick(View v) 
    {
        switch(v.getId())
        {
        case R.id.Q1A1:

            SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
            SharedPreferences.Editor editor = settings.edit();
            editor.putInt("YourScore", (testScore + 10));
            editor.commit();

            //Intent FinalScore = new Intent(this, FinalScore.class);
            //startActivity(FinalScore);
            break;
        case R.id.Q1A2:

            break;
        }   
    }   
}

感谢帮助

【问题讨论】:

  • 具体来说,您在哪里遇到问题?这段代码乍一看似乎没问题。

标签: android int sharedpreferences save


【解决方案1】:

您将分数保存为 int,但将其称为字符串。

改变

test.setText(settings.getString("YourScore" , "No Score"));

test.setText(""+settings.getInt("YourScore" , 0));

【讨论】:

  • 第二件事是 testScore 总是从零开始。您可能希望将其设置为您保存的分数。 testScore = settings.getInt("YourScore" , 0 );
  • 感谢它的工作,但现在如果我想有第二个按钮,可以在分数上添加不同的数字但仍在保存中,如果这有意义的话。因此,如果我有第二个按钮 Q1A2,所有相同的代码但 + 5 而不是 10 我在第二个“设置”和“编辑器”上收到错误,说要更改名称但它们不会设置文本不起作用?
  • 老实说,我不确定您这次要问什么。如果您可以将此答案标记为已解决,那就太好了。如果您无法解决新问题,请尝试使用更新后的代码将其发布到新问题中。如果我看到它,我会尽力为您解决。
猜你喜欢
  • 2019-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多