小编典典

如何通过意图接收int

java

我正在通过一个Intent传递一个int,但是我不知道如何接收它,因为我必须从OnCreate方法中接收一个intent,但是如果我将其放置在那里,则无法将其与其余代码中的另一个int进行比较:我在这里发送意图:

public class HomeActivityPro extends ActionBarActivity {
EditText conttext = (EditText) findViewById ( R.id.texthome );
Button buttone = (Button) findViewById(R.id.buttone);
String maxom = conttext.getText().toString();
int maxam = Integer.parseInt(maxom);

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

    View.OnClickListener maxim = new View.OnClickListener() {
        @Override
        public void onClick (View view) {
            Intent wall = new Intent(HomeActivityPro.this, GuessOne.class);
            wall.putExtra("maxPressed", maxam);
            startActivity(wall);
        }
    };
    buttone.setOnClickListener(maxim);

在这里,我收到它:

public class GuessOne extends ActionBarActivity {
    int randone;
    int contone;
    Bundle bundle;
    int maxnumpre = 0;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_guess_one);
    Intent wall = getIntent();
    int maxnumpre = wall.getIntExtra("maxPressed", 0);}

但是在onCreate方法之后,我必须这样做:

if (contone >= maxnumpre ){
            resultaone.setText("You Failed" + " " + maxnumpre);
            Toast.makeText(this, "You Failed", Toast.LENGTH_LONG).show();

        }

阅读 245

收藏
2020-12-03

共1个答案

小编典典

您需要获取在onCreate方法中传递的数据,而不是在声明中。

另外你不发送Bundle,正在发送StringIntent。所以,你需要得到StringIntent

像这样做

public class GuessOne extends ActionBarActivity {
    int randone;
    int contone;
    Bundle bundle;
    String maxPressed = "";
    int maxcont = 0;

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

        maxPressed = getIntent().getStringExtra("maxNumberPressed");
        try {
            maxCont = Integer.parseInt(maxPressed);
        }
        catch (NumberFormatException e) {
            e.printStackTrace();
        } 
    }

    //the rest of the code

还发送这样的数据

Intent wall = new Intent(HomeActivityPro.this, GuessOne.class);
wall.putExtra("maxNumberPressed", conttext.getText().toString());
startActivity(wall);
2020-12-03