Accessing instance of the parent activity? - 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...

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.

Related

How to get Object of calling Activity in an Intent?

I have two Activities.
I got my FirstActivity and SecondActivity and I start an Intent from the first activity which brings me from the first to the second one like this:
startActivity(new Intent(FirstActivity.this, SecondActivity.class));
Now I need an Instance of my FirstActivity in the second activity. My working approach was a static instance in my FirstActivity:
private static FirstActivity firstActivity;
onCreate(...) { firstActivity = this; }
public static FirstActivity get() { return firstActivity; }
This although is breaking InstantRun and is considered as a memory leak. I know that I can send Parcelable's through intents, but I need my FirstActivity object.
A typical solution for this is inheritance:
Step #1: Create a BaseActivity class that extends from whatever you are using right now (Activity, AppCompatActivity, etc.)
Step #2: Have FirstActivity extend BaseActivity
Step #3: Move the onCreateOptionsMenu() and onPrepareOptionsMenu() methods from FirstActivity to BaseActivity
Step #4: Have SecondActivity also extend BaseActivity
Another option would be to use static utility methods for the common code bits, where those static methods are called by the onCreateOptionsMenu() and onPrepareOptionsMenu() of FirstActivity and SecondActivity.
//first activity
Bundle bundle = new Bundle();
bundle.putSerializable("TAG", object);
Intent intent = new Intent(getApplicationContext(), ActivityB.class).putExtras(bundle);}
startActivity(intent);
//second activity
onCreate().....
Bundle bundle = getIntent().getExtras();
if(bundle!=null){
Object object = (Object) bundle.get("TAG");
//and implements serializable in your class object

pass data from activity one to activity three directly while going through activity two but data should not be passed to activity two

I have three activities A,B and C. I need to pass some data from activity A to activity C. But the navigation is from A to B to C i.e. I can't go to activity C from activity A directly. I don't want to pass my data to activity B from A and I don't want to use any external storage like sqlite or shared preferences. Can it be done through intent ? If yes , how ? If no, is there any other way ?
use Interface to communicate with other Activity.
or you can make your variable public static on Activity1
The problem is that your third activity has no way of knowing which activity sent the bundle. You need to add a field that identifies what type of bundle this is so you can process accordingly. For instance, in activity 1:
Intent i = new Intent(ActivityOne.this, ActivityTwo.class);
i.putExtra("activity", (int)1);
i.putExtra("key", value);
startActivity(i);
Then in 3rd activity:
Bundle extras = getIntent().getExtras();
if(extras !=null) {
int typeAct = extras.getInt("activity");
if (typeAct == 1) {
//do something with data
}
There are various ways to send the data from one activity to other activity,
Now as you can not use intent so I would suggest you to go with either Application class or create a Global singleton class to hold your data.
Please refer following link
https://androidresearch.wordpress.com/2012/03/22/defining-global-variables-in-android/
Following are the steps to create an application class:
Step 1: Create any class and extend it with the Application class:
public class Globals extends Application{
private int data=200;
public int getData(){
return this.data;
}
public void setData(int d){
this.data=d;
}
}
Step 2: Defining the application class in the manifest file:
<application
android:name=".Globals"
.... />
Step 3:Now by calling getApplication() in any of the activity you get your application class. Just typecast it and call the methods required.
Globals g = (Globals)getApplication();
int data=g.getData();
I hope this will help.
make one interface :
public interface PassData {
public void data(String data);
}
if you want to pass the data from activity A to activity C then :
from Activity A you need to pass the data like this:then on Activity A.
PassData passData;// make it global variable
passData.data("Your DATA WHICH YOU WANT TO SEND TO ACTIVITY C");
In Activity C :
ActivityC extends AppCompatActivity implements PassData{
//onCreate Stuff
#Override
public void data(String data) {
// print this data and see it's coming or not
}
yes sure.
for example in your Activity
class ActivityA extend Activity{
public static String abc = "hello";
}
in ActivityC
ActivityC extend Activity{
onCreate(){
String a = ActivityA.abc;
Log.d("test",a);
}
}

how to send data from activity to fragment when user clicks on back button in android?

I have a fragment that opens up a new activity. how can I pass data back to the fragment from that activity when user clicks on back button?
I've tried creating a new Intent and put data in there then call setResult(), but neither the Fragment or FragmentActivity got anything in onActivityResult. the only way I can think of now is through static method, but still want to see if there's a proper way of doing this?
Thanks!
calling static function and assigning is not a proper solution. you can use interface call back or you can use startActivityForResult() method.
interface callback basic idea ;
public class YourActivity extends Activity{
private MyListener mFragmentCallbackListener;
public YourActivity(MyListener listener){
mFragmentCallbackListener = listener;
}
#Override
public void onBackPressed(){
if(mFragmentCallbackListener != null){
mFragmentCallbackListener.updateFragment(String data);
}
}
public interface MyListener{
void updateFragment(String data)
}
}
I have a fragment that opens up a new activity
Start your Activity using startActivityForResult() instead of startActivity()
I've tried creating a new Intent and put data in there then call setResult(), but neither the Fragment or FragmentActivity got anything in onActivityResult.
If you are using startActivityForResult() then the onActivityResult() will be called after you finished that Acivity.

How to manage all activities transference with conductor class

I want to manage all activities with class conductor like this:
Also all activities extend base activity to use common view.
In this case, I want to handle transfer activity, for example:
Base -> First -> Second -> Third -> First
Base -> First -> Fourth -> Fifth -> Fourth
When transferring activity, Conductor must handle all activity in stack.
I try to write this conductor as below (I use list to manage instead of stack):
public class Conductor {
private List<Activity> listOfActivityInStack;
public Conductor(){
listOfActivityInStack = new ArrayList<Activity>();
}
public void startActivity(Activity activity, Class<?> cls){
listOfActivityInStack.add(activity);
Intent i = new Intent(activity.getApplicationContext(), cls);
activity.startActivity(i);
}
public void startActivityForResult(Activity activity, Class<?> cls, int requestCode){
listOfActivityInStack.add(activity);
Intent i = new Intent(activity.getApplicationContext(), cls);
activity.startActivityForResult(i, requestCode);
}
public void startAcitivtyClearPrevious(Activity activity, Class<?> cls){
listOfActivityInStack.clear();
listOfActivityInStack.add(activity);
Intent i = new Intent(activity.getApplicationContext(), cls);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
activity.startActivity(i);
}
public int getCount(){
if(listOfActivityInStack == null)
return 0;
return listOfActivityInStack.size();
}
}
I store this conductor in Global variable. Then I use it as below:
//Get conductor from application global
conductor.startActivity(FirstActivity.this, SecondActivity.class);
//Then add conductor to application global
But I have some problem:
I must handle goBack() for all activity to remove activity from list.
Check activity has exist in list, if yes, try get its instance.
Is there best way to manage all activity on android? I have tried search but not found good answer. I wonder weather or not my way is right. Any recommend or example would be help!
there is one way to do this. you must save your all activities state. and when you need to recall them you must use that state.
for extra info look here:
Saving Android Activity state using Save Instance State

how to know the calling activity in android

I have an activity which is called by few other activities. For example: I have Activity1,Activity2,Activity3.
Activity1 calls Activity2 and pass parameter.
Activity3 also calls Activity2 and pass parameter.
Now based on the calling activity, Activity2 performs some task.
But how do I know which activity is calling Activity2??
can anybody plz help me??
If you start the activity with startActivityForResult(Intent, int), then you can get calling activity by getCallingActivity().getClassName().
A. If you can use startActivityForResult
As per Zain Ali's answer below: If you can start Activity with startActivityForResult() then you can get name of calling Activity class by this.getCallingActivity().getClassName();
B. If you can not use startActivityForResult
If you can not use startActivityForResult(), then you can use following method:
You can pass additional parameter in intent, check the value in activity and act accordingly.
1) Define an interface or constants class to define integer constants to indicate calling activity
public interface ActivityConstants {
public static final int ACTIVITY_1 = 1001;
public static final int ACTIVITY_2 = 1002;
public static final int ACTIVITY_3 = 1003;
}
2) Add extra parameter in intent while calling Activity2.
Intent act2 = new Intent(context, Activity2.class);
act2.putExtra("calling-activity", ActivityConstants.ACTIVITY_1);
// or ActivityConstants.ACTIVITY_3 if called form Activity3
startActivity(act2);
3) Check the value of this extra parameter in Activity2 and act accordingly..
int callingActivity = getIntent().getIntExtra("calling-activity", 0);
switch (callingActivity) {
case ActivityConstants.ACTIVITY_1:
// Activity2 is started from Activity1
break;
case ActivityConstants.ACTIVITY_3:
// Activity2 is started from Activity3
break;
}
In your calling activity (FirstActivity):
Intent i = new Intent(FirstActivity.this, SecondActivity.class);
i.putExtra("classFrom", FirstActivity.class.toString());
startActivity(i);
And add the following code in the onCreate of the called activity (SecondActivity):
Bundle bundle = getIntent().getExtras();
if (bundle.getString("classFrom").equals(FirstActivity.class.toString())) {
//Do some task
}
Notice that you should be carefully because the bundle object can't be null when you perform "b.getString("classFrom")".
You could pass an additional parameter that specifies the calling Activity.
I successfully use: (Activity).getLocalClassName()
Pass anything(String/ int etc.) to putExtra and base on that do the your work like
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("PARENT_ACTIVITY_REF", "ParentActivityIsA");
startActivity(intent);
And then receive in child like
String parentActivityRef = intent.getStringExtra("PARENT_ACTIVITY_REF");
then
if (parentActivityRef.equals("ParentActivityIsA"){
// do your work here
}else if ...{
// ...
}else{
//...
}
I'm Using This line
if (((((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE)).getRunningTasks(1).get(0).baseActivity)).compareTo(new ComponentName(getPackageName()
, AnyActivityWantToCheck.class.getName())) == 0){
// do somthing .....
}
i hope it work with you
Another solution, using companion object as in the following example:
class MainActivity: BaseActivity {
...
LoginActivity.callerActivity = this
it.context.startActivity(Intent(getActivity(), LoginActivity::class.java))
...
}
class LoginActivity : BaseActivity() {
companion object {
var callerActivity: AppCompatActivity? = null
}
...
callerActivity?.let {
it.callSomething()
}
}

Categories

Resources