Albin Skaria
Albin Skaria

Reputation: 11

Why we are not passing any value to an activity using constructor?

Activity activity = new Activity(String var1, String var2);
startActivity(new Intent(mContext, activity.getClass());

Upvotes: 0

Views: 97

Answers (1)

Jefferson Tavares
Jefferson Tavares

Reputation: 991

Because activities and fragments must be initialized by android itself, so how are you supposed to pass arguments, lets say, to the Lauch activity of your app? That's the reason why both activities and fragments must have only a default no argument constructor. If you want to use this as a way of making sure that arguments are properly passed to the activity before you start it, you can use the following pattern.

public class MyActivity extends AppCompatActivity {
    public static Intent newIntent(Context context, String arg1, String arg2) {
        Intent intent = new Intent(context, MyActivity.class)

        intent.putExtra("extra_arg1", arg1);
        intent.putExtra("extra_arg2", arg2);


        return intent;


     }

}

Upvotes: 1

Related Questions