Reputation: 2759
I have an async task which eventually creates the parameters email,about. The async task is in the onCreate method, and so is this CustomListAdapter. I want to move the CustomListAdapter from onCreate in the asyncTask in onPostExecute
.My problem is that this
means the context of the application. When I move it in onPostExecute
it doesn't get that context anymore. I tried to replace it with getApplicationContext()
, activityName.this.getApplicationContext
but it doesn't work because it's expecting the context of the application. I found this Static way to get 'Context' on Android? but I can't define a name in the manifest for some reason. What other method of getting the application's context can I use in the onPostExecute method of the asyncTask? Or should I just make an Asynck task with the context as a parameter ?
CustomListAdapter adapter=new CustomListAdapter(this, email,about);
list=(ListView)findViewById(R.id.list);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
String Slecteditem= email.get(position);
Toast.makeText(getApplicationContext(), Slecteditem, Toast.LENGTH_SHORT).show();
}
});
Upvotes: 0
Views: 20363
Reputation: 2075
You can pass context of your Activity
component in constructor of your CustomAysncTask
like in below code snippet and use it. But always make proper check for null
MyActivity activity
public CustomAsycTask(MyActivity activity) {
this.activity=activity;
}
Update: As Tomer Shemesh
pointed out
private WeakReference<MyActivity> activity = null;
public CustomAsycTask(MyActivity activity) {
activity= new WeakReference<MyActivity>(activity);
}
and for accessing it:
final MyActivity iActivity = activity.get();
Upvotes: 1
Reputation: 13405
If your activities name is MyActivity, you can always just use MyActivity.this to get its context
Upvotes: 7