I am using the code below to display the device images in a GridView.
But I am getting an image orientation problem while displaying them in the GridView.
Some images are showing in horizontal orientation mode
public class MultiImagePicActivity extends Activity {
GridView mGrid;
static public String[] arrPath,modifiedArrayPath;
private int ids[];
private int count;
static int selectCount;
Activity act=this;
Context ctx=this;
ArrayList<String> imagepaths;
public static int count1 = 0;
public static String classs;
static int maximageselection;
static int width,height;
//int sel=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
//now get Intent Extras
Bundle extras;
if (savedInstanceState == null)
{
//fetching extra data passed with intents in a Bundle type variable
extras = getIntent().getExtras();
if(extras == null)
{ maximageselection= 0;
classs=null;
}
else
{ /* fetching the string passed with intent using ‘extras’*/
maximageselection= extras.getInt("maximage");
classs=extras.getString("From");
}
}
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
width = size.x;
height = size.y;
imagepaths=new ArrayList<String>();
imagepaths.clear();
loadApps();
setContentView(R.layout.grid_1);
mGrid = (GridView) findViewById(R.id.myGrid);
mGrid.setAdapter(new ImageAdapterxtends());
mGrid.setChoiceMode(GridView.CHOICE_MODE_MULTIPLE_MODAL);
mGrid.setMultiChoiceModeListener(new MultiChoiceModeListener());
}
private void loadApps() {
final String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID };
final String orderBy = MediaStore.Images.Media._ID;
Cursor imagecursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null, null, orderBy);
int image_column_index = imagecursor.getColumnIndex(MediaStore.Images.Media._ID);
this.count = imagecursor.getCount();
this.arrPath = new String[this.count];
ids = new int[count];
for (int i = 0; i <this.count; i++) {
imagecursor.moveToPosition(i);
ids[i] = imagecursor.getInt(image_column_index);
int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
arrPath[i] = imagecursor.getString(dataColumnIndex);
}
imagecursor.close();
}
#Override
public void onBackPressed() {
setResult(Activity.RESULT_CANCELED);
super.onBackPressed();
}
public class ImageAdapterxtends extends BaseAdapter{
CheckableLayout l;
ImageView i;
#Override
public int getCount() {
// TODO Auto-generated method stub
return arrPath.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return arrPath[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if (convertView == null) {
i = new ImageView(MultiImagePicActivity.this);
i.setScaleType(ImageView.ScaleType.FIT_CENTER);
i.setLayoutParams(new ViewGroup.LayoutParams(50, 50));
l = new CheckableLayout(MultiImagePicActivity.this);
l.setLayoutParams(new GridView.LayoutParams(
GridView.LayoutParams.WRAP_CONTENT,
GridView.LayoutParams.WRAP_CONTENT));
l.addView(i);
} else {
l = (CheckableLayout) convertView;
i = (ImageView) l.getChildAt(0);
}
try {
setBitmap(i, ids[position]);
} catch (Throwable e) {
}
return l;
}
}
private void setBitmap(final ImageView iv,final int id) {
new AsyncTask<Void, Void, Bitmap>() {
Bitmap myBitmap;
#Override
protected Bitmap doInBackground(Void... params) {
return MediaStore.Images.Thumbnails.getThumbnail(getApplicationContext().getContentResolver(), id, MediaStore.Images.Thumbnails.MICRO_KIND, null);
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
//iv.setImageBitmap(result);
setMyBitmap(result);
}
public final void setMyBitmap(Bitmap bitmap) {
if (this.myBitmap != null) {
this.myBitmap.recycle();
}
this.myBitmap = bitmap;
iv.getLayoutParams().height = width/3;
iv.getLayoutParams().width = width/3;
iv.setImageBitmap(myBitmap);
}
}.execute();
}
public class CheckableLayout extends FrameLayout implements Checkable {
private boolean mChecked;
public CheckableLayout(Context context) {
super(context);
}
public void setChecked(boolean checked) {
mChecked = checked;
setForeground(checked ? getResources().getDrawable(R.drawable.tr) : null);
}
public boolean isChecked() {
return mChecked;
}
public void toggle() {
setChecked(!mChecked);
}
}
public class MultiChoiceModeListener implements
GridView.MultiChoiceModeListener {
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// Inflate the menu for the CAB
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
//return true;
mode.setTitle("Select Items");
mode.setSubtitle("One item selected");
return true;
}
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return true;
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
// Respond to clicks on the actions in the CAB
switch (item.getItemId()) {
case R.id.menu_ok:
if(classs.equals("SliderExistingDetailedActivity")){
Intent i = new Intent();
modifiedArrayPath=imagepaths.toArray(new String[imagepaths.size()]);
i.putExtra("selectedImagepath", modifiedArrayPath);
//i.putExtra("data", selectedPath);
setResult(Activity.RESULT_OK, i);
finish();
}else{
Intent intent=new Intent(MultiImagePicActivity.this, AudioSelectActivity.class);
intent.putExtra("IMAGEPATHS", imagepaths);
startActivity(intent);
finish();
}
return true;
default:
return false;
}
}
public void onDestroyActionMode(ActionMode mode) {
Toast.makeText(getApplicationContext(), "text", 1);
}
public void onItemCheckedStateChanged(ActionMode mode, int position,
long id, boolean checked) {
selectCount = mGrid.getCheckedItemCount();
if(checked){
imagepaths.add(arrPath[position]);
if(selectCount>maximageselection){
imagepaths.remove(arrPath[position]);
new AlertDialog.Builder(MultiImagePicActivity.this)
.setTitle("Restriction")
.setMessage("You can add at max "+maximageselection+" images !!!")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
mGrid.refreshDrawableState();
dialog.dismiss();
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
}
else{
imagepaths.remove(arrPath[position]);
}
switch (selectCount) {
case 1:
mode.setSubtitle("One item selected");
break;
default:
mode.setSubtitle("" + selectCount + " items selected");
break;
}
}
//}
}
}
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!
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);
}
}
I have the following class to show some images...
I have implemented an ability to download images to the sd card.
If I go through them everything is fine (Image + Title showing) but if I start the download at a certain image, uses another url (of another image) so I somehow think that my ViewPager is not updated correctly or something.
This is my class:
public class ImagePagerActivity extends BaseActivity {
private ViewPager pager;
LinearLayout buttonBar;
TextView txtTitle;
String urlOfImageToDownload;
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private ProgressDialog mProgressDialog;
private static DisplayImageOptions options;
ImageView imageView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ac_image_pager);
Bundle bundle = getIntent().getExtras();
String[] imageUrls = bundle.getStringArray(Extra.IMAGES);
String[] imageTitles = bundle.getStringArray(Extra.TITLES);
int pagerPosition = bundle.getInt(Extra.IMAGE_POSITION, 0);
options = new DisplayImageOptions.Builder()
.cacheOnDisc().showImageForEmptyUri(R.drawable.no_image)
.imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)
.build();
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(new ImagePagerAdapter(imageUrls, imageTitles));
pager.setCurrentItem(pagerPosition);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
if (imageView.getDrawable() == null)
menu.getItem(0).setEnabled(false);
return true;
}
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, 0, 0,
getString(R.string.save_image)).setIcon(android.R.drawable.ic_menu_save);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 0:
Random randomGenerator = new Random();
int randomInt = 0;
for (int idx = 1; idx <= 10; ++idx) {
randomInt = randomGenerator.nextInt(100000);
}
imageView.setDrawingCacheEnabled(true);
Bitmap b = imageView.getDrawingCache();
try {
b.compress(CompressFormat.JPEG, 100,
new
FileOutputStream(Environment.getExternalStorageDirectory()
.getPath() + "/DCIM/image" + randomInt + ".jpg"));
Crouton.makeText(ImagePagerActivity.this,
"Bild erfolgreich gespeichert",
Style.INFO)
.show();
} catch (FileNotFoundException e) {
Crouton.makeText(ImagePagerActivity.this,
"Fehler beim speichern von Datei",
Style.ALERT)
.show();
}
startDownload();
return true;
}
return false;
}
private void startDownload() {
String url = urlOfImageToDownload;
Log.e(MainActivity.LOG_TAG, "url=" + urlOfImageToDownload);
new DownloadFileAsync().execute(url);
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage(getString(R.string.downloading_image));
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
#Override
protected void onStop() {
imageLoader.stop();
super.onStop();
}
private class ImagePagerAdapter extends PagerAdapter {
private String[] images;
private String[] titles;
private LayoutInflater inflater;
ImagePagerAdapter(String[] images, String[] imageTitles) {
this.images = images;
this.titles = imageTitles;
inflater = getLayoutInflater();
}
#Override
public void destroyItem(View container, int position, Object object) {
((ViewPager) container).removeView((View) object);
}
#Override
public void finishUpdate(View container) {
}
#Override
public int getCount() {
return images.length;
}
#Override
public Object instantiateItem(View view, int position) {
final FrameLayout imageLayout = (FrameLayout) inflater.inflate(
R.layout.item_pager_image, null);
imageView = (ImageView) imageLayout
.findViewById(R.id.image);
final ProgressBar spinner = (ProgressBar) imageLayout
.findViewById(R.id.loading);
txtTitle = (TextView) imageLayout.findViewById(R.id.txtTitle);
urlOfImageToDownload = images[position];
buttonBar = (LinearLayout) imageLayout.findViewById(R.id.buttonBar);
txtTitle.setText(titles[position]);
imageLoader.displayImage(images[position], imageView, options,
new ImageLoadingListener() {
#Override
public void onLoadingStarted() {
spinner.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(FailReason failReason) {
switch (failReason) {
case IO_ERROR:
break;
case OUT_OF_MEMORY:
break;
case UNKNOWN:
break;
}
spinner.setVisibility(View.GONE);
imageView.setImageResource(android.R.drawable.ic_delete);
}
#Override
public void onLoadingComplete(Bitmap bm) {
spinner.setVisibility(View.GONE);
}
#Override
public void onLoadingCancelled() {
spinner.setVisibility(View.GONE);
}
});
((ViewPager) view).addView(imageLayout, 0);
return imageLayout;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
#Override
public Parcelable saveState() {
return null;
}
#Override
public void startUpdate(View container) {
}
}
class DownloadFileAsync extends AsyncTask<String, String, String> {
#SuppressWarnings("deprecation")
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Random rand = new Random();
int randomNumber = rand.nextInt(100000);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(
"sdcard/nature_" + randomNumber + ".jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
return null;
}
protected void onProgressUpdate(String... progress) {
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
Crouton.makeText(ImagePagerActivity.this,
getString(R.string.image_saved),
Style.CONFIRM)
.show();
}
}
}
Thanks for any help!
Issue:
The first time the user looks at an image in the ViewPager, instantiateItem(..) for that image will be called and the field urlOfImagetoDownload will be set to the correct URL:
urlOfImageToDownload = images[position];
However if the user now returns to an image he has seen before that is already instantiated, instantiateItem(...) will not be called and urlOfImageToDownload will hold the wrong URL (of the previous image).
Solution:
You can use ViewPager#getCurrentItem() to retrieve the index of the current image, then use that index with images[] to get the right URL when the user clicks to download.