Skip to content Skip to sidebar Skip to footer

Make My Class Take An Argument

Well I have a main Screen with 5 buttons. Each time a press a button I want to go a new screen. So far I have other 5 classes (each for each screen) and 5 xmls. But Iam sure that t

Solution 1:

If I understand your question correctly, you want to pass arguments to the activity. Normally it would be done through the class constructor, however, activities can't have user defined constructors, only the default one; they can be instantiated only indirectly via intent creation. If you need to pass data between activities, do it by putting extras to bundles, for example:

bundle.putInt("intName",intValue);

then you can extract the data from bundle by

int intValue = bundle.getInt("intName");

Put extras before starting the activity:

Intenti=newIntent(this, YourActivity.class);
Bundleb=newBundle();

b.putInt("intName",intValue);
i.putExtras(b);
startActivity(i);

and then read the extras in the onCreate method:

publicvoidonCreate(Bundle savedInstanceState)
{
   super.onCreate(savedInstanceState);

   Bundleb= getIntent().getExtras();
   int intValue;

   if (b != null)
   {
      intValue= b.getInt("intName");
   }
}

The same way you can pass other data types as String boolean etc. If this is not sufficient and you need to pass some more complex data, then use Parcelable interface.

Solution 2:

You can pass parameters with an Intent by adding extra's to it, something like the following:

Intent i = newIntent(this, MyActivity.class);
i.putExtra("paramName", "value");
startActivity(i);

In your activity you can use the getIntent() method to retrieve the Intent and extract your parameter(s) from it:

Intenti= getIntent();
Bundleextras= i.getExtras();
Stringparam= extras.getString("paramName", "default value");

You can place all the different text and data in your Intent, but you can also decide based on the value of an Intent parameter which data and text to retrieve. If it is a lot of data or text you are probably better off using the second approach.

Solution 3:

If you want to pass object instead of simple data, you must use parcelable objects as it´s explained in: [http://developer.android.com/reference/android/os/Parcelable.html][1]

Reading and writing with parcelable objects is very similar to the way with a simple data

Intent intent = new Intent(this ,newthing.class);
Bundle b = new Bundle();
b.putParcelable("results", listOfResults);
intent.putExtras(b);
startActivityForResult(intent,0);

Intent i = getIntent();
Bundle extras = i.getExtras();
String param = extras.getParcelable("results");

Post a Comment for "Make My Class Take An Argument"