Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing instance of the parent activity?

Tags:

android

Suppose I have a class first.java (activity class) and I start another activity in this class (second.java - activity class).

How can I access the instance of first.java from second.java?

Can someone give me a good explanation on this... An example would be great...

like image 668
Arun Abraham Avatar asked Feb 09 '11 12:02

Arun Abraham


People also ask

What is the instance for activity?

Activity instances are always created by the Android system. This is because a lot of initializations have to be done for the activity to work. To create a new activity you call startActivity with an Intent describing the activity to start.

How can we call parent activity from fragment?

Simply call your parent activity using getActivity() method.

How do I set parent activity?

Declare a Parent Activity You can do this in the app manifest, by setting an android:parentActivityName attribute. The android:parentActivityName attribute was introduced in Android 4.1 (API level 16). To support devices with older versions of Android, define a <meta-data> name-value pair, where the name is "android.

How do I get back the result from child activity to parent in android?

Intent data = new Intent(); data. putExtra("myData1", "Data 1 value"); data. putExtra("myData2", "Data 2 value"); // Activity finished ok, return the data setResult(RESULT_OK, data); finish();


1 Answers

If you need your second activity to return some data to your first activity I recommend you use startActivityForResult() to start your second activity. Then in onResult() in your first activity you can do the work needed.

In First.java where you start Second.java:

Intent intent = new Intent(this, Second.class); int requestCode = 1; // Or some number you choose startActivityForResult(intent, requestCode); 

The result method:

protected void onActivityResult (int requestCode, int resultCode, Intent data) {   // Collect data from the intent and use it   String value = data.getString("someValue"); } 

In Second.java:

Intent intent = new Intent(); intent.putExtra("someValue", "data"); setResult(RESULT_OK, intent); finish(); 

If you do not wish to wait for the Second activity to end before you do some work in the First activity, you could instead send a broadcast which the First activity reacts to.

like image 70
Eric Nordvik Avatar answered Oct 02 '22 20:10

Eric Nordvik