Skip to content

Instantly share code, notes, and snippets.

@aNNiMON
Last active August 29, 2015 13:59
Show Gist options
  • Save aNNiMON/10616772 to your computer and use it in GitHub Desktop.
Save aNNiMON/10616772 to your computer and use it in GitHub Desktop.
Android Best Practices

Activity

New Instance

public class ExampleActivity extends Activity {

    public static final String EXTRA_PRODUCT_ID = "product_id";
    public static final String EXTRA_PRODUCT_TITLE = "product_title";

    public static Intent newIntent(Context context, long productId, String productTitle) {
        final Intent intent = new Intent(context, ExampleActivity.class);

        intent.putExtra(EXTRA_PRODUCT_ID, productId);
        intent.putExtra(EXTRA_PRODUCT_TITLE, productTitle);

        return intent;
    }
}

Fragment

New Instance

public class ExampleFragment extends Fragment {

    private static final String ARG_PRODUCT_ID = "product_id";
    private static final String ARG_PRODUCT_TITLE = "product_title";

    public static ExampleFragment newInstance(long productId, String productTitle) {
        final ExampleFragment fragment = new ExampleFragment();

        final Bundle args = new Bundle();
        args.putLong(ARG_PRODUCT_ID, productId);
        args.putString(ARG_PRODUCT_TITLE, productTitle);
        fragment.setArguments(args);

        return fragment;
    }
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Bundle args = getArguments();
        if (args != null) {
            long id = args.getLong(ARG_PRODUCT_ID);
            String title = args.getString(ARG_PRODUCT_TITLE);
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment