ViewPager uses the wrong entry - android

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.

Related

Handlle image orientation in GridView android

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;
}
}
//}
}
}

How do i get the position of a URL in an array?

What I'm trying to achieve is to obtain the URL received from Instagram and pass its array position to an onlick listener for each corresponding photo in a grid view.
Here is my code:
MainActivity.java
public class MainActivity extends Activity {
private InstagramSession mInstagramSession;
private Instagram mInstagram;
private ProgressBar mLoadingPb;
private GridView mGridView;
private static final String CLIENT_ID = "83549f9eb76f4a5b90daf6e4e14da107";
private static final String CLIENT_SECRET = "6df26b0c8f664323a07126bfe8511651";
private static final String REDIRECT_URI = "http://www.yahoo.com";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mInstagram = new Instagram(this, CLIENT_ID, CLIENT_SECRET, REDIRECT_URI);
mInstagramSession = mInstagram.getSession();
if (mInstagramSession.isActive()) {
setContentView(R.layout.activity_user);
InstagramUser instagramUser = mInstagramSession.getUser();
mLoadingPb = (ProgressBar) findViewById(R.id.pb_loading);
mGridView = (GridView) findViewById(R.id.gridView);
((TextView) findViewById(R.id.tv_name)).setText(instagramUser.fullName);
((TextView) findViewById(R.id.tv_username)).setText(instagramUser.username);
((Button) findViewById(R.id.btn_logout)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
mInstagramSession.reset();
startActivity(new Intent(MainActivity.this, MainActivity.class));
finish();
}
});
ImageView userIv = (ImageView) findViewById(R.id.iv_user);
DisplayImageOptions displayOptions = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_user)
.showImageForEmptyUri(R.drawable.ic_user)
.showImageOnFail(R.drawable.ic_user)
.cacheInMemory(true)
.cacheOnDisc(false)
.considerExifParams(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)
.writeDebugLogs()
.defaultDisplayImageOptions(displayOptions)
.build();
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
AnimateFirstDisplayListener animate = new AnimateFirstDisplayListener();
imageLoader.displayImage(instagramUser.profilPicture, userIv, animate);
new DownloadTask().execute();
} else {
setContentView(R.layout.activity_main);
((Button) findViewById(R.id.btn_connect)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
mInstagram.authorize(mAuthListener);
}
});
}
}
private void showToast(String text) {
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
}
private Instagram.InstagramAuthListener mAuthListener = new Instagram.InstagramAuthListener() {
#Override
public void onSuccess(InstagramUser user) {
finish();
startActivity(new Intent(MainActivity.this, MainActivity.class));
}
#Override
public void onError(String error) {
showToast(error);
}
#Override
public void onCancel() {
showToast("OK. Maybe later?");
}
};
public static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 500);
displayedImages.add(imageUri);
}
}
}
}
ArrayList<String> photoList;
public class DownloadTask extends AsyncTask<URL, Integer, Long> {
protected void onCancelled() {
}
protected void onPreExecute() {
}
protected Long doInBackground(URL... urls) {
long result = 0;
try {
List<NameValuePair> params = new ArrayList<NameValuePair>(1);
params.add(new BasicNameValuePair("count", "20"));
InstagramRequest request = new InstagramRequest(mInstagramSession.getAccessToken());
String response = request.createRequest("GET", "/users/21846697/media/recent", params);
if (!response.equals("")) {
JSONObject jsonObj = (JSONObject) new JSONTokener(response).nextValue();
JSONArray jsonData = jsonObj.getJSONArray("data");
int length = jsonData.length();
if (length > 0) {
photoList = new ArrayList<String>();
for (int i = 0; i < length; i++) {
JSONObject jsonPhoto = jsonData.getJSONObject(i).getJSONObject("images").getJSONObject("standard_resolution");
photoList.add(jsonPhoto.getString("url"));
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(Long result) {
mLoadingPb.setVisibility(View.GONE);
if (photoList == null) {
Toast.makeText(getApplicationContext(), "No Photos Available", Toast.LENGTH_LONG).show();
} else {
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = (int) Math.ceil((double) dm.widthPixels / 2);
width=width-50;
int height = width;
PhotoListAdapter adapter = new PhotoListAdapter(MainActivity.this);
adapter.setData(photoList);
adapter.setLayoutParam(width, height);
mGridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Maybe you'll have to cast it to a string, I'm currently writing directly in SO
String url = (String) parent.getAdapter().getItem(position);
Intent myintent=new Intent(MainActivity.this, FullscreenImageView.class).putExtra("SelectedImageURL", position);
startActivity(myintent);
}
});
mGridView.setAdapter(adapter);
}
}
}
}
PhotoListAdapter.java
public class PhotoListAdapter extends BaseAdapter {
private Context mContext;
private ImageLoader mImageLoader;
private AnimateFirstDisplayListener mAnimator;
private ArrayList<String> mPhotoList;
private int mWidth;
private int mHeight;
public PhotoListAdapter(Context context) {
mContext = context;
DisplayImageOptions displayOptions = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.instagram_logo)
.showImageForEmptyUri(R.drawable.instagram_logo)
.showImageOnFail(R.drawable.instagram_logo)
.cacheInMemory(true)
.cacheOnDisc(false)
.considerExifParams(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
.writeDebugLogs()
.defaultDisplayImageOptions(displayOptions)
.build();
mImageLoader = ImageLoader.getInstance();
mImageLoader.init(config);
mAnimator = new AnimateFirstDisplayListener();
}
public void setData(ArrayList<String> data) {
mPhotoList = data;
}
public void setLayoutParam(int width, int height) {
mWidth = width;
mHeight = height;
}
#Override
public int getCount() {
return (mPhotoList == null) ? 0 : mPhotoList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageIv;
if (convertView == null) {
imageIv = new ImageView(mContext);
imageIv.setLayoutParams(new GridView.LayoutParams(mWidth, mHeight));
imageIv.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageIv.setPadding(0, 0, 0, 0);
} else {
imageIv = (ImageView) convertView;
}
mImageLoader.displayImage(mPhotoList.get(position), imageIv, mAnimator);
return imageIv;
}
}
FullScreenImageView.java
import android.app.Activity;
public class FullscreenImageView extends Activity {
String imageURL = getIntent().getStringExtra("SelectedImageURL");
}
The workflow of the gridView as you understood is to have an adapter to populate this view.
What I would do is that the getItem(int position) returns the URL which, if I good understood, is contained in your mPhotoList. Something like:
#Override
public Object getItem(int position) {
return mPhotoList.get(position);
}
And use it where you need it like this:
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Maybe you'll have to cast it to a string, I'm currently writing directly in SO
String url = parent.getAdapter().getItem(position)
Intent myintent=new Intent(MainActivity.this, FullscreenImageView.class).putExtra("SelectedImageURL", url);
startActivity(myintent);
}
});
Hope it helps.

How to use AsyncTask to display URL image in PaperAdapter

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;
}
}
}

Set As Wallpaper From ButtonClick Using ViewPager Adapter in Android?

i want set wallpaper which is currenton viewpager imageview on buttonclick but button is not in view pager so how to set the wall paper from viewpager adapter and button is not in the imageview
onclick where i want to set as wall paper
imagebutton.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// coding for wall set as wallpaper
int b=pager.getCurrentItem();
WallpaperManager myWallpaperManager=WallpaperManager. getInstance(getApplicationContext());
myWallpaperManager.setResource(id);
}
});
CopyOfClickedImagesActivity .java
public class CopyOfClickedImagesActivity extends BaseActivity
{
ArrayList<HashMap<String,String>> mylist = new ArrayList<HashMap<String,String>>();
public static final String TAG_STATUS="status";
public static final String TAG_DATA="data";
public static final String TAG_ID="id";
public static final String TAG_CATEGORYNAME="category_name";
public static final String TAG_IMAGENAME="image_name";
public static final String TAG_SETID="set_id";
DisplayImageOptions options;
ViewPager pager;
ImageView imagebutton;
ImagePagerAdapter pagerAdapter;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_clickedimage);
pager=(ViewPager)findViewById(R.id.myviewpager);
imagebutton=(ImageView)findViewById(R.id.imagebutton);
BaseActivity.imageLoader.init(ImageLoaderConfiguration.createDefault(getBaseContext()));
options = new DisplayImageOptions.Builder()
.showImageForEmptyUri(R.drawable.ic_launcher)
.showImageOnFail(R.drawable.ic_launcher)
.resetViewBeforeLoading(true)
.cacheOnDisk(true)
.imageScaleType(ImageScaleType.EXACTLY)
.bitmapConfig(Bitmap.Config.RGB_565)
.considerExifParams(true)
.displayer(new FadeInBitmapDisplayer(300))
.build();
imagebutton.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// coding for wall set as wallpaper
int b=pager.getCurrentItem();
WallpaperManager myWallpaperManager=WallpaperManager. getInstance(getApplicationContext());
myWallpaperManager.setResource(id);
}
});
}
public class GetImagesAsync extends AsyncTask<String, ArrayList<HashMap<String,String>>, ArrayList<HashMap<String,String>>>
{
#Override
protected ArrayList<HashMap<String, String>> doInBackground(String... params)
{
JsonParser json = new JsonParser();
String url="myurlhere";
String data=json.getdata(url);
try
{
JSONObject jobject= new JSONObject(data);
String status=jobject.get(TAG_STATUS).toString();
if(status.equalsIgnoreCase("1"))
{
JSONArray jarray = jobject.getJSONArray(TAG_DATA);
for(int i=0;i<jarray.length();i++)
{
String id =jarray.getJSONObject(i).get(TAG_ID).toString();
String category=jarray.getJSONObject(i).get(TAG_IMAGENAME).toString();
HashMap<String, String> map = new HashMap<>();
map.put(TAG_ID,id);
map.put(TAG_IMAGENAME, category);
mylist.add(map);
}
}
}
catch (JSONException e)
{
e.printStackTrace();
}
Log.e("ClickedImagesActivity","Data-------"+data);
return mylist;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result)
{
pagerAdapter=new ImagePagerAdapter(result);
//pager.setAdapter(new ImagePagerAdapter(result));
pager.setAdapter(pagerAdapter);
}
}
private class ImagePagerAdapter extends PagerAdapter
{
//private String[] images;
ArrayList<HashMap<String,String>> images;
private LayoutInflater inflater;
ImagePagerAdapter(ArrayList<HashMap<String,String>> images)
{
this.images = images;
inflater = getLayoutInflater();
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public int getCount() {
return images.size();
}
#Override
public Object instantiateItem(ViewGroup view, int position) {
View imageLayout = inflater.inflate(R.layout.imagelayout, view, false);
assert imageLayout != null;
final ImageView imageView = (ImageView) imageLayout.findViewById(R.id.image);
imageView.setBackgroundResource(R.drawable.rounded_corner);
imageView.setScaleType(ScaleType.FIT_XY);
final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loading);
imageView.setTag(position);
imageLoader.displayImage(images.get(position).get(TAG_IMAGENAME), imageView, options, new SimpleImageLoadingListener()
{
#Override
public void onLoadingStarted(String imageUri, View view)
{
spinner.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
String message = null;
switch (failReason.getType()) {
case IO_ERROR:
message = "Input/Output error";
break;
case DECODING_ERROR:
message = "Image can't be decoded";
break;
case NETWORK_DENIED:
message = "Downloads are denied";
break;
case OUT_OF_MEMORY:
message = "Out Of Memory error";
break;
case UNKNOWN:
message = "Unknown error";
break;
}
spinner.setVisibility(View.GONE);
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
spinner.setVisibility(View.GONE);
}
});
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;
}
}

mp3 file download via asynctask and having progress bar listview android

I have an async task
new DownloadFile().execute(url2.toString());
When ever i find a mp3 file on url for example www.xyz.com/preview.mp3
I call the above async task
new DownloadFile().execute(url2.toString());
Then i also have a progress bar in a list view, But now the progress bar isnt updated
I use a custom adapter and have inflated the view properly.
public class CopyOfDownloadsListActivity extends ListActivity {
/** Called when the activity is first created. */
// static ArrayList<String> pthreads = new ArrayList<String>();
static ImageView bt;
static ProgressBar pb;
static ListView allList;
static TextView tv;
String fileName;
String mp3URL;
URL url2;
int myProgress;
static int filecount = 0;
MyCustomAdapter adapter;
private class DownloadFile extends AsyncTask<String, Integer, Void>{
int count = 0;
ProgressDialog dialog;
int myProgess = 0;
ProgressBar progressBar;
#Override
protected Void doInBackground(String... u) {
try {
URL ul = new URL(u[0]);
Log.i("UI",ul.toString());
// int len = CopyOfMusicDownloader.mp3urls.size();
// URL url2 = new URL(CopyOfMusicDownloader.mp3urls.get(len-1));
HttpURLConnection c = (HttpURLConnection) ul.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
int lengthOfFile = c.getContentLength();
String PATH = Environment.getExternalStorageDirectory()
+ "/download/";
Log.v("", "PATH: " + PATH);
File file = new File(PATH);
file.mkdirs();
fileName = "Track";
filecount++;
fileName = fileName + Integer.toString(filecount) + ".mp3";
File outputFile = new File(file, fileName);
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
myProgress = (int)(len1*100/lengthOfFile);
//myProgress = (int)(len1);
Log.i("My Progress", Integer.toString(myProgress));
publishProgress(myProgress);
// publishProgress((int)(len1*100/lengthOfFile));
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
}catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute() {
}
#Override
protected void onPreExecute() {
setListAdapter(new MyCustomAdapter(CopyOfDownloadsListActivity.this, R.layout.row, CopyOfMusicDownloader.mp3urls));
}
#Override
protected void onProgressUpdate(Integer... values) {
pb.setProgress(count);// HERE IS THE PROBLEM
count++;
Log.i("Values", Integer.toString(values[0]));
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
int len = CopyOfMusicDownloader.mp3urls.size();
try {
url2 = new URL(CopyOfMusicDownloader.mp3urls.get(len-1));
new DownloadFile().execute(url2.toString());
Log.i("url",url2.toString());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater myMenuInflater = getMenuInflater();
myMenuInflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case(R.id.browsermenu):
Intent i = new Intent(CopyOfDownloadsListActivity.this, MusicDownloader.class);
startActivity(i);
break;
case(R.id.downloaderrmenu):
break;
case(R.id.playermenu):
Intent j = new Intent(CopyOfDownloadsListActivity.this, Players.class);
startActivity(j);
break;
}
return true;
}
public class MyCustomAdapter extends ArrayAdapter<String> {
public MyCustomAdapter(Context context, int textViewResourceId, ArrayList<String> pthreads) {
super(context, textViewResourceId, pthreads);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.row, parent, false);
bt =(ImageView)row.findViewById(R.id.cancel_btn);
tv =(TextView)row.findViewById(R.id.filetext);
pb = (ProgressBar)row.findViewById(R.id.progressbar_Horizontal);
return row;
}
}
}
is that what you are looking for?
private class DownloadFile extends AsyncTask<String, Integer, Void> {
ProgressBar progressBar;
public DownloadFile(ProgressBar progressBar) {
this.progressBar=progressBar;
}
#Override
protected void onProgressUpdate(Integer... values) {
progressBar.setProgress(count);
}
}
now, every DownloadFile Task have its own ProgressBar.
i think this is the problem ( i didnt test your code)
myProgress = (int)(len1*100/lengthOfFile);
this must look like this
myProgress += (int)(len1*100/lengthOfFile);
I know this question is old but someone might came across like I did. Here's my code. Maybe it's not the best approach but I need to make it work ASAP.
My adapter element
ChatRow
public class ChatRow {
private int progressCount;
private boolean sending;
public boolean isSending()
{
return sending;
}
public void setSending(boolean sending)
{
this.sending = sending;
}
public int getProgressCount() {
return progressCount;
}
public void setProgressCount(int progressCount) {
this.progressCount = progressCount;
}
}
on the getView method of my adapter i have this part of code
if (row.isSending()) {
holder.progressBar.setVisibility(View.VISIBLE);
holder.progressBar.setProgress(row.getProgressCount());
}
and this on my AsyncTask
SendFileTask
private class SendFileTask extends AsyncTask<String, Integer, Boolean> {
private ChatRow row;
public SendFileTask(int rowNumber) {
this.row = adapter.getItem(rowNumber);
}
#Override
protected void onProgressUpdate(Integer... values) {
Logger.d(String.format("progress[%d]", values[0]));
row.setProgressCount(values[0]);
adapter.notifyDataSetChanged();
}
#Override
protected void onPostExecute(Boolean result) {
row.setSending(false);
row.setProgressCount(0);
adapter.notifyDataSetChanged();
}

Categories

Resources