Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android activity class constructor working

When considering the case with android activity, the first method to work is its onCreate method..right?

Suppose i want to pass 2 parameters to android activity class say UserHome . For that am creating the constructor of activity class UserHome and accepting the params.

But when we are calling an activity we are not initializing the Activity class, we are just creating an intent of UserHome class.

Then how can we pass params to that activity from another activity without using intent.putExtra("keyName", "somevalue"); usage.

Experts please clarify how we can cover a situation like this.?

like image 566
TKV Avatar asked Jan 04 '12 10:01

TKV


1 Answers

Not sure why you would not want to use the intent params. That is what they are there for. If you need to pass the same parameters from different places in your application, you could consider using a static constructor that builds your intent request for you.

For example:

/**
 * Sample activity for passing parameters through a static constructor
 * @author Chase Colburn
 */
public class ParameterizedActivity extends Activity {

    private static final String INTENT_KEY_PARAM_A = "ParamA";

    private static final String INTENT_KEY_PARAM_B = "ParamB";

    /**
     * Static constructor for starting an activity with supplied parameters
     * @param context
     * @param paramA
     * @param paramB
     */
    public static void startActivity(Context context, String paramA, String paramB) {
        // Build extras with passed in parameters
        Bundle extras = new Bundle();
        extras.putString(INTENT_KEY_PARAM_A, paramA);
        extras.putString(INTENT_KEY_PARAM_B, paramB);

        // Create and start intent for this activity
        Intent intent = new Intent(context, ParameterizedActivity.class);
        intent.putExtras(extras);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Extract parameters
        Bundle extras = getIntent().getExtras();
        String paramA = extras.getString(INTENT_KEY_PARAM_A);
        String paramB = extras.getString(INTENT_KEY_PARAM_B);

        // Proceed as normal...
    }
}

You can then launch your activity by calling:

ParameterizedActivity.startActivity(this, "First Parameter", "Second Parameter");

like image 100
Chase Avatar answered Nov 02 '22 22:11

Chase