To maintain the old states, we can overriding the method onRetainNonConfigurationInstance() to return the old activity. Via the returned activity object, we can retrieve the fields of the old activity.
Please notice that the method onRetainNonConfigurationInstance() is deprecated, If you are targeting HONEYCOMB or later, consider instead using a Fragment with Fragment.setRetainInstance(boolean).
Modify the java code in the exercise "GridView loading photos from SD Card", override the method onRetainNonConfigurationInstance() to return the activity object, this. In orCreate() method, check if old activity exist by calling getLastNonConfigurationInstance(). If the returned object not null, means old activity exist.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView gridview = (GridView) findViewById(R.id.gridview);
//Check if old activity exist
MainActivity oldActivity = (MainActivity)getLastNonConfigurationInstance();
if(oldActivity == null){
myImageAdapter = new ImageAdapter(this);
gridview.setAdapter(myImageAdapter);
String ExternalStorageDirectoryPath = Environment
.getExternalStorageDirectory()
.getAbsolutePath();
String targetPath = ExternalStorageDirectoryPath + "/test/";
Toast.makeText(getApplicationContext(), targetPath, Toast.LENGTH_LONG).show();
File targetDirector = new File(targetPath);
File[] files = targetDirector.listFiles();
for (File file : files){
myImageAdapter.add(file.getAbsolutePath());
}
// Get memory class of this device, exceeding this amount will throw an
// OutOfMemory exception.
final int memClass
= ((ActivityManager)getSystemService(Context.ACTIVITY_SERVICE))
.getMemoryClass();
// Use 1/8th of the available memory for this memory cache.
final int cacheSize = 1024 * 1024 * memClass / 8;
mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap bitmap) {
// The cache size will be measured in bytes rather than number of items.
return bitmap.getByteCount();
}
};
}else{
Toast.makeText(getApplicationContext(), "oldActivity exist", Toast.LENGTH_LONG).show();
myImageAdapter = oldActivity.myImageAdapter;
gridview.setAdapter(myImageAdapter);
}
}
@Override
public Object onRetainNonConfigurationInstance() {
// TODO Auto-generated method stub
return this;
}
Download the files.
Hi dear Android-er How can I use this example on android GingerBread 2.3.6? please Help me.....
ReplyDelete