开发者

Accessing instance of the parent activity?

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...


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.


You can simply call getParent() from the child activity.

I have no clue why other answers are so complicated.


Only this should work

class first
{
    public static first instance;
    oncreate()
    {
        instance = this;
    }
}

first.instance is the required thing that is accessible from the second class


try this if this work 4 u.........
something like this.....

class first
{
public static first instance;
oncreate()
{
instance=this;
}

public static getInstance()
{
return instance;
}

}

now from second class call first.getInstance();

you can also directly acess instance in static way like this first.instance.......
Thanks...


You can't create an activity directly. In the first activity take a static activity variable like this,

public static Activity activity;

In the onCreate do this.

activity = this;

Then in the second activity do this,

Activity activity = (your activity name).activity;

Edit: For passing data from one activity to other activity this is not the way. Above answer was to get activity instance from other activity which was initially asked.

To pass data from one activity to other activty generally use bundle. But if the data is not primitive data type, then use object class which should implement parcelable or serializable interface. Then through bundle only parcelable list of objects we can pass.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜