TheChosenWan
TheChosenWan

Reputation: 43

Android: How to get the activity calling the class

I have Activity1 and Activity2. Both can call a class named "fetchData.java". Is there any way inside fetchData.java wherein I can get which activity called it?

Here is my fetchData.java:

public class fetchData extends AsyncTask<String,String,String> {

    @Override
    protected String doInBackground(String... voids) {
    //do something
    }

    @Override
    protected void onPostExecute(String aVoid) {
        super.onPostExecute(aVoid);
    }
}

Activity1 and Activity2 code:

public class Activity1 extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Call fetchData.java
        fetchData getValues = new fetchData();
        getValues.execute();
}

Upvotes: 0

Views: 50

Answers (1)

TheWanderer
TheWanderer

Reputation: 17874

The only way I can see for you to do this is by passing the Activity in the constructor:

public class FetchData extends AsyncTask<String, String, String> { //rename fetchData to FetchData to follow Java coding practices
    private Activity activity;

    public FetchData(Activity activity) {
        this.activity = activity;
    }

    @Override
    protected String doInBackground(String... strings) { //use the proper variable names
        //...
    }

    @Override
    protected void onPostExecute(String string) { //use the proper variable names
        //use instanceof to check the identity of the activity instance
        if (activity instanceof Activity1) {
            //whatever
        } else if (activity instanceof Activity2) {
            //whatever else
        }
        //super call isn't needed
    }
}

And to instantiate it:

FetchData getValues = new FetchData(this);
getValues.execute();

Take note of my comments. I made a few changes to your code to improve readability and conform better to Java's coding standards.

In other cases, you might be able to read the stacktrace and find the calling class, but since you're using an AsyncTask, which runs on another Thread, the stacktrace only goes back to when the Thread was created, so it wouldn't work here.

Upvotes: 1

Related Questions