My android app uses a single Activity which creates a single SurfaceView which is not defined in the manifest, and all of my UI elements are custom. Now I’m trying to make an asynchronous HTTP call and I can’t access any of my application’s classes. Every example I’ve seen for an async http call looks something like this:
class RequestTask extends AsyncTask<String, String, String>{
@Override
protected String doInBackground(String... uri) {
// Code to make http call
return responseString;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
TextView txt = (TextView) findViewById(R.id.output);
// format the result and write it to the TextView object
}
}
In that example, since the RequestTask doesn’t have access to any application objects, you get at them with findViewByID. What I don’t understand is, how can I access my application’s objects if I don’t have any Views defined in my manifest? The only thing in my manifest is the Activity:
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.blah.blah.MyActivity"
android:label="@string/app_name" >
android:configChanges="keyboardHidden|orientation" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
I did this for simplicity/laziness and it’s worked fine so far. Is there a way to access my application (either the activity, or the views defined in it, or other classes I’ve instantiated) without using findViewById, or do I need to define my SurfaceView in the manifest?
Add a constructor to the task. Pass in the view it needs to access in the constructor. Save it to a class variable of the task.
If you need to do a lot of them, pass in the activity, and call findViewById on the activity. Just remember to null out the activity at the end of the onPostExec, to avoid the risk of leaking the activity.