如何通过 Intent 接收 int

How to receive an int through an Intent

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

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

        }

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

此外,您没有发送 Bundle,而是在 Intent 中发送了 String。所以你需要从 Intent.

得到 String

这样做

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