I'm using ViewPager with Action Bar. On the Action Bar there are some component, for example delete button. My application is a gallery app, and I would like to delete the selected pictures. It's works, but I don't know how to refresh my fragment in order to disappear deleted pictures from gridview.
I try to make it for a long time, and It would be very important for me.
Thanks for your help.
MainActivity:
public class MainActivity extends FragmentActivity {
private static final int FOLDER = 0;
private static final int TEXT_ID = 0;
private static final String PATH_OF_FILES = "/Pictures/";
File folder;
ViewPager Tab;
TabPagerAdapter TabAdapter;
ActionBar actionBar;
ArrayList<ImageItem> listOfFiles = new ArrayList<ImageItem>();
private String dirToMove = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listOfFiles = FileListerUtil.getFilesFromDirectory(PATH_OF_FILES);
TabAdapter = new TabPagerAdapter(getSupportFragmentManager());
Tab = (ViewPager) findViewById(R.id.pager);
Tab.setAdapter(TabAdapter);
Tab.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar = getActionBar();
actionBar.setSelectedNavigationItem(position);
}
});
Tab.setAdapter(TabAdapter);
actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.TabListener tabListener = new ActionBar.TabListener() {
#Override
public void onTabReselected(android.app.ActionBar.Tab tab,
FragmentTransaction ft) {
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
Tab.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(android.app.ActionBar.Tab tab,
FragmentTransaction ft) {
}
};
actionBar.addTab(actionBar.newTab().setText("Pic")
.setTabListener(tabListener));
actionBar.addTab(actionBar.newTab().setText("Other")
.setTabListener(tabListener));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.layout.activity_main_action, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_remove:
for (int i = 0; i < listOfFiles.size(); i++) {
if (listOfFiles.get(i).isChecked()) {
File file = new File(listOfFiles.get(i).getImagePath());
file.delete();
}
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public ArrayList<ImageItem> getListOfFiles() {
return listOfFiles;
}
public void setListOfFiles(ArrayList<ImageItem> listOfFiles) {
this.listOfFiles = listOfFiles;
}
public String getDirToMove() {
return dirToMove;
}
public void setDirToMove(String dirToMove) {
this.dirToMove = dirToMove;
}
public static boolean copyFile(String from, String to) {
try {
File sd = Environment.getExternalStorageDirectory();
if (sd.canWrite()) {
int end = from.toString().lastIndexOf("/");
String str1 = from.toString().substring(0, end);
String str2 = from.toString().substring(end+1, from.length());
File source = new File(str1, str2);
File destination= new File(to, str2);
if (source.exists()) {
FileChannel src = new FileInputStream(source).getChannel();
FileChannel dst = new FileOutputStream(destination).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
}
}
return true;
} catch (Exception e) {
return false;
}
}
FragmentStateAdapter:
public class TabPagerAdapter extends FragmentStatePagerAdapter {
public TabPagerAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0:
return new Pictures();
case 1:
return new Albums();
}
return null;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 2; //No of Tabs
}
public int getItemPosition(Object object) {
return POSITION_NONE;
}
Pictures:
public class Pictures extends Fragment{
private LruCache<String, Bitmap> mMemoryCache;
private int count;
private Bitmap[] thumbnails;
private String[] arrPath;
private Context context;
ArrayList<ImageItem> fileListParam = new ArrayList<ImageItem>();
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.layout.fragment_menu, menu);
}
public class ImageAdapter extends BaseAdapter {
boolean[] checkState;
private LayoutInflater inflat;
private Context mContext;
ArrayList<ImageItem> itemList = new ArrayList<ImageItem>();
public ImageAdapter(ArrayList<ImageItem> files, Context c) {
mContext = c;
inflat = (LayoutInflater) getActivity().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
this.itemList = files;
}
void clear() {
itemList.clear();
}
void remove(int index) {
itemList.remove(index);
}
#Override
public int getCount() {
return itemList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return itemList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
View rowView = convertView;
// reuse views
if (rowView == null) {
rowView = inflat.inflate(R.layout.galleryitem, null);
// configure view holder
final ViewHolderPictures viewHolderPictures = new ViewHolderPictures();
viewHolderPictures.imageview = (ImageView) rowView
.findViewById(R.id.thumbImage);
viewHolderPictures.checkbox = (CheckBox) rowView
.findViewById(R.id.itemCheckBox);
viewHolderPictures.imageview.setBackgroundResource(R.drawable.image_border);
viewHolderPictures.imageview.setScaleType(ImageView.ScaleType.FIT_XY);
viewHolderPictures.imageview.setPadding(5, 5, 5, 5);
rowView.setTag(viewHolderPictures);
}
// fill data
ViewHolderPictures holder = (ViewHolderPictures) rowView.getTag();
holder.checkbox
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton arg0,
boolean arg1) {
itemList.get(position).setChecked(arg1);
}
});
final Bitmap bm = getBitmapFromMemCache(itemList.get(position)
.getImagePath());
if (bm == null) {
BitmapWorkerTask task = new BitmapWorkerTask(holder.imageview);
task.execute(itemList.get(position).getImagePath());
}
holder.imageview.setImageBitmap(bm);
holder.checkbox.setChecked(itemList.get(position).isChecked());
return rowView;
}
}
public Bitmap decodeSampledBitmapFromUri(String path, int reqWidth,
int reqHeight) {
Bitmap bm = null;
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
bm = BitmapFactory.decodeFile(path, options);
return bm;
}
public int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float) height / (float) reqHeight);
} else {
inSampleSize = Math.round((float) width / (float) reqWidth);
}
}
return inSampleSize;
}
public class BitmapWorkerTask extends AsyncTask<String, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
public BitmapWorkerTask(ImageView imageView) {
// Use a WeakReference to ensure the ImageView can be garbage
// collected
imageViewReference = new WeakReference<ImageView>(imageView);
}
#Override
protected Bitmap doInBackground(String... params) {
final Bitmap bitmap = decodeSampledBitmapFromUri(params[0], 140,
120);
addBitmapToMemoryCache(String.valueOf(params[0]), bitmap);
return bitmap;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
if (imageViewReference != null && bitmap != null) {
final ImageView imageView = (ImageView) imageViewReference
.get();
if (imageView != null) {
imageView.setImageBitmap(bitmap);
}
}
}
}
int fragVal;
ImageAdapter myImageAdapter;
static Pictures init(int val) {
Pictures truitonFrag = new Pictures();
// Supply val input as an argument.
Bundle args = new Bundle();
args.putInt("val", val);
truitonFrag.setArguments(args);
return truitonFrag;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fragVal = getArguments() != null ? getArguments().getInt("val") : 1;
setHasOptionsMenu(true);
final int memClass = ((ActivityManager) getActivity().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) {
protected int sizeOf(String key, Bitmap bitmap) {
// The cache size will be measured in bytes rather than number
// of items.
return bitmap.getByteCount();
}
};
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Gridview gridview;
View layoutView = inflater.inflate(R.layout.kepgrid, container, false);
gridview = (GridView) layoutView.findViewById(R.id.gv_photolist);
ArrayList<ImageItem> files = ((MainActivity) getActivity())
.getListOfFiles();
context = getActivity();
myImageAdapter = new ImageAdapter(files, context);
gridview.setAdapter(myImageAdapter);
return layoutView;
}
public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
if (getBitmapFromMemCache(key) == null) {
mMemoryCache.put(key, bitmap);
}
}
public Bitmap getBitmapFromMemCache(String key) {
return (Bitmap) mMemoryCache.get(key);
}
}
Related
Background
Hi, I'm relatively new to android programming. I'm still learning.
I have a database with two tables : Item and Type. Item has the following columns : _id, code, type. Type has the following columns : _id, name.
In my activity, I display a spinner of the types, and a gridview of the items. The spinner is supposed to filter the results and update the gridview.
The gridview items only consist in images. The column code gives the name of the image file.
I have a database helper DatabaseHelper, that opens, close, and access the database in different ways.
At the start of my activity ItemList, getContents() is called, getContents() calls the database, and updates listOfIds and listOfCodes according to the value of selectedType (initialised to 0). Then the gridview is created.
For the gridview, I had memory issues while displaying images and scrolling (out of memory). So I followed the Android tutorial : https://developer.android.com/training/displaying-bitmaps/process-bitmap.html Now, each item is displayed asynchronously. And it works fine.
Issue
When I select a type in the spinner, selectedType is updated, getContents() is called and then notifyDataSetChanged() is called. Sometimes it works fine, sometimes it crashes. I think that when I select a type, old threads that have not been terminated are accessing listOfIds and listOfCodes while they are being updated.
How to kill all of thoses threads (before updating list) and prevent the gridview from calling getView during the update?
I was thinking about creating a list containing the threads, update it, and kill all threads before updating the lists. But I can't find the right way to prevent the gridview's adapter from creating views during the update.
Thank you for your help.
Code
Here are parts of my code :
ItemList.java
public class ItemList extends Activity {
private ImageAdapter mAdapter;
private Bitmap mPlaceHolderBitmap;
private DatabaseHelper myHelper;
public static int column = 3;
public static int MARGIN = 5; //margin in dp
public static int width;
public GridView gallery;
public SpinnerAdapter spinnerAdapter;
public Spinner mySpinner;
public int defaultImageID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.item_list);
initialiseValues();
createHelper();
resetPositions();
getContents();
createLists();
createSpinnerListener();
}
#Override
protected void onResume() {
super.onResume();
}
public void createHelper() {
myHelper = new DatabaseHelper(getApplicationContext());
myHelper.getSpinnerIds();
}
public void initialiseValues(){
myHelper.selectedType = 0;
//determines the width of the displayed image
Point size = new Point();
Display display = getWindowManager().getDefaultDisplay();
display.getSize(size);
width = size.x - dpToPx(2*column*MARGIN);
//determines the default image to display
defaultImageID = ...; //here I get the id of the default image;
mPlaceHolderBitmap = decodeSampledBitmapFromResource(getResources(), defaultImageID, null, null), width, width);
}
public void createList() {
spinnerAdapter = new SpinnerAdapter(this, myHelper, myHelper.spinnerNames);
spinnerAdapter.setDropDownViewResource(R.layout.spinner_item);
mySpinner = (Spinner) findViewById(R.id.spinner);
mySpinner.setAdapter(spinnerAdapter);
gallery = (GridView) findViewById(R.id.gallery);
mAdapter = new ImageAdapter(this);
gallery.setAdapter(mAdapter);
}
public void getContents() {
myHelper.getLists();
}
public void createSpinnerListener() {
mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
myHelper.selectedType = myHelper.spinnerIds.get(position);
getContents();
mAdapter.notifyDataSetChanged();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public int dpToPx(int dp) {
DisplayMetrics displayMetrics = this.getResources().getDisplayMetrics();
return Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
}
private class ImageAdapter extends BaseAdapter {
private final Context mContext;
public ImageAdapter(Context context) {
super();
mContext = context;
}
#Override
public int getCount() {
return myHelper.listOfCodes.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup container) {
View view;
if (convertView == null) { // if it's not recycled, initialize some attributes
LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.grid_item, null);
}
else {view = convertView;}
int image_id = getApplicationContext().getResources().getIdentifier(".../" + myHelper.listOfCodes.get(position), null, null);
if (image_id == 0) {image_id = R.drawable.item_unknown;}
loadBitmap(image_id, imageView);
return view;
}
}
public void loadBitmap(int resId, ImageView imageView) {
if (cancelPotentialWork(resId, imageView)) {
final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
final AsyncDrawable asyncDrawable = new AsyncDrawable(getResources(), mPlaceHolderBitmap, task);
imageView.setImageDrawable(asyncDrawable);
task.execute(resId);
}
}
public static boolean cancelPotentialWork(int data, ImageView imageView) {
final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
if (bitmapWorkerTask != null) {
final int bitmapData = bitmapWorkerTask.data;
if (bitmapData != data) {
bitmapWorkerTask.cancel(true); // Cancel previous task
}
else {
return false; // The same work is already in progress
}
}
return true; // No task associated with the ImageView, or an existing task was cancelled
}
private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {
if (imageView != null) {
final Drawable drawable = imageView.getDrawable();
if (drawable instanceof AsyncDrawable) {
final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
return asyncDrawable.getBitmapWorkerTask();
}
}
return null;
}
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) >= reqHeight
&& (halfWidth / inSampleSize) >= reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
static class AsyncDrawable extends BitmapDrawable {
private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
public AsyncDrawable(Resources res, Bitmap bitmap, BitmapWorkerTask bitmapWorkerTask) {
super(res, bitmap);
bitmapWorkerTaskReference = new WeakReference<BitmapWorkerTask>(bitmapWorkerTask);
}
public BitmapWorkerTask getBitmapWorkerTask() {
return bitmapWorkerTaskReference.get();
}
}
class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
private int data = 0;
public BitmapWorkerTask(View view) {
// Use a WeakReference to ensure the ImageView can be garbage collected
imageViewReference = new WeakReference<ImageView>(imageView);
}
// Decode image in background.
#Override
protected Bitmap doInBackground(Integer... params) {
data = params[0];
return decodeSampledBitmapFromResource(getResources(), data, width, width);
}
#Override
protected void onPostExecute(Bitmap bitmap) {
if (isCancelled()) {
bitmap = null;
}
if (imageViewReference != null && bitmap != null) {
final ImageView imageView = imageViewReference.get();
final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
if (this == bitmapWorkerTask && imageView != null) {
imageView.setImageBitmap(bitmap);
}
}
}
}
}
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper{
...
public int currentID = 0;
public int numberOfItems = 0;
public List<Integer> listOfIds = new ArrayList<>();
public List<String> listOfCodes = new ArrayList<>();
public List<Integer> spinnerIds = new ArrayList<>();
public List<String> spinnerNames = new ArrayList<>();
public int selectedType = 0;
private Context context;
public SQLiteDatabase myDataBase;
...
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, 1);
this.context = context;
}
...
public void getSpinnerIds() {
spinnerIds.clear();
spinnerNames.clear();
/*
updates spinnerIds by accessing the db, first one is "All types"
*/
}
public void getLists() {
listOfIds.clear();
listOfCodes.clear();
numberOfItems = 0;
String where = " WHERE code <> '0'";
if (selectedPosition != 0) {where += " AND Type = " + String.valueOf(selectedType);}
openDataBase();
try {
Cursor myCursor = myDataBase.rawQuery("SELECT _id, code, type FROM Item" + where + " ORDER BY _id ASC", null);
myCursor.moveToFirst();
do {
listOfIds.add(myCursor.getInt(0));
listOfCodes.add(myCursor.getString(1));
}
while (myCursor.moveToNext());
myCursor.close();
numberOfItems = listOfIds.size();
}
catch (Exception CursorIndexOutOfBoundsException) {}
myDataBase.close();
}
public String getName(int id) {
String name;
openDataBase();
Cursor myCursor = myDataBase.rawQuery("SELECT name FROM Item WHERE _id = " + String.valueOf(id), null);
myCursor.moveToFirst();
name = myCursor.getString(0);
myCursor.close();
myDataBase.close();
return name;
}
...
}
SpinnerAdapter.java
public class SpinnerAdapter extends ArrayAdapter<String> {
private Context context;
private DatabaseHelper helper;
public SpinnerAdapter(Context context, DatabaseHelper helper, List<String> list) {
super(context, R.layout.spinner_item_small, R.id.text, list);
this.context = context;
this.helper = helper;
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
return getCustomView(position, convertView);
}
#Override
public View getView(int position, View convertView, ViewGroup prnt) {
return getCustomView(position, convertView);
}
public View getCustomView(int position, View convertView) {
View view;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.spinner_item_small, null);
}
else {view = convertView;}
TextView textView = (TextView) view.findViewById(R.id.text);
textView.setText(helper.spinnerNames.get(position));
return view;
}
}
I would like to load all image from gallery to activity with asynctask. I learn it from this link. But there was a problem that I was unable to solve yet.
When I scroll down slowly from the grid view it work perfectly fine. But When I scroll up or scroll faster the Image view either will load previous loaded image then only loaded the correct photo or it might loaded few photo randomly eventually only get to the correct photo.
Here is my source code
public class PhotoPicker extends ActionBarActivity {
ArrayList<String> mArrayList = new ArrayList<String>();
ImageAdapter myImageAdapter;
AsyncTaskLoadFiles myAsyncTaskLoadFiles;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photo_picker);
Context context = getApplicationContext();
final GridView gridview = (GridView) findViewById(R.id.gridview);
myImageAdapter = new ImageAdapter(this);
gridview.setAdapter(myImageAdapter);
myAsyncTaskLoadFiles = new AsyncTaskLoadFiles(myImageAdapter);
myAsyncTaskLoadFiles.execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_photo_picker, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public class AsyncTaskLoadFiles extends AsyncTask<Void, String, Void> {
ImageAdapter myTaskAdapter;
Context context = getApplicationContext();
Cursor cur;
public AsyncTaskLoadFiles(ImageAdapter adapter) {
myTaskAdapter = adapter;
}
#Override
protected void onPreExecute() {
String[] projection = new String[]{
MediaStore.Images.Media.DATA
};
// Get the base URI for the People table in the Contacts content provider.
Uri images = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
// Make the query.
cur = context.getContentResolver().query(images,
projection, // Which columns to return
null, // Which rows to return (all rows)
null, // Selection arguments (none)
MediaStore.MediaColumns.DATE_ADDED + " DESC" // Ordering
);
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
if (cur.moveToFirst()) {
String bucket;
int bucketColumn = cur.getColumnIndex(
MediaStore.Images.Media.DATA);
do {
bucket = cur.getString(bucketColumn);
publishProgress(bucket);
if (isCancelled()) break;
} while (cur.moveToNext());
}
return null;
}
#Override
protected void onProgressUpdate(String... values) {
myTaskAdapter.add(values[0]);
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Void result) {
/*myTaskAdapter.notifyDataSetChanged();*/
super.onPostExecute(result);
}
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
void remove(int index){
mArrayList.remove(index);
}
public void add(String path){
mArrayList.add(path);
}
public int getCount() {
return mArrayList.size();
}
public Object getItem(int position) {
return mArrayList.get(position);
}
public long getItemId(int position) {
return 0;
}
class ViewHolder {
ImageView image;
int position;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
ImageView imageView;
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(230, 230));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(2, 2, 2, 2);
convertView = imageView;
holder = new ViewHolder();
holder.image = imageView;
holder.position = position;
convertView.setTag(holder);
} else {
((ImageView)convertView).setImageBitmap(null);
holder = (ViewHolder) convertView.getTag();
}
new AsyncTask<ViewHolder, Void, Bitmap>() {
private ViewHolder v;
#Override
protected Bitmap doInBackground(ViewHolder... params) {
v = params[0];
Bitmap bm = decodeSampledBitmapFromUri(mArrayList.get(position), 220, 220);
Log.d("holder", String.valueOf(position));
return bm;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
//Not work for me!
v.image.setImageBitmap(result);
}
}.execute(holder);
//imageView.setImageBitmap(bm);
//return imageView;
return convertView;
}
}
public Bitmap decodeSampledBitmapFromUri(String path, int reqWidth,
int reqHeight) {
Bitmap bm = null;
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
bm = BitmapFactory.decodeFile(path, options);
return bm;
}
public int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float) height
/ (float) reqHeight);
} else {
inSampleSize = Math.round((float) width / (float) reqWidth);
}
}
return inSampleSize;
}
}
Apologies if my english make it confuse the link that I provide have 2 youtube video the second video also have the problem that I mention earlier.Any help really very grateful
It is because GridView (ListView, RecyclerView also) is re-using already existing views. When row view moved out of the screen GridView is re-using this view for another data.
In your example, when you call v.image.setImageBitmap(result); it may change image on view that is already used for another data item.
To fix this you should check if view is still related to your data model, e.g.
public View getView(final int position, final View convertView, ViewGroup parent) {
...
holder.image.setTag(position);
new AsyncTask<ViewHolder, Void, Bitmap>() {
...
#Override
protected void onPostExecute(Bitmap result) {
if(v.image.getTag() == position) {
v.image.setImageBitmap(result);
}
}
}
}
There is an error for implementing listview in fragments of custom page adapter.
The error has caused in ones of Samsung, so i did modify my actionbar(change to just header) and tab page adapter as the custom one.
As you can see i didn't implements actionbar.tablistener.
There is an error message :
java.lang.NoClassDefFoundError: zmnx.com.tripdocent.views.SpotListAdapter
at zmnx.com.tripdocent.views.FeaturedListFragment.onCreateView(FeaturedListFragment.java:49)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1786)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:947)
at
This crash, we can see it in just only Samsung phone such as Note2(android 4.4.2) and Galaxy Nexus(android 4.2.1). My condition of build, it is Android Studio 1.0.0, SDK Build tools ver 21.1.2
How can I solve that?
And There are codes :
SpotActivity.class
public class SpotActivity extends FragmentActivity implements OnTabChangeListener, OnPageChangeListener {
public SharedPreferences settings;
ViewPager mViewPager;
private ListView mListView;
public static SpotInfo spotInfo;
public static List<SpotInfo> spotInfoList;
public static List<SpotInfo> nSpotInfoList;
public static List<SpotInfo> fSpotInfoList;
private RelativeLayout backLay;
SpotListAdapter mAdapter;
HandleJSON jsonHandler = null;
CityInfo cInfo = null;
String name = null;
String path = null;
String localName = null;
String type = null;
String hours = null;
String price = null;
String address = null;
String addressDetail = null;
String description = null;
Bitmap bitmapImg = null;
String tabString[] = null;
private TabHost mTabHost = null;
private TabPagerAdapter mPageAdapter = null;
private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spotact_layout);
Intent intent = getIntent();
cInfo = (CityInfo) intent.getSerializableExtra("city");
Data.setCurrentCityInfo(cInfo);
name = cInfo.getCityName();
path = cInfo.getFilePath();
Data.setImgPath(path);
tabString = Constants.TAB_NAMES;
init();
initialiseTabHost();
mPageAdapter = new TabPagerAdapter(this, getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mPageAdapter);
mViewPager.setOnPageChangeListener(SpotActivity.this);
}
private static void AddTab(SpotActivity activity, TabHost tabHost, TabHost.TabSpec tabSpec) {
tabSpec.setContent(new TabFactory(activity));
tabHost.addTab(tabSpec);
}
private void init() {
getPref();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case android.R.id.home:
// ProjectsActivity is my 'home' activity
onBackPressed();
return true;
case R.id.action_account:
Intent i= new Intent(this, Accounts.class);
startActivity(i);
break;
default :
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
Intent intent = new Intent(SpotActivity.this, City.class);
intent.putExtra("city", cInfo);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
private void initialiseTabHost() {
mTabHost = (TabHost) findViewById(android.R.id.tabhost);
mTabHost.setup();
SpotActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec(" ").setIndicator(" "));
SpotActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec(" ").setIndicator(" "));
mTabHost.setOnTabChangedListener(this);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
int pos = this.mViewPager.getCurrentItem();
this.mTabHost.setCurrentTab(pos);
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
#Override
public void onTabChanged(String tabId) {
int pos = this.mTabHost.getCurrentTab();
this.mViewPager.setCurrentItem(pos);
}
}
TabPagerAdapter :
public class TabPagerAdapter extends FragmentPagerAdapter {
private final int NUM_ITEMS = 2;
private Context mContext;
public TabPagerAdapter(Context context, FragmentManager fm) {
super(fm);
this.mContext = context;
}
#Override
public Fragment getItem(int position) {
FeaturedListFragment featured = new FeaturedListFragment();
NearbyListFragment nearbyListFragment = new NearbyListFragment();
if (position == 0) {
return featured;
} else if (position == 1){
return nearbyListFragment;
} else {
throw new IllegalArgumentException("Invalid page position: " + position);
}
}
#Override
public int getCount() {
return NUM_ITEMS;
}
}
FeaturedListFragment :
public class FeaturedListFragment extends ListFragment {
public List<SpotInfo> spotList = null;
public static SpotListAdapter mAdapter = null;
public ListView mListView = null;
public static final String ARG_OBJECT = "object";
public String imgPath = null;
public FeaturedListFragment() {
spotList = Data.getSpotFeaturedInfo();
imgPath = Data.getImgPath();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.spot_list, container, false);
spotList = Data.getSpotFeaturedInfo();
imgPath = Data.getImgPath();
mListView = (ListView) view.findViewById(android.R.id.list);
mAdapter = new SpotListAdapter(getActivity().getBaseContext(),imgPath, spotList);
setListAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
return view;
}
}
SpotListAdapter :
public class SpotListAdapter extends BaseAdapter {
Context context;
LayoutInflater inflater;
int cnt = 0;
private List<SpotInfo> spotList = null;
private ArrayList<SpotInfo> arrayList = null;
private String path = null;
public SpotListAdapter(Context context, String path, List<SpotInfo> spotList) {
this.context = context;
this.spotList = spotList;
this.path = path;
this.arrayList = new ArrayList<SpotInfo>();
this.arrayList.addAll(spotList);
inflater = LayoutInflater.from(context);
}
public class ViewHolder {
TextView spotName;
TextView dist;
TextView address;
ImageView img;
}
#Override
public int getCount() {
return spotList.size();
}
#Override
public Object getItem(int position) {
return spotList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if(convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.spot_row, null);
holder.img = (ImageView) convertView.findViewById(R.id.down_thumb_img);
holder.spotName = (TextView) convertView.findViewById(R.id.down_title_txt);
holder.address = (TextView) convertView.findViewById(R.id.loc_txt);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
FileTotal ft = new FileTotal();
String extStore = System.getenv("EXTERNAL_STORAGE");
String filePath = "/Download/" + path + "-v001/images/";
String imgCode = spotList.get(position).getCode() + ".jpg";
String fileName = extStore + filePath + imgCode ;
File f = new File(fileName);
boolean ex = ft.isFileExist(f);
if(ex) {
Bitmap bmp = decodeSampledBitmapFromFile(fileName, 180, 180);
Canvas canvas = new Canvas();
Bitmap mask = BitmapFactory.decodeResource(context.getResources(), R.drawable.list_thumbframe);
Bitmap tempResult = Bitmap.createScaledBitmap(mask, 180, 180, true);
mask.recycle();
Bitmap result = Bitmap.createBitmap(180, 180, Bitmap.Config.ARGB_8888);
canvas.setBitmap(result);
Paint paint = new Paint();
paint.setFilterBitmap(false);
canvas.drawBitmap(bmp, 0, 0, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
canvas.drawBitmap(tempResult, 0, 0, paint);
paint.setXfermode(null);
holder.img.setImageBitmap(result);
holder.img.invalidate();
}
final String sName = spotList.get(position).getName();
final String descr = spotList.get(position).getDesc();
holder.spotName.setText(sName);
holder.address.setText(descr);
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, SpotDetail.class);
SpotInfo spotInfo = new SpotInfo();
spotInfo = spotList.get(position);
intent.putExtra("spot", spotInfo);
intent.putExtra("path", path);
context.startActivity(intent);
}
});
return convertView;
}
public static Bitmap decodeSampledBitmapFromFile(String path, int reqWidth, int reqHeight)
{ // BEST QUALITY MATCH
//First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize, Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
options.inPreferredConfig = Bitmap.Config.RGB_565;
int inSampleSize = 1;
if (height > reqHeight)
{
inSampleSize = Math.round((float)height / (float)reqHeight);
}
int expectedWidth = width / inSampleSize;
if (expectedWidth > reqWidth)
{
//if(Math.round((float)width / (float)reqWidth) > inSampleSize) // If bigger SampSize..
inSampleSize = Math.round((float)width / (float)reqWidth);
}
options.inSampleSize = inSampleSize;
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
}
I am getting a memory leak from the following code. It is an activity that contains a mainViewPager. That viewPager return 4 different fragments, which each have their own ViewPagers that hold images which are being retrieved from the same asyncTask. Here is my code. When I run it I can scroll throught the Pages with some lag. But when I exit the go back into the activity I get an Out Of Memory Error. So it must be a memory leak. I've stared at my code forever and I can't figure out why. Please help me... PS. I am using the Picasso library to fetch the images from a server.
Activity
package info.nightowl.nightowl;
import info.nightowl.nightowl.LocationsGridFragment.onLocationSelectedListener;
public class NightWatch extends FragmentActivity implements onLocationSelectedListener {
public static ArrayList<String> imageUrl = new ArrayList<String>();
public static ArrayList<String> dateList = new ArrayList<String>();
public static ArrayList<String> trendList = new ArrayList<String>();
public static ArrayList<String> nameList = new ArrayList<String>();
public static ArrayList<String> imageLocationsList = new ArrayList<String>();
public static ArrayList<String> imageClubsList = new ArrayList<String>();
public static ArrayList<String> locationsList = new ArrayList<String>();
public static ArrayList<String> clubsList = new ArrayList<String>();
public static ArrayList<String> locationImagesUrl = new ArrayList<String>();
public static ArrayList<String> addressList = new ArrayList<String>();
public static ArrayList<String> hotImageUrl = new ArrayList<String>();
public static ArrayList<String> hotDateList = new ArrayList<String>();
public static ArrayList<String> hotTrendList = new ArrayList<String>();
public static ArrayList<String> hotNameList = new ArrayList<String>();
public static ArrayList<String> hotImageLocationsList = new ArrayList<String>();
public static ArrayList<String> hotImageClubsList = new ArrayList<String>();
FetchClubs fetchClubs = null;
public int width, height;
public JSONArray list;
public final String IMAGE_URL = "http://www.night-owl.info/webservice/";
SharedPreferences prefs;
static FeedFragment feedFragment;
static LocationsFragment locationsFragment;
static HotFragment hotFragment;
static ClubsFragment clubsFragment;
CustomViewPager customPager;
CustomViewPageAdapter theAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_night_watch);
//Method to set up the tabs
getSizes();
setupFragments();
updateList();
prefs = getSharedPreferences("prefs", 0);
}
//Called from the fragment which fetches image
public void loadBitmap(String image, ImageView imageView, boolean grid, TextView loadText) {
int size;
if (grid) size = (width-width/9)/3;
else size = width - width/9;
Log.d("Pager About to load", "Pager Loading bitmap picasso");
getBitmap load = new getBitmap(image, imageView, size, loadText);
load.execute(image);
}
public class getBitmap extends AsyncTask<String, Void, Bitmap> {
String loadImageUrl;
Bitmap bmp;
int sizes;
TextView loadingTextView;
private final WeakReference<ImageView> imageViewReference;
public getBitmap(String image, ImageView imageView, int size, TextView loadText){
imageViewReference = new WeakReference<ImageView>(imageView);
sizes = size;
loadingTextView = loadText;
}
#Override
protected void onPreExecute() {
Log.d("async", "async starting");
super.onPreExecute();
}
#Override
protected Bitmap doInBackground(String... arg0) {
// TODO Auto-generated method stub
try {
bmp = Picasso.with(NightWatch.this).load(IMAGE_URL+arg0[0]).resize(sizes,
sizes).get();
} catch (IOException e) {
Log.d("ioexc", "Pager IOEXCEPTION IDIOT!!!");
e.printStackTrace();
}
return bmp;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
/*RoundedCornersDrawable drawable = new RoundedCornersDrawable(getResources(), bmp);
loadImage.setImageDrawable(drawable);
loadingTextView.setVisibility(View.GONE);
loadImage.setVisibility(View.VISIBLE);*/
if(imageViewReference != null && bitmap!= null) {
final ImageView imageView = imageViewReference.get();
if(imageView != null) {
imageView.setImageBitmap(bitmap);
loadingTextView.setVisibility(View.GONE);
imageView.setVisibility(View.VISIBLE);
}
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.feed, menu);
return true;
}
//SET UP THE TWO TABS 'FEED' AND 'LOCATIONS'
//Update ArrayList of the image names
public void updateList() {
imageUrl.clear();
trendList.clear();
dateList.clear();
nameList.clear();
imageLocationsList.clear();
imageClubsList.clear();
locationsList.clear();
clubsList.clear();
locationImagesUrl.clear();
addressList.clear();
hotImageUrl.clear();
hotTrendList.clear();
hotDateList.clear();
hotNameList.clear();
hotImageLocationsList.clear();
hotImageClubsList.clear();
new getImageUrl().execute();
new getLocationsUrl().execute();
}
class getImageUrl extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... arg0) {
JSONParser parser = new JSONParser();
JSONObject json = parser.getJSONFromUrl(IMAGE_URL + "updateimages.php");
try {
list = json.getJSONArray("posts");
for(int i = 0; i < list.length(); i++) {
JSONObject c = list.getJSONObject(i);
String imgSrc = c.getString("source");
String trend = c.getString("trend");
String date = c.getString("date");
String name = c.getString("name");
String location = c.getString("location");
String club = c.getString("club");
imageUrl.add(imgSrc);
dateList.add(date);
trendList.add(trend);
nameList.add(name);
imageLocationsList.add(location);
imageClubsList.add(club);
Log.d("async trend", trendList.get(0));
}
Log.d("Got list", imageUrl.get(0) + " " + trendList.get(0));
} catch(JSONException je) {
je.printStackTrace();
}
try {
list = json.getJSONArray("hot");
for(int i = 0; i < list.length(); i++) {
JSONObject c = list.getJSONObject(i);
String imgSrc = c.getString("source");
String trend = c.getString("trend");
String date = c.getString("date");
String name = c.getString("name");
String location = c.getString("location");
String club = c.getString("club");
hotImageUrl.add(imgSrc);
hotDateList.add(date);
hotTrendList.add(trend);
hotNameList.add(name);
hotImageLocationsList.add(location);
hotImageClubsList.add(club);
Log.d("async trend", trendList.get(0));
}
Log.d("Got list","hot list" + hotImageUrl.get(0) + " " + hotTrendList.get(0));
} catch(JSONException je) {
je.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
hotFragment.updateAdapter();
feedFragment.updateAdapter();
}
}
public void scrollMainPager(int pos) {
customPager.setCurrentItem(pos, true);
}
public void scrollPager(int pos) {
feedFragment.scrollPager(pos);
}
public void setupFragments() {
feedFragment = new FeedFragment();
locationsFragment = new LocationsFragment();
hotFragment = new HotFragment();
clubsFragment = new ClubsFragment();
customPager = (CustomViewPager) findViewById(R.id.customviewpager);
customPager.setOffscreenPageLimit(3);
theAdapter = new CustomViewPageAdapter(getSupportFragmentManager());
customPager.setAdapter(theAdapter);
customPager.setCurrentItem(1);
}
//GET SIZES OF SCREEN
public void getSizes(){
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
width = size.x;
height = size.y;
}
public static class CustomViewPageAdapter extends FragmentStatePagerAdapter {
public CustomViewPageAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int arg0) {
if(arg0 == 0) return hotFragment;
else if(arg0 == 1) return feedFragment;
else if(arg0 == 2) return locationsFragment;
else if(arg0 == 3) return clubsFragment;
return null;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 4;
}
}
#Override
public void onLocationSelected(int position) {
}
}
FeedFragment
public class FeedFragment extends Fragment implements OnClickListener {
ToggleButton buttonGrid;
static Spinner spinnerUploadStatus;
CustomEditText et;
CustomScrollTextView tv;
int width, height;
View view;
static boolean isGrid;
ViewPager mPager;
SharedPreferences prefs;
public ImagePagerAdapter mPageAdapter;
Button buttonSwitchFragment;
Integer[] b = { R.drawable.statusunpressed, R.drawable.red,
R.drawable.green, R.drawable.blue };
List<Integer> spinnerList = new ArrayList<Integer>(Arrays.asList(b));
CustomSpinnerAdapter myAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
prefs = getActivity().getSharedPreferences("prefs", 0);
getSizes();
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.activity_feed, container, false);
setup();
return view;
}
#SuppressLint("NewApi")
public void setup() {
isGrid = false;
mPager = (ViewPager) view.findViewById(R.id.myviewpager1);
mPager.setOffscreenPageLimit(0);
buttonGrid = (ToggleButton) view.findViewById(R.id.button_grid);
buttonGrid.setOnClickListener(this);
spinnerUploadStatus = (Spinner) view
.findViewById(R.id.buttonUploadStatus);
myAdapter = new CustomSpinnerAdapter(getActivity(),
R.layout.item_simple_list_item, spinnerList);
myAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerUploadStatus.setAdapter(myAdapter);
spinnerUploadStatus.setDropDownWidth((int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, 50, getResources()
.getDisplayMetrics()));
spinnerUploadStatus.setOnItemSelectedListener(myOnItemSelectedListener);
spinnerUploadStatus.getBackground().setAlpha(0);
buttonSwitchFragment = (Button) view
.findViewById(R.id.buttonSwitchFragment);
buttonSwitchFragment.setOnClickListener(this);
Typeface font = Typeface.createFromAsset(getActivity().getAssets(),
"NotCourierSans.ttf");
et = (CustomEditText) view.findViewById(R.id.customEditText1);
et.updateTypeFace(font);
tv = (CustomScrollTextView) view
.findViewById(R.id.customscrolltextview);
tv.setText("WELCOME TO NIGHTOWL");
tv.setTypeface(font);
tv.start(width / 2500.0);
Log.d("width", "width is " + width);
}
public void getSizes() {
Display display = getActivity().getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
width = size.x;
height = size.y;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_grid:
isGrid = !isGrid;
updateAdapter();
break;
case R.id.buttonSwitchFragment:
((NightWatch) getActivity()).scrollMainPager(2);
break;
}
}
public OnItemSelectedListener myOnItemSelectedListener = new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
int colour = arg2;
spinnerUploadStatus.setSelection(0, true);
et.sendText(prefs.getString("username", "username invalid"), colour);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
};
public void scrollPager(int position) {
isGrid = false;
buttonGrid.setChecked(false);
updateAdapter();
mPager.setCurrentItem(position, true);
Log.d("Pager", "PAGER UPDATED");
}
public static void disableButton(Boolean enabled) {
spinnerUploadStatus.setEnabled(enabled);
}
public void updateAdapter() {
int theSize;
if (!isGrid)
theSize = NightWatch.imageUrl.size();
else if (NightWatch.imageUrl.size() % 9 > 0)
theSize = NightWatch.imageUrl.size() / 9 + 1;
else
theSize = NightWatch.imageUrl.size() / 9;
mPageAdapter = new ImagePagerAdapter(getChildFragmentManager(), theSize);
mPager.setAdapter(mPageAdapter);
Log.d("size of viewPager Adapter", "" + theSize);
}
public static class ImagePagerAdapter extends FragmentStatePagerAdapter {
int mSize;
public ImagePagerAdapter(FragmentManager fm, int size) {
super(fm);
mSize = size;
}
#Override
public Fragment getItem(int arg0) {
// TODO Auto-generated method stub
Log.d("Starting imageDetailFragment", "");
Log.d("Pager", "Pager starting fragment");
Log.d("GRID", "fuck grid");
if (!isGrid)
return ImageDetailFragment.newInstance(
arg0, NightWatch.imageUrl, NightWatch.nameList,
NightWatch.trendList, NightWatch.dateList);
else
return GridFragment.newInstance(arg0, NightWatch.imageUrl);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mSize;
}
}
public class CustomSpinnerAdapter extends ArrayAdapter<Integer> {
List<Integer> resourceId;
Context c;
public CustomSpinnerAdapter(Context context, int textViewResourceId,
List<Integer> objects) {
super(context, textViewResourceId, objects);
resourceId = objects;
c = context;
}
#Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
return getCustomDropdownView(position, convertView, parent);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
public View getCustomView(int position, View convertView,
ViewGroup parent) {
ImageView imageView = new ImageView(c);
imageView.setImageResource(resourceId.get(position));
imageView.setLayoutParams(new ListView.LayoutParams(
(int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, 50, getResources()
.getDisplayMetrics()), (int) TypedValue
.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 34,
getResources().getDisplayMetrics())));
return imageView;
}
public View getCustomDropdownView(int position, View convertView,
ViewGroup parent) {
ImageView imageView = new ImageView(c);
imageView.setImageResource(resourceId.get(position));
imageView.setLayoutParams(new ListView.LayoutParams(
(int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, 50, getResources()
.getDisplayMetrics()), (int) TypedValue
.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 34,
getResources().getDisplayMetrics())));
if (position == 0) {
imageView.setVisibility(View.GONE);
}
return imageView;
}
}
}
ImageDetailFragment
package info.nightowl.nightowl;
import java.io.IOException;
import java.util.ArrayList;
import com.example.nightowl.R;
import com.squareup.picasso.Picasso;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class ImageDetailFragment extends Fragment implements OnClickListener {
int mImageNum;
ImageView imageView;
TextView trendTextView;
TextView nameTextView;
TextView dateTextView;
TextView loadingTextView;
Button upVoteButton, downVoteButton;
final String list = "voteList";
static SharedPreferences prefs;
SharedPreferences.Editor editor;
public ArrayList<String> imageUrl;
public ArrayList<String> trendList;
public ArrayList<String> nameList;
public ArrayList<String> dateList;
RelativeLayout.LayoutParams rParams;
int width, height;
static ImageDetailFragment newInstance(int imageNum,
ArrayList<String> imageList, ArrayList<String> tempNameList,
ArrayList<String> tempTrendList, ArrayList<String> tempDateList) {
final ImageDetailFragment f = new ImageDetailFragment();
Bundle args = new Bundle();
args.putInt("imageNum", imageNum);
args.putStringArrayList("imageList", imageList);
args.putStringArrayList("nameList", tempNameList);
args.putStringArrayList("trendList", tempTrendList);
args.putStringArrayList("dateList", tempDateList);
f.setArguments(args);
return f;
}
public ImageDetailFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mImageNum = getArguments().getInt("imageNum");
imageUrl = getArguments().getStringArrayList("imageList");
nameList = getArguments().getStringArrayList("nameList");
trendList = getArguments().getStringArrayList("trendList");
dateList = getArguments().getStringArrayList("dateList");
} else
mImageNum = -1;
prefs = getActivity().getSharedPreferences("prefs", 0);
editor = getActivity().getSharedPreferences("prefs", 0).edit();
getSizes();
rParams = new RelativeLayout.LayoutParams((width - width/9), width - width/9);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.image_detail_fragment,
container, false);
imageView = (ImageView) v.findViewById(R.id.imageView1);
imageView.setVisibility(View.INVISIBLE);
loadingTextView = (TextView) v.findViewById(R.id.loadingTextView);
loadingTextView.setVisibility(View.VISIBLE);
trendTextView = (TextView) v.findViewById(R.id.trendTextView);
nameTextView = (TextView) v.findViewById(R.id.nameTextView);
dateTextView = (TextView) v.findViewById(R.id.dateTextView);
upVoteButton = (Button) v.findViewById(R.id.buttonUpVote);
downVoteButton = (Button) v.findViewById(R.id.buttonDownVote);
rParams.addRule(RelativeLayout.BELOW, nameTextView.getId());
rParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
imageView.setLayoutParams(rParams);
upVoteButton.setOnClickListener(this);
downVoteButton.setOnClickListener(this);
if (NightWatch.class.isInstance(getActivity())) {
Typeface font = Typeface.createFromAsset(getActivity().getAssets(),
"NotCourierSans.ttf");
final String image = imageUrl.get(mImageNum);
((NightWatch) getActivity()).loadBitmap(image, imageView, false, loadingTextView);
trendTextView.setText(trendList.get(mImageNum));
nameTextView.setText(nameList.get(mImageNum));
dateTextView.setText(dateList.get(mImageNum));
updateButtonBackgrounds();
loadingTextView.setTypeface(font);
trendTextView.setTypeface(font);
nameTextView.setTypeface(font);
dateTextView.setTypeface(font);
Log.d("fragment trend", NightWatch.trendList.get(0));
}
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonUpVote:
if (prefs.getInt(imageUrl.get(mImageNum), 0) == -1) {
downVoteButton
.setBackgroundResource(R.drawable.downvoteunpressed);
upVoteButton.setBackgroundResource(R.drawable.upvotepressed);
((NightWatch) getActivity()).sendVote(1,
imageUrl.get(mImageNum));
} else if (prefs.getInt(imageUrl.get(mImageNum), 0) == 0) {
upVoteButton.setBackgroundResource(R.drawable.upvotepressed);
((NightWatch) getActivity()).sendVote(1,
imageUrl.get(mImageNum));
}
break;
case R.id.buttonDownVote:
if (prefs.getInt(imageUrl.get(mImageNum), 0) == 1) {
downVoteButton
.setBackgroundResource(R.drawable.downvotepressed);
upVoteButton.setBackgroundResource(R.drawable.upvoteunpressed);
((NightWatch) getActivity()).sendVote(-1,
imageUrl.get(mImageNum));
} else if (prefs.getInt(imageUrl.get(mImageNum), 0) == 0) {
downVoteButton
.setBackgroundResource(R.drawable.downvotepressed);
((NightWatch) getActivity()).sendVote(-1,
imageUrl.get(mImageNum));
}
break;
}
};
public void updateButtonBackgrounds() {
if (prefs.getInt(imageUrl.get(mImageNum), 0) == -1) {
downVoteButton.setBackgroundResource(R.drawable.downvotepressed);
} else if (prefs.getInt(imageUrl.get(mImageNum), 0) == 1) {
upVoteButton.setBackgroundResource(R.drawable.upvotepressed);
}
}
public static void sendVote(int vote, String imageName) {
prefs.edit().putInt(imageName, vote).commit();
}
public void getSizes() {
Display display = getActivity().getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
width = size.x;
height = size.y;
}
}
HotFragment
package info.nightowl.nightowl;
public class HotFragment extends Fragment implements OnClickListener {
ToggleButton buttonGrid;
static Spinner spinnerUploadStatus;
CustomEditText et;
CustomScrollTextView tv;
int width, height;
View view;
static boolean isGrid;
ViewPager mPager;
SharedPreferences prefs;
public ImagePagerAdapter mPageAdapter;
Button buttonSwitchFragment;
Integer[] b = { R.drawable.statusunpressed, R.drawable.red,
R.drawable.green, R.drawable.blue };
List<Integer> spinnerList = new ArrayList<Integer>(Arrays.asList(b));
CustomSpinnerAdapter myAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
prefs = getActivity().getSharedPreferences("prefs", 0);
getSizes();
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.activity_feed, container, false);
setup();
return view;
}
#SuppressLint("NewApi")
public void setup() {
isGrid = false;
mPager = (ViewPager) view.findViewById(R.id.myviewpager1);
mPager.setOffscreenPageLimit(0);
buttonGrid = (ToggleButton) view.findViewById(R.id.button_grid);
buttonGrid.setOnClickListener(this);
spinnerUploadStatus = (Spinner) view
.findViewById(R.id.buttonUploadStatus);
myAdapter = new CustomSpinnerAdapter(getActivity(),
R.layout.item_simple_list_item, spinnerList);
myAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerUploadStatus.setAdapter(myAdapter);
spinnerUploadStatus.setDropDownWidth((int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, 50, getResources()
.getDisplayMetrics()));
spinnerUploadStatus.setOnItemSelectedListener(myOnItemSelectedListener);
spinnerUploadStatus.getBackground().setAlpha(0);
buttonSwitchFragment = (Button) view
.findViewById(R.id.buttonSwitchFragment);
buttonSwitchFragment.setOnClickListener(this);
Typeface font = Typeface.createFromAsset(getActivity().getAssets(),
"NotCourierSans.ttf");
et = (CustomEditText) view.findViewById(R.id.customEditText1);
et.updateTypeFace(font);
tv = (CustomScrollTextView) view
.findViewById(R.id.customscrolltextview);
tv.setText("WELCOME TO NIGHTOWL");
tv.setTypeface(font);
tv.start(width / 2500.0);
Log.d("width", "width is " + width);
}
public void getSizes() {
Display display = getActivity().getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
width = size.x;
height = size.y;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_grid:
isGrid = !isGrid;
updateAdapter();
break;
case R.id.buttonSwitchFragment:
((NightWatch) getActivity()).scrollMainPager(1);
break;
}
}
public OnItemSelectedListener myOnItemSelectedListener = new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
spinnerUploadStatus.setSelection(0, true);
et.sendText(prefs.getString("username", "username invalid"), arg2);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
};
public void scrollPager(int position) {
isGrid = false;
buttonGrid.setChecked(false);
updateAdapter();
mPager.setCurrentItem(position, true);
Log.d("Pager", "PAGER UPDATED");
}
public static void disableButton(Boolean enabled) {
spinnerUploadStatus.setEnabled(enabled);
}
public void updateAdapter() {
int theSize;
if (!isGrid)
theSize = NightWatch.imageUrl.size();
else if (NightWatch.imageUrl.size() % 9 > 0)
theSize = NightWatch.imageUrl.size() / 9 + 1;
else
theSize = NightWatch.imageUrl.size() / 9;
mPageAdapter = new ImagePagerAdapter(getChildFragmentManager(), theSize);
mPager.setAdapter(mPageAdapter);
Log.d("size of viewPager Adapter", "" + theSize);
}
public static class ImagePagerAdapter extends FragmentStatePagerAdapter {
int mSize;
public ImagePagerAdapter(FragmentManager fm, int size) {
super(fm);
mSize = size;
}
#Override
public Fragment getItem(int arg0) {
// TODO Auto-generated method stub
Log.d("Starting imageDetailFragment", "");
Log.d("Pager", "Pager starting fragment");
Log.d("GRID", "fuck grid");
if (!isGrid)
return ImageDetailFragment.newInstance(arg0,
NightWatch.hotImageUrl, NightWatch.hotNameList,
NightWatch.hotTrendList, NightWatch.hotDateList);
else
return GridFragment.newInstance(arg0, NightWatch.imageUrl);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mSize;
}
}
public class CustomSpinnerAdapter extends ArrayAdapter<Integer> {
List<Integer> resourceId;
Context c;
public CustomSpinnerAdapter(Context context, int textViewResourceId,
List<Integer> objects) {
super(context, textViewResourceId, objects);
resourceId = objects;
c = context;
}
#Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
return getCustomDropdownView(position, convertView, parent);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
public View getCustomView(int position, View convertView,
ViewGroup parent) {
ImageView imageView = new ImageView(c);
imageView.setImageResource(resourceId.get(position));
imageView.setLayoutParams(new ListView.LayoutParams(
(int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, 50, getResources()
.getDisplayMetrics()), (int) TypedValue
.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 34,
getResources().getDisplayMetrics())));
return imageView;
}
public View getCustomDropdownView(int position, View convertView,
ViewGroup parent) {
ImageView imageView = new ImageView(c);
imageView.setImageResource(resourceId.get(position));
imageView.setLayoutParams(new ListView.LayoutParams(
(int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, 50, getResources()
.getDisplayMetrics()), (int) TypedValue
.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 34,
getResources().getDisplayMetrics())));
if (position == 0) {
imageView.setVisibility(View.GONE);
}
return imageView;
}
}
}
I dont see a point in posting the rest of the fragments. The memory leak is somewhere here I'm sure
I would really appreciate it if someone helped me with this.
Loading a Bitmap from a URL in such manner will cause IOException. With Picasso, you don't even need asynctask. Simply call this in UI Thread:
Picasso.with(getActivity())
.load(url)
.into(imageView); //you can add .resize() before .into()
OR if you really want to have the Bitmap, you use this code:
new AsyncTask<Void, Void, Void>() {
Bitmap bitmap;
#Override
protected void onPreExecute() {
//some code
}
#Override
protected Void doInBackground(Void... arg0) {
bitmap = getBitmapFromURL(url);
return null;
}
#Override
protected void onPostExecute(Void result) {
imageView.setImageBitmap(bitmap);
}
}.execute();
And getBitmapFromURL():
public Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
return BitmapFactory.decodeStream(input);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
Ok so I would recommend you stick with using Picasso as this will make your life a lot easier in terms of memory management and the likes. One thing to remember is that the image contained in an imageview can ultimately retrieved as a Bitmap regardless of the image type (eg jpeg, png etc), so if you use Picasso to load the image via a URL you can still retrieve the image as a Bitmap after it is loaded and apply your transformation on it. Picasso also have a function called .transform() which you can use to transform your images by supplying a custom transformation. Here is an example for a rounded transformation, first the code that implements the transformation:
//calcualte the raduis for the rounded images
final float scale = mContext.getResources().getDisplayMetrics().density; //get screen density for scale
int pixels = (int) ((imageView.getWidth()-5) * scale); //get screen pixels based on density. Imageview is 60dp x 60dp in size, subtract some padding = 55
mRadiusCenter = pixels / 2; //get the raduis
//now load your image
Picasso.with(mContext)
.load(imageUrl)
.fit().centerCrop()
.transform(new RoundedTransformation(mRadiusCenter))
.into(imageView);
The you need to create a class for the RoundedTransformation that implements Picasso Transformation:
// enables hardware accelerated rounded corners
// original idea here : http://www.curious-creature.org/2012/12/11/android-recipe-1-image-with-rounded-corners/
public class RoundedTransformation implements com.squareup.picasso.Transformation {
private final int radius;
// radius is corner radii in dp
public RoundedTransformation(final int radius) {
this.radius = radius;
}
#Override
public Bitmap transform(final Bitmap source) {
final Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setShader(new BitmapShader(source, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
Bitmap output = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
canvas.drawCircle(radius, radius, radius, paint);
if (source != output) {
source.recycle();
}
return output;
}
#Override
public String key() {
return "rounded";
}
}
Here are some more links that might prove useful:
https://gist.github.com/julianshen/5829333
Load large images with Picasso and custom Transform object
Hope that helps!
Finally, i change my code and use univeral-image-loader library
I use paperadapter to display url image like the code ,it works fine.
#Override
public Object instantiateItem(final ViewGroup container, final int position) {
Drawable[] imageDrawable = new Drawable[3];
for (int i = 0; i < 3; i++) {
imageDrawable[i] = LoadImageFromWebOperations(server_url+ image_name.replace(" ","")+ "_0" +String.valueOf(i + 1) + ".jpg");
}
imageView = new ImageView(mContext);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setImageDrawable(imageDrawable[position]);
container.addView(imageView, 0);
return imageView;
}
but i want to use asynctask to do this,like the code
#Override
public Object instantiateItem(final ViewGroup container, final int position) {
AsyncTask<String, Void, Drawable[]> loadingImage = new AsyncTask<String, Void, Drawable[]>(){
#Override
protected Drawable[] doInBackground(String... params) {
// TODO Auto-generated method stub
Drawable imageDrawable[] = new Drawable[3];
for (int i = 0; i < 3; i++) {
imageDrawable[i] = LoadImageFromWebOperations(server_url
+ image_name.replace(" ","")+ "_0" + String.valueOf(i + 1) + ".jpg");
System.out.println("doInBackground="+position);
}
return imageDrawable;
}
#Override
protected void onPostExecute(Drawable[] result) {
System.out.println("onPostExecute="+position);
imageView = new ImageView(getBaseContext());
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setImageDrawable(result[position]);
container.addView(imageView, 0);
}
});
}
}; loadingImage.execute();
return imageView;
}
it do not work fine.i found that the position "1" is null without image,but position 0 and 2 is not null,waiting for some suggestion,thanks!
this is the all code :
public class ProductDetailActivity1 extends FragmentActivity {
ImageAdapter mAdapter;
ViewPager mPager;
CirclePageIndicator mIndicator;
private String server_url;
ImageView imageView;
protected ScrollView mScrollView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_detail1);
mScrollView = (ScrollView)findViewById(R.id.card_scrollview);
getActionBar();
getActionBar().setHomeButtonEnabled(true);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setDisplayShowTitleEnabled(true);
getActionBar().setTitle(R.string.product_detail);
Intent intent = getIntent();
server_url = intent.getStringExtra("SERVER_URL");
mAdapter = new ImageAdapter(getApplicationContext());
mPager = (ViewPager) findViewById(R.id.imageViewpager);
mPager.setAdapter(mAdapter);
mIndicator = (CirclePageIndicator) findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
mIndicator.setFillColor(0xFFFFFFFF);
mIndicator.setStrokeColor(0xFFFFFFFF);
mIndicator.setStrokeWidth(1);
mIndicator.setRadius(6 * getResources().getDisplayMetrics().density);
((CirclePageIndicator) mIndicator).setSnap(true);
mIndicator
.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrolled(int position,
float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Intent intent = new Intent(ProductDetailActivity1.this,
com.wangrui.ams.MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.product_detail, menu);
return true;
}
public class ImageAdapter extends PagerAdapter {
private Context mContext;
private Drawable[] imageDrawable = new Drawable[3];;
public ImageAdapter(Context cx) {
mContext = cx.getApplicationContext();
}
#Override
public Object instantiateItem(final ViewGroup container, final int position) {
AsyncTask<Void, Void, Drawable[]> loadingImage = new AsyncTask<Void, Void, Drawable[]>(){
#Override
protected Drawable[] doInBackground(Void... params) {
// TODO Auto-generated method stub
for (int i = 0; i < 3; i++) {
imageDrawable[i] = LoadImageFromWebOperations(server_url
+ image_name.replace(" ","")+ "_0" + String.valueOf(i + 1) + ".jpg");
System.out.println("position="+i);
}
return imageDrawable;
}
#Override
protected void onPostExecute(Drawable[] result) {
imageView = new ImageView(mContext);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setImageDrawable(result[position]);
mPager.getAdapter().notifyDataSetChanged();
((ViewPager) container).addView(imageView, position);
}
}; loadingImage.execute();
return imageView;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 3;
}
#Override
public boolean isViewFromObject(final View view, final Object object) {
// TODO Auto-generated method stub
//return arg0 == (View) arg1;
return view == ((ImageView) object);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((ImageView) object);
}
}
private void showAlertMessage(String msg){
SuperToast superToast = new SuperToast(getApplicationContext());
superToast.setAnimations(SuperToast.Animations.FLYIN);
superToast.setDuration(SuperToast.Duration.LONG);
superToast.setBackground(SuperToast.Background.RED);
superToast.setTextSize(SuperToast.TextSize.EXTRA_SMALL);
superToast.setText(msg);
superToast.show();
}
private Drawable LoadImageFromWebOperations(String url) {
try {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
} catch (Exception e) {
System.out.println("Exc=" + e);
return null;
}
}
}