How to refresh activity after creating dynamic controls in android
In my work, the Oncreate () function im calling AsyncTask . In this PostExecute ( ), create some dynamic gallery items and call ImageAdapterL.notifyDataSetChanged (); ... but Im getting a Null Pointer exception.
I need to update the activity without calling Oncreate () [B'coz in Oncreate just for calling async Task].
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
new testAynscTask().execute();
}
private class testAynscTask extends AsyncTask<Void, Void, Void>{
@Override
protected Void doInBackground(Void... params) {
processTogetImages();
// TODO Auto-generated method stub
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
CreateDynamicGallery();
aImageAdapterL.notifyDataSetChanged();
}
}
public void CreateDynamicGallery(){
CategoryGalleryLayout = (LinearLayout) findViewById(R.id.linearLayout1);
Gallery g = new Gallery(getApplicationContext());
GalleryLayout.addView(g,new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
g.setSpacing(15);
aImageAdapterL = new ImageAdapter(getApplicationContext());
g.setAdapter(aImageAdapterL);
g[positionP].setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(@SuppressWarnings("rawtypes") AdapterView parent, View v, int position, long id) {
Toast.makeText(getBaseContext(), "" + position, Toast.LENGTH_SHORT).show();
}
});
}
}
Thank you in advance
source to share
It seems to me that you are not really refreshing the activity but only the images in the adapter. I would suggest calling createDynamicGallery from onCreate with a null adapter (a well-written adapter view should handle the null adapter, treating it as empty), then load images and populate the real adapter (or new adapter) with images. Installing the gallery view adapter into a real adapter should update the gallery and you should be fine.
As an additional observation, you can look at using asynctaskloader with loadermanager to help you figure it out correctly. With your current code, if the async task is taking a long time to complete, it might be possible to get errors (likely "kill activity" errors) or a race condition with two async tasks trying to load images after screen rotation.
source to share