Android: using getIntent() only within onCreate?
Asked Answered
F

2

7

In Android (targeting APIs 14-16) I have a MainActivity and a NextActivity. There is no difficulty using intents to start NextActivity from within MainActivity if the getIntent() method is called inside the onCreate() block of NextActivity:

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        int data = 7;
        ...
        Intent intent = new Intent(this, NextActivity.class);
        intent.putExtra("data", data);
        startActivity(intent);
        }
    }

public class NextActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final int data = this.getIntent().getIntExtra("data", 7);
        ...
        }
    ...
    }

However, since the field data is being used inside an anonymous ("inner") class in NextActivity, I am compelled to declare it final.

I'd prefer not to declare fields final, and I can usually avoid doing so if I declare them at the beginning of the class, before onCreate() begins. But for some reason, the app crashes when NextActivity starts if the getIntent() statement appears (without the final keyword) outside of onCreate().

Any idea why?

Felker answered 21/12, 2012 at 3:2 Comment(1)
Can you post a logcat of the crash?Moppet
A
10

You can't getIntent() before onCreate() -- there's simply no Intent available at that point. I believe the same is true for anything that requires a Context.

Your anonymous inner class can still call getIntent(), however, so you don't need to declare this as a variable at all.

Airport answered 21/12, 2012 at 4:44 Comment(2)
Good point about context. The variable is needed both within the inner class and elsewhere, and I need to be able to modify it. So perhaps I should declare the variable as non-final but introduce a second, final variable to shepherd the value into the inner class.Felker
Or declare it as a non-final field in the activity with a getter method. You would be able to call getData() from inside or outside the anonymous inner class.Airport
H
1

According to your question what i understand is u don't want to declare data as final in next activity..Then y cant u try for this./

public class NextActivity extends Activity {
    int data=0;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
         data = this.getIntent().getIntExtra("data", 7);
        ...
        }
    ...
    }

Try this...

Hoppe answered 21/12, 2012 at 4:35 Comment(3)
The compiler requires a type declaration; can't run it without int.Felker
Ah, very nice. You got around the problem perfectly.Felker
And this is a fine general method.Felker

© 2022 - 2024 — McMap. All rights reserved.