How to use Context to access/manipulate another class/activity

老子叫甜甜 提交于 2019-12-08 09:17:30

you can use ((ActivityName)contextName).methodName()

But it is not a good solution. You can try something like this

pass your activity name along with the context to the async class.

    protected void onPostExecute(SoapObject result)
    {

            if(classname.equals("LoginActivity"))
            {
                ((LoginActivity) object).method();
            }
                    else if(classname.equals("MainActivity"))
            {
                ((MainActivity) object).method();
            }


}

Easy to do, you just create a method in your activity and call it from the instance you pass through AsyncTask parent class constructor.

Assume you have in your activity some like this:

public void Foo(ArrayList<DataType> data)
{
//Do some with data
}

You then call this method from onPostExecute like this:

@Override
        protected void onPostExecute(ArrayList<DataType> data)
        {
                activity.Foo(data);
        }

Where activity is the instance passed through the constructor. Cheers

This involves basic Object Oriented Programming knowledge.

If you look closely at http://developer.android.com/reference/android/app/Activity.html you can see Activity extends Context, that's why you can get away with passing this to your AsyncTask constructor and having the compiler do the required object slicings.

We can use that to your advantage: Create an abstract class extending Activity (Let's say: DataActivity, just an example though, name it whatever you want) and write a method named onDataDownloadComplete(JSONObject json) (A callback) on it, that you would of call on your AsyncTask's onPostExecute. Make all your activities extend from DataActivity and implement that method. Change the AsyncTask context from Context to DataActivity so you can call the onDataDownloadComplete callback and you are done. Again, as DataActivity would of extend Activity and Activity extends Context, DataActivity or anyhting extending it would be a valid context for the AsyncTask.

Hope you find this useful.

I realized there is another way to achieve what I was trying to do. This takes away the Asyncrony, but for the case of login, I actually do want the UI to be inactive while the app trys to log in.

After I call

asyncTask.execute() 

I can call

asyncTask.get()

and that will retrieve the result of doInBackground and allow you to run it on the spot. Alternatively I can use a timeout so I dont block forever:

asynceTask.get(5000, TimeUnit.MILLISECONDS)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!