简体   繁体   中英

Android app crashes when retrieving int from an intent in another activity

I am trying to make a button in one activity (SetupMenu) that, when pressed, puts an int into the intent and carries that over to the next activity (IntroActivity) where a textView will retrieve the int and display it.

Problem is, when the app runs and I get to the activity and press the button, the app crashes and my emulator tells me that "Unfortunately [my app] has stopped working."

I feel like I've tested every possible angle to get this to work. I should note that the button has worked fine, the textview has worked fine, everything else is working smoothly - I only run into issues when I try retrieving the intent and displaying it in textView. I tried passing through a String instead of an Int and also had issues (my string would not appear). Any pointers?

SetupMenu activity (here I put an int into my intent):

public class SetupMenu extends Activity {

    public final static String extra_progress_key = "com.example.angelsanddemons.track_players";
    public int track_players = 0;

    public void to_intro(View view) {
        Intent intent = new Intent(this, IntroActivity.class);
        intent.putExtra(extra_progress_key, track_players);
    startActivity(intent);
}

IntroActivity activity (here I try to retrieve the int from the intent):

public class IntroActivity extends Activity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();
        int temp = intent.getIntExtra(SetupMenu.extra_progress_key, 0 );
        TextView textView = new TextView(this);
        textView.setText(temp);
        setContentView(textView);
    }
}

One problem is that you can't set a TextView's text to an int; you'll need to first convert it to an string. It's also not a good idea to be manipulating views before you've inflated them, so perhaps your onCreate() should be:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Intent intent = getIntent();
    int temp = intent.getIntExtra(SetupMenu.extra_progress_key, 0 );
    TextView textView = new TextView(this);
    setContentView(textView);
    textView.setText(String.valueof(temp));
}

I see nothing that ensure that SetupMenu activity is created and in memory when IntroActivity is launched. To make sure, don't pass the variable, but the string itself and check if it work: int temp = intent.getIntExtra("com.example.angelsanddemons.track_players", 0 );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM