【问题标题】:How do I pass an int to another activitiy for calculation in Android Studio? [duplicate]如何将 int 传递给另一个活动以在 Android Studio 中进行计算? [复制]
【发布时间】:2020-10-17 12:36:19
【问题描述】:

我正在创建一个简单的问答游戏,用户必须旋转“命运之轮”来决定他得到的是高分问题还是低分问题。轮子停止几毫秒后,他获得的分数将被带到另一个活动中,他将在那里回答问题。

这是为了将分数从这个文件 (Play.java) 传递给其他活动 (Quiz.java):

int mScore = 0;
timerQuiz = new CountDownTimer(500, 1000) {
            @Override
            public void onFinish() {
                Intent i = new Intent(Play.this, Quiz.class);
                i.putExtra("keyscore", mScore);
                startActivity(i);
                finish();
            }
            @Override
            public void onTick(long millisLeft) {
                // not ticking
            }
        };

这是为了从 Play.java 中提取分数:

int mScore = getIntent().getIntExtra("keyscore", 0);

由于某种我不知道的原因,它说它找不到符号“mScore”。当我在 Quiz.java 文件上启动 int mScore = 0; 时,当我尝试运行游戏时它给了我一个 NullPointerException 错误。我已经阅读了一些关于如何修复错误的文章,然后尝试自行修复,但无济于事。

作为参考,这里是 Play.java 的完整代码:

package com.example.al_biruniapp;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.Toast;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.Random;

public class Play extends AppCompatActivity {

    private Button btnSpin;
    private TextView txtTop;
    private ImageView colorWheel;

    Random r;
    int degree = 0, degree_old =0;
    private Dialog dialog;
    private CountDownTimer timerQuiz;
    private  static final float FACTOR = 15f;

    int mScore = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play);

        btnSpin = (Button) findViewById(R.id.btnSpin);
        txtTop = (TextView) findViewById(R.id.txtTop);
        colorWheel = (ImageView) findViewById(R.id.colorWheel);
        dialog = new Dialog(Play.this);

        r = new Random();

        btnSpin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                degree_old = degree % 360;
                degree = r.nextInt(3600) + 720;

                //some animation and calculation for the spinny thingy
                RotateAnimation rotate = new RotateAnimation(degree_old,degree,
                        RotateAnimation.RELATIVE_TO_SELF,0.5f,RotateAnimation.RELATIVE_TO_SELF,0.5f);
                rotate.setDuration(2000);
                rotate.setFillAfter(true);
                rotate.setInterpolator(new DecelerateInterpolator());
                rotate.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {
                        txtTop.setText("");
                    }
                    @Override
                    public void onAnimationEnd(Animation animation) {
                        txtTop.setText(currentNumber(360 - (degree % 360)));
                    }
                    @Override
                    public void onAnimationRepeat(Animation animation) {
                    }
                });
                colorWheel.startAnimation(rotate);
                timerQuiz.start();
            }
        });

    }

    //this is the main spinny thingy process
    private String currentNumber(int degrees){
        String text="";
        if(degrees >= (FACTOR * 1) && degrees < (FACTOR * 3)){
            text = "BONUS";
            mScore = mScore + 70;
            nextActivity();
        }if(degrees >= (FACTOR * 3) && degrees < (FACTOR * 5)){
            text = "BONUS";
            mScore = mScore + 70;
            nextActivity();
        }if(degrees >= (FACTOR * 5) && degrees < (FACTOR * 7)){
            text = "+ 50 bir";
            mScore = mScore + 50;
            nextActivity();
        }if(degrees >= (FACTOR * 7) && degrees < (FACTOR * 9)){
            text = "+ 50 bir";
            mScore = mScore + 50;
            nextActivity();
        }if(degrees >= (FACTOR * 9) && degrees < (FACTOR * 11)){
            text = "+ 30 bir";
            mScore = mScore + 30;
            nextActivity();
        }if(degrees >= (FACTOR * 11) && degrees < (FACTOR * 13)){
            text = "+ 30 bir";
            mScore = mScore + 30;
            nextActivity();
        }if(degrees >= (FACTOR * 13) && degrees < (FACTOR * 15)){
            text = "+ 40 bir";
            mScore = mScore + 40;
            nextActivity();
        }if(degrees >= (FACTOR * 15) && degrees < (FACTOR * 17)){
            text = "+ 40 bir";
            mScore = mScore + 40;
            nextActivity();
        }if(degrees >= (FACTOR * 17) && degrees < (FACTOR * 19)){
            text = "Hilang Pusingan";
            gameOver();
        }if(degrees >= (FACTOR * 19) && degrees < (FACTOR * 21)){
            text = "SUPER BONUS";
            mScore = mScore + 100;
            nextActivity();
        }if(degrees >= (FACTOR * 21) && degrees < (FACTOR * 23)){
            text = "+ 40 bir";
            mScore = mScore + 40;
            nextActivity();
        }if(degrees >= (FACTOR * 23) && degrees < (FACTOR * 25)){
            text = "+ 40 bir";
            mScore = mScore + 40;
            nextActivity();
        }if((degrees >= (FACTOR * 25) && degrees < 360) || (degrees >= 0 && degrees < (FACTOR * 1))) {
            text = "+ 40 bir";
            mScore = mScore + 40;
            nextActivity();
        }
        return text;
    }
    private void gameOver(){
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Play.this);
        alertDialogBuilder
                .setMessage("Pusingan Tamat! Sila cuba lain kali ????")
                .setCancelable(false)
                .setPositiveButton("Back To Menu",
                        new DialogInterface.OnClickListener(){
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i){
                                startActivity(new Intent(getApplicationContext(), Menu.class));
                                finish();
                            }
                        })
                .setNegativeButton("Quit Game",
                        new DialogInterface.OnClickListener(){
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i){
                                finish();
                            }
                        });
        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
    }
    private void nextActivity(){
        timerQuiz = new CountDownTimer(500, 1000) {
            @Override
            public void onFinish() {
                Intent i = new Intent(Play.this, Quiz.class);
                i.putExtra("keyscore", mScore);
                startActivity(i);
                finish();
            }
            @Override
            public void onTick(long millisLeft) {
                // not ticking
            }
        };
    }
}

这是 Quiz.java 的代码:

package com.example.al_biruniapp;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import java.util.Random;

public class Quiz extends AppCompatActivity {

    Button answer1, answer2;
    TextView score, question;

    private Questions mQuestions = new Questions();
    private String mAnswers;
    private int mQuestionsLength = mQuestions.mQuestions.length;

    MediaPlayer correct, wrong;

    Dialog dialog;

    Random r;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_quiz);

        int mScore = getIntent().getIntExtra("keyscore", 0);

        dialog = new Dialog(Quiz.this);
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
            dialog.getWindow().setBackgroundDrawable(getDrawable(R.drawable.background));
        };
        dialog.setContentView(R.layout.dialog);
        dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.setCancelable(false);

        r = new Random();

        answer1 = findViewById(R.id.answer1);
        answer2 = findViewById(R.id.answer2);

        score = findViewById(R.id.score);
        question = findViewById(R.id.question);

        score.setText("Score : " + mScore);

        updateQuestion(r.nextInt(mQuestionsLength));

        correct = MediaPlayer.create(this, R.raw.correct);
        wrong = MediaPlayer.create(this, R.raw.wrong);

        answer1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(answer1.getText().toString() == mAnswers){
                    mScore++;
                    score.setText("Score : " + mScore);
                    updateQuestion(r.nextInt(mQuestionsLength));
                    correct.start();
                    dialog.show();
                }else {
                    wrong.start();
                    gameOver();
                }
            }
        });
        answer2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(answer2.getText().toString() == mAnswers){
                    mScore++;
                    score.setText("Score : " + mScore);
                    updateQuestion(r.nextInt(mQuestionsLength));
                    correct.start();
                    dialog.show();
                }else {
                    wrong.start();
                    gameOver();
                }
            }
        });
    }
    private void updateQuestion(int num){
        question.setText((mQuestions.getQuestion(num)));
        answer1.setText((mQuestions.getChoice1(num)));
        answer2.setText((mQuestions.getChoice2(num)));

        mAnswers = mQuestions.getCorrectAnswer(num);
    }
    private void gameOver(){
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Quiz.this);
        alertDialogBuilder
                .setMessage("Game Over! Your Final Score is " + mScore + " bir.")
                .setCancelable(false)
                .setPositiveButton("Back To Menu",
                        new DialogInterface.OnClickListener(){
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i){
                                startActivity(new Intent(getApplicationContext(), Menu.class));
                                finish();
                            }
                        })
                .setNegativeButton("Quit Game",
                        new DialogInterface.OnClickListener(){
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i){
                                finish();
                            }
                        });
        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
    }
    public void onCompletion(MediaPlayer mp) {
        mp.release();
    }
}

我还是 Java 编程新手,很抱歉问了这么愚蠢的问题。

【问题讨论】:

    标签: java android nullpointerexception


    【解决方案1】:

    您应该尝试从捆绑包中获取它。

    Bundle passedInformation = getIntent().getExtras();
    
    int mScore = passedInfomration.getInt("keyscore");
    

    【讨论】:

    • 非常感谢,但现在它给了我另一个错误,Attempt to invoke virtual method 'android.os.CountDownTimer android.os.CountDownTimer.start()' on a null object reference at com.example.al_biruniapp.Play$1.onClick(Play.java:77)。虽然 CountDownTimer 不为空...
    【解决方案2】:

    您可以通过意图将值和对象传递给其他活动。

    假设:

    • Activity_A = 发送活动
    • Activity_B = 接收活动

    您可以通过将单个值作为 Extra 传递单个值:

    //Activity A
    static final String KEY_EXTRA_VALUE = "EXTRA_VALUE"; /*key to identify value in 
                                                           Intent*/
    int your_value = 5;
    
    Intent intent = new Intent(this, Activity_B.class);
    intent.putExtra(KEY_EXTRA_VALUE, your_value);
    
    startActivity(intent);
    
    
    //Activity B
    static final String KEY_EXTRA_VALUE = "EXTRA_VALUE"; /*key to identify value in 
                                                           Intent*/
    int your_value = getIntent().getIntExtra(KEY_EXTRA_VALUE, -1); /*-1 is default 
                                                                     value*/
    

    (请注意,getIntent() 始终返回启动此 Activity 的意图)

    要将多个值发送到另一个 Activity,您应该先将它们捆绑到一个 Bundle 对象中:

    //Activity A
    String s1 = "test1"; //values you want to send
    String s2 = "test2";
    
    static final String KEY_EXTRA_VALUE_1 = "EXTRA_VALUE_1"; /*keys to identify values 
                                                               in Bundle*/
    static final String KEY_EXTRA_VALUE_2 = "EXTRA_VALUE_2";
    
    Bundle bundle = new Bundle();
    bundle.putString(KEY_EXTRA_VALUE_1, s1);
    bundle.putString(KEY_EXTRA_VALUE_2, s2);
    
    Intent intent = new Intent(this, Activity_B.class);
    intent.putExtras(bundle);
    
    startActivity(intent);
    
    
    //Activity B
    static final String KEY_EXTRA_VALUE_1 = "EXTRA_VALUE_1"; /*keys to identify values 
                                                               in Bundle*/
    static final String KEY_EXTRA_VALUE_2 = "EXTRA_VALUE_2";
    
    Bundle passed_Bundle = getIntent().getExtras();
    String s1 = passed_Bundle.getString(KEY_EXTRA_VALUE_1);
    String s2 = passed_Bundle.getString(KEY_EXTRA_VALUE_2);
    

    要将对象发送到另一个 Activity,它必须是 Parcelable。

    您可以阅读 Parcelables here。但原理是一样的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-08
      • 2022-01-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多