【问题标题】:Passing variable score from one activity to another将可变分数从一项活动传递到另一项活动
【发布时间】:2017-05-19 07:32:40
【问题描述】:

我正在制作一个简单的测验应用程序,其中包含 10 个问题,每个问题都有 10 秒的倒数计时器,这意味着我有 10 个问题活动。当每个问题正确回答乘以 CountDownTimer 方法的剩余时间时,评分有效,因此它将是: score = answer * timeLeft;并且总分将在活动 10 之后的活动结束时打印在 ResultActivity 上。问题是我无法通过每个活动传递我的分数变量,当我单击下一个按钮时,该意图从活动 10 到 ResultActivity,ResultActivity 无法打开或强制关闭。这是我的代码:

TestActivity1

package com.finalproject.logicaltest;

import android.content.Intent;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.TextView;

import java.util.Timer;

import butterknife.ButterKnife;
import butterknife.Bind;

import static android.R.id.message;
import static android.R.string.cancel;
import static com.finalproject.logicaltest.R.id.rb1;
import static com.finalproject.logicaltest.R.id.rb2;
import static com.finalproject.logicaltest.R.id.rb3;
import static com.finalproject.logicaltest.R.id.rb4;


public class TestActivity1 extends AppCompatActivity {

    @Bind(R.id.rb1) RadioButton rB1;
    @Bind(R.id.rb2) RadioButton rB2;
    @Bind(R.id.rb3) RadioButton rB3;
    @Bind(R.id.rb4) RadioButton rB4;
    @Bind(R.id.next) Button bNext;
    @Bind(R.id.timer) TextView cDown;

    public int answer = 0;
    public int score = 0;
    public long timeLeft = 0;
    //The number of milliseconds in the future from
    //the call to start() until the countdown is done
    public long millisInFuture = 11000; //11 seconds
    //The interval along the way to receive onTick(long) callbacks
    long countDownInterval = 1000; //1 second

    public long millisUntilFinished;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test1);
        ButterKnife.bind(this);

        setTimer();

    }

    public void setTimer() {

        //Initialize a new CountDownTimer instance
       final CountDownTimer timer = new CountDownTimer(millisInFuture,countDownInterval){
            public void onTick(long millisUntilFinished){
                //do something in every tick
                //Display the remaining seconds to app interface
                //1 second = 1000 milliseconds
                cDown.setText("" + millisUntilFinished / 1000);
                timeLeft = millisUntilFinished / 1000;

            }
            public void onFinish(){
                //Do something when count down finished
                cDown.setText("NEXT!");
                Intent intent = new Intent(TestActivity1.this,TestActivity2.class);
                intent.putExtra("score", score);
                startActivity(intent);
                finish();
                timeLeft = 0;
            }


        }.start();

        bNext.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                timer.cancel();
                timeLeft = millisUntilFinished;
                Intent intent = new Intent(TestActivity1.this,TestActivity2.class);
                intent.putExtra("score", score);
                startActivity(intent);
                finish();
                overridePendingTransition(R.anim.fade_in, R.anim.fade_out);

            }

        });

    }

    public void onRadioButtonClicked (View v) {

        boolean checked = ((RadioButton) v).isChecked();

        switch (v.getId()) {

            case rb1:
                if (checked){
                    answer++;
                    break;
                }

            case rb2:
                if (checked){
                    answer = 0;
                    break;
                }

            case rb3:
                if (checked){
                    answer = 0;
                    break;
                }

            case rb4:
                if (checked){
                    answer = 0;
                    break;
                }
        }

        score = ((int)(timeLeft) * Integer.valueOf(answer));

    }




}

它使用 putExtra 通过 TestActivity2 直到 TestActivity10 像这样通过分数:

package com.finalproject.logicaltest;

/**
 * Created by VICKY on 19-May-17.
 */

import android.app.Activity;
import android.content.Intent;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.TextView;

import butterknife.ButterKnife;
import butterknife.Bind;

import static com.finalproject.logicaltest.R.id.rb1;
import static com.finalproject.logicaltest.R.id.rb2;
import static com.finalproject.logicaltest.R.id.rb3;
import static com.finalproject.logicaltest.R.id.rb4;
import static com.finalproject.logicaltest.R.id.rb5;

public class TestActivity10 extends AppCompatActivity {

    @Bind(rb1) RadioButton rB1;
    @Bind(rb2) RadioButton rB2;
    @Bind(rb3) RadioButton rB3;
    @Bind(rb4) RadioButton rB4;
    @Bind(rb5) RadioButton rB5;
    @Bind(R.id.end) Button bEnd;
    @Bind(R.id.timer) TextView cDown;

    public int answer = 0;
    public int score = 0;
    public long timeLeft = 0;
    //The number of milliseconds in the future from
    //the call to start() until the countdown is done
    public long millisInFuture = 11000; //11 seconds
    //The interval along the way to receive onTick(long) callbacks
    long countDownInterval = 1000; //1 second

    public long millisUntilFinished;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test10);
        ButterKnife.bind(this);
        score = getIntent().getExtras().getInt("score");

        setTimer();
    }

    public void setTimer() {


        //Initialize a new CountDownTimer instance
        final CountDownTimer timer = new CountDownTimer(millisInFuture,countDownInterval){
            public void onTick(long millisUntilFinished){
                //do something in every tick
                //Display the remaining seconds to app interface
                //1 second = 1000 milliseconds
                cDown.setText("" + millisUntilFinished / 1000);
                timeLeft = millisUntilFinished / 1000;
            }
            public void onFinish(){
                //Do something when count down finished
                cDown.setText("NEXT!");
                Intent intent = new Intent(TestActivity10.this,ResultActivity.class);
                intent.putExtra("score", score);
                startActivity(intent);
                finish();
                timeLeft = 0;
            }
        }.start();


        bEnd.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                timer.cancel();
                timeLeft = millisUntilFinished;
                Intent intent = new Intent(TestActivity10.this,ResultActivity.class);
                intent.putExtra("score", score);
                startActivity(intent);
                finish();
                overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
            }

        });
    }

    public void onRadioButtonClicked (View v) {

        boolean checked = ((RadioButton) v).isChecked();

        switch (v.getId()) {

            case rb1:
                if (checked){
                    answer = 0;
                    break;
                }

            case rb2:
                if (checked){
                    answer++;
                    break;
                }

            case rb3:
                if (checked){
                    answer = 0;
                    break;
                }

            case rb4:
                if (checked){
                    answer = 0;
                    break;
                }

            case rb5:
                if (checked){
                    answer = 0;
                    break;
                }
        }

        score += ((int)(timeLeft) * Integer.valueOf(answer));

    }




}

并在 ResultActivity 上打印总分:

package com.finalproject.logicaltest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import static android.R.id.message;


public class ResultActivity extends AppCompatActivity {
    public int score = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_result);
        score = getIntent().getExtras().getInt("score");
        TextView result = (TextView) findViewById(R.id.total_score);
        result.setText(score);
    }
}

我的代码有什么问题?

【问题讨论】:

  • 您可以将结果的值存储在 shared Preference 中并在结果屏幕中获取它,而不是总是传递它。
  • 为什么要为每个问题创建活动?您应该尽可能多地使用 Fragment 并重复使用它。
  • I'm making a simple quiz app that consist of 10 questions with 10sec countdown timer each questions, which means i have 10 activity for questions 这似乎是您试图以错误的方式解决问题。我想你可以只有一个通用的活动来接受一个问题然后显示这个问题,而不是为每个问题创建一个新的活动。现在你所有的 10 项活动基本上都是彼此的副本。随着时间的推移,维护这些将变得更加困难。
  • 不工作是什么意思?分数返回 0 或者你得到一个异常或者......?
  • 检查一次 Android Monitor 是否有任何异常。

标签: java android


【解决方案1】:

你好试试这个代码它可能会有所帮助,根据你的逻辑使用

声明和初始化

SharedPreferences sharedpreferences;
sharedpreferences = getSharedPreferences("results", Context.MODE_PRIVATE);

存储您的分数以用于其他活动

SharedPreferences.Editor editor = sharedpreferences.edit();
            editor.putString("score", score);
            editor.commit();

检索存储的数据

SharedPreferences prefs = this.getSharedPreferences("results", Context.MODE_PRIVATE);
String lanSettings = prefs.getString("score", null);

【讨论】:

  • 我应该在哪里写这段代码?在 onCreate?公开课?或者哪种方法?
  • 你必须在开始测试之前使用 SharedPreferences,onCreate 在这里可以正常工作
  • 我只需要添加这些代码或用我的其他错误代码替换它?我应该更换哪一个?在声明中,与我的不同,您没有声明像 public int score = 0; 这样的全局变量,否则它会自动工作?我应该让 putExtra() 写在那里还是用 SharedPreferences 替换它?
  • 你应该使用共享偏好而不是发送意图
  • editor.putInt("userScore1", 零); int userScore1 = prefs.getInt("userScore1",0); editor.putFloat("percantage", 1.2f); float someFloat = prefs.getFloat("percantage", 0.0f);
【解决方案2】:

您可以为此使用 Application 类,将分数值保存在 Application 类中,该类可以从您想要的任何类访问。(因为您只需要保存分数值。)有关更多信息,您可以检查here

希望对你有帮助..

【讨论】:

  • 虽然这是一个可行的解决方案,但通常不建议这样做。为什么Application 类要保存这些数据?最好通过 Intent 和 Extras 传递它。
  • 您只需要分数值 .... 因为该应用程序类可以工作。毫无疑问,意图是它应该工作的好方法,但应用程序类也可以在这里工作,检查我提到的链接。
  • 我的观点是,在 Application 类中转储所有内容很快就会导致紧密耦合的系统成为一个怪物,可以进行任何形式的测试/重构。
【解决方案3】:

IMO 您将 score 设置为您的 TextView,这是不正确的。 要么这样设置:

result.setText(String.valueOf(score));

或者像这样:

result.setText(" "+score);

看看这是否有效。

【讨论】:

    猜你喜欢
    • 2014-09-19
    • 2012-01-24
    • 2014-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-08
    相关资源
    最近更新 更多