如何将一个整数传递给另一个活动以在Android Studio中进行计算?

huangapple go评论91阅读模式
英文:

How do I pass an int to another activitiy for calculation in Android Studio?

问题

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

I'm creating a simple quiz game where the user have to spin a "wheel of fortune" thingy to decide whether he got a high-point question or a low-point question. A few milliseconds after the wheel stops, the points that he got will be carried away to another activity where he will answer a question.

This is for passing the score from this file (Play.java) to the other activity (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
            }
        };

This is for pulling the score from the Play.java :

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

For some reason that I don't know, it said that it cannot find the symbol 'mScore'. When I initiate int mScore = 0; on the Quiz.java file, it gives me a NullPointerException error when I try to run the game. I've read some articles on how to fix the error, then tried fixing it my self but to no avail.

For some reference, here is the full code for 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
            }
        };
    }
}

Here is the code for 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();
    }
}

I'm still new to programming in java and I apologize for asking such a dumb question.

答案1

得分: 1

从捆绑包中尝试获取它。

Bundle passedInformation = getIntent().getExtras();

int mScore = passedInfomration.getInt("keyscore");
英文:

You should try to get it from the bundle.

Bundle passedInformation = getIntent().getExtras();

int mScore = passedInfomration.getInt("keyscore");

答案2

得分: 0

你可以通过意图(Intent)将值和对象传递给其他活动(Activity)。

假设:

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

你可以通过将单个值直接放置为额外信息(Extra)来传递单个值:

// Activity A
static final String KEY_EXTRA_VALUE = "EXTRA_VALUE"; // 用于在意图中识别值的键
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"; // 用于在意图中识别值的键
int your_value = getIntent().getIntExtra(KEY_EXTRA_VALUE, -1); // -1 是默认值

(请注意,getIntent() 总是返回启动此活动的意图)

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

// Activity A
String s1 = "test1"; // 要发送的值
String s2 = "test2";

static final String KEY_EXTRA_VALUE_1 = "EXTRA_VALUE_1"; // 用于在 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"; // 用于在 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);

要将对象发送到另一个活动,它必须是 Parcelable(可捆绑的)。

您可以在此处阅读有关 Parcelable 的信息。但原则是相同的。

英文:

You can pass values and objects to other activitys with an intent.

Let's say:

  • Activity_A = sending activity
  • Activity_B = recieving activity

You can pass single values by just putting them as an 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*/

(note that getIntent() always returns the intent, that started this Activity)

To send multiple values to another Activity, you should bundle them into a Bundle object first:

//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);

To send Objects to another Activity, it has to be Parcelable.

You can read about Parcelables here. But the principle is the same.

huangapple
  • 本文由 发表于 2020年10月17日 20:36:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/64402526.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定