ViewPager with fragment which shows ParseImage - android

I have a problem with a ViewPager. My ViewPager must shows images from Parse.com. Each item of ViewPager is a fragment, the same fragment, and it shows different images depending the item.
My problem is for example: if i have three pages, the first page shows nothing, the second one, shows the correct image, and the third one the correct one too. When I return to the first page then the image loads, but only when i return to it, not the first time.
This is my code:
My Activity:
public class FolletosActivity extends FragmentActivity {
public static final String QUERY = "query";
String selec;
ViewPager viewPager;
private PagerAdapter mPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_carta_menu);
Intent intent = getIntent();
selec = intent.getStringExtra(QUERY);
viewPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new FolletosPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mPagerAdapter);
}
The PagerAdapter:
public class FolletosPagerAdapter extends FragmentPagerAdapter {
int numPages;
public FolletosPagerAdapter(FragmentManager fm) {
super(fm);
ParseQuery<ParseObject> query = ParseQuery.getQuery("folletos_app");
query.whereGreaterThanOrEqualTo("num_pag", 0); //busco todos los objetos de parse
List<ParseObject> promosParse = null;
try {
promosParse = query.find();
numPages = promosParse.size();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public Fragment getItem(int position) {
return new PaginaFolletoFragment(position);
}
#Override
public int getCount() {
return numPages;
}
}
And the Fragment:
public class PaginaFolletoFragment extends Fragment {
public static final String QUERY = "query";
ParseImageView imageView;
String selec;
int position_;
public PaginaFolletoFragment(int position) {
// TODO Auto-generated constructor stub
position_ = position;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
String filepath = "/sdcard/Android/data/package/cache/uil-images/"+"folleto_"+selec+"_"+"numpage_"+position_;
File file = new File(filepath);
if(file.exists()){
Bitmap bmp = BitmapFactory.decodeFile(filepath);
imageView.setImageBitmap(bmp);
}
else{
if(ImageLoader.getInstance().isInited())
ImageLoader.getInstance().destroy();
//Create image options.
DisplayImageOptions options = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisc(true)
.build();
//Create a config with those options.
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getActivity().getApplicationContext())
.defaultDisplayImageOptions(options)
.discCacheFileNameGenerator(new FileNameGenerator() {
#Override
public String generate(String imageUri) {
return "folleto_"+selec+"_"+"numpage_"+position_;
}
})
.memoryCacheSize(41943040)
.discCacheSize(104857600)
.threadPoolSize(10)
.build();
ImageLoader.getInstance().init(config);
ParseQuery<ParseObject> query = ParseQuery.getQuery("folletos_app");
query.whereEqualTo("num_pag", position_);
List<ParseObject> promosParse;
try {
promosParse = query.find();
for(final ParseObject dealsObject : promosParse) {
final ParseFile image = dealsObject.getParseFile("pagina");
imageView.loadInBackground(new GetDataCallback() {
public void done(byte[] data, ParseException e) {
// The image is loaded and displayed!
int oldHeight = imageView.getHeight();
int oldWidth = imageView.getWidth();
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.displayImage(image.getUrl(), imageView);
}
});
}
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} //los meto en una lista
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_pagina_menu, container, false);
imageView = (ParseImageView) view.findViewById(R.id.imagePage);
Intent intent = getActivity().getIntent();
selec = intent.getStringExtra(QUERY);
return view;
}
}

Sorry if this is late but this is what you wanna do..
//Get the image from your ParseObject
ParseFile file = (ParseFile) dealsObject.getParseFile("pagina");
//Set the imageview to show the content of your ParseFile
imageView.setParseFile(file);
//Load the image in the background and display ones loaded
imageView.loadInBackground(new GetDataCallback() {
#Override
public void done(byte[] bytes, ParseException e) {
if (e != null) {
}
}
}

Related

out of memory exception with glide and ViewPager

I have a gallery of images that shows the images in a recyclerviewusing glide and by clicking on each image in the recyclerview that image open in a view pager. every thing is ok in the beginning the recyclerview is fine, the images open in a viewpager and sliding in viewpager are all fine. but when i press back to close the viewpager and goback to recyclerview suddenly the allocated memory raises to about 400 MB!!!
there are 8 images that are about 490*420 pixel and 72 KB size.
MainGallery.xml
<android.support.v7.widget.RecyclerView
android:id="#+id/recView_Gallery1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
>
</android.support.v7.widget.RecyclerView>
<Button
android:id="#+id/btn_retry_Gallery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="تلاش مجدد"
android:textSize="16sp"
android:visibility="gone"
android:layout_gravity="center"
android:gravity="center"/>
</android.support.design.widget.CoordinatorLayout>
GalleryEnter.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorAccent">
<ImageView
android:id="#+id/iv_photoGallety"
android:adjustViewBounds="true"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:layout_margin="2dp"
android:layout_width="match_parent"
android:background="#android:color/white"/>
</LinearLayout>
ImageDetail.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorAccent"
tools:context="com.parsroyan.restaurant.imageDetailActivity">
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.support.design.widget.CoordinatorLayout>
MainGalleryActivity.java
public class GalleryMain_Activity extends AppCompatActivity {
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
public static RecyclerView recListMenuTypes;
public static ImageAdapter mta;
ArrayList<ImageGallery> data = new ArrayList<>();
Button btn_retry;
TextView tv_message;
ImageView imv_message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery_main_);
btn_retry = (Button) findViewById(R.id.btn_retry_Gallery);
recListMenuTypes = (RecyclerView) findViewById(R.id.recView_Gallery1)
;
recListMenuTypes.setHasFixedSize(true);
GridLayoutManager mLayoutManager = new
GridLayoutManager(GalleryMain_Activity.this, 2);
recListMenuTypes.setLayoutManager(mLayoutManager);
//LinearLayoutManager llm = new
LinearLayoutManager(GalleryMain_Activity.this);
//llm.setOrientation(LinearLayoutManager.VERTICAL);
//recListMenuTypes.setLayoutManager(llm);
recListMenuTypes.setItemAnimator(new DefaultItemAnimator());
mta = new ImageAdapter(GalleryMain_Activity.this, data);
recListMenuTypes.setAdapter(mta);
Check_Connection_Retrive();
btn_retry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Check_Connection_Retrive();
}
});
}
private void alertView1(String message,boolean success) {
final TypedArray styledAttributes =
GalleryMain_Activity.this.getTheme().obtainStyledAttributes(new int[] {
android.R.attr.actionBarSize });
int Y = (int) styledAttributes.getDimension(0, 0);
styledAttributes.recycle();
LayoutInflater inflater = getLayoutInflater();
View toastLayout = inflater.inflate(R.layout.custom_toast,
(ViewGroup)
findViewById(R.id.custom_toast_layout));
tv_message = (TextView)
toastLayout.findViewById(R.id.custom_toast_message);
tv_message.setText(message);
Toast toast = new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP | Gravity.START |
Gravity.FILL_HORIZONTAL,0,Y);
toast.setView(toastLayout);
imv_message = (ImageView)
toastLayout.findViewById(R.id.custom_toast_image);
if(!success){
toastLayout.setBackgroundColor(Color.parseColor("#cc0000"));
imv_message.setBackgroundResource(android.R.drawable.ic_dialog_alert);
}
else {
imv_message.setBackgroundResource(android.R.drawable.ic_dialog_info);
}
toastLayout.setAlpha(.8f);
toast.show();
}
public void Check_Connection_Retrive()
{
if(InternetConnection.checkConnection(getApplicationContext(),this))
{
btn_retry.setVisibility(View.GONE);
new FetchGallery().execute();
}
else
{
btn_retry.setVisibility(View.VISIBLE);
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
private class FetchGallery extends AsyncTask<String, String, String> {
TransparentProgressDialog pdLoading = new
TransparentProgressDialog
(GalleryMain_Activity.this,R.drawable.progress_circle);
HttpURLConnection conn;
URL url = null;
#Override
protected void onPreExecute() {`enter code here`
super.onPreExecute();
//pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
//pdLoading.setProgress(10);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try {
url = new URL("My_URL");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "1";
}
try {
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return "2";
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return "3";
}
} catch (IOException e) {
return "4";
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
pdLoading.dismiss();
switch(result) {
case "1":
break;
case "2":
break;
case "3":
break;
case "4":
break;
default:
try {
btn_retry.setVisibility(View.GONE);
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
//JSONObject json_data = jArray.getJSONObject(i);
ImageGallery image = new ImageGallery();
//image.name = json_data.getString("name");
image.title = jArray.get(i).toString();
image.url = "MY_URL" + image.title;
data.add(image);
}
// Setup and Handover data to recyclerview
mta.notifyDataSetChanged();
recListMenuTypes.addOnItemTouchListener(new
RecyclerViewTouchListener(getApplicationContext(), recListMenuTypes, new
RecyclerViewClickListener() {
#Override
public void onClick(View view, int position) {
Intent intent = new Intent(GalleryMain_Activity.this,
imageDetailActivity.class);
intent.putParcelableArrayListExtra("data", data);
intent.putExtra("pos", position);
startActivity(intent);
}
#Override
public void onLongClick(View view, int position){
}
}));
} catch (JSONException e) {
Toast.makeText(GalleryMain_Activity.this,
e.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
}
ImageAdapter.java
public class ImageAdapter extends
RecyclerView.Adapter<ImageAdapter.MenuViewHolder> {
private List<ImageGallery> imageGalleryList;
private Context context;
protected int lastPosition = -1;
public ImageAdapter(Context Context,List<ImageGallery> contactList)
{
this.imageGalleryList = contactList;
this.context = Context;
}
#Override
public int getItemCount() {
return imageGalleryList.size();
}
#Override
public void onBindViewHolder(ImageAdapter.MenuViewHolder menuViewHolder,
int i) {
final ImageGallery m = imageGalleryList.get(i);
Glide.with(context).load("MyURL"+m.title)
.thumbnail(.1f)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.override(200,200).placeholder(R.drawable.logoback)
.into(menuViewHolder.vImage);
setFadeAnimation(menuViewHolder,i);
}
#Override
public int getItemViewType(int position) {
return super.getItemViewType(position);
}
#Override
public ImageAdapter.MenuViewHolder onCreateViewHolder(ViewGroup
viewGroup, int i) {
final View itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.activity_gallery_enter, viewGroup, false);
return new ImageAdapter.MenuViewHolder(itemView);
}
#Override
public void onViewDetachedFromWindow(ImageAdapter.MenuViewHolder holder)
{
((ImageAdapter.MenuViewHolder)holder).itemView.clearAnimation();
}
public class MenuViewHolder extends RecyclerView.ViewHolder{
protected ImageView vImage;
public MenuViewHolder(View v) {
super(v);
vImage = (ImageView) v.findViewById(R.id.iv_photoGallety);
}
}
private void setFadeAnimation(ImageAdapter.MenuViewHolder view, int
position) {
if (position > lastPosition) {
AlphaAnimation anim = new AlphaAnimation(0.0f, 2.0f);
anim.setDuration(1000);
view.itemView.startAnimation(anim);
lastPosition = position;
}
}
}
ImageDetailActivity.java
public class imageDetailActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
public ArrayList<ImageGallery> data = new ArrayList<>();
int pos;
Toolbar aboveToolbar;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_detail);
//aboveToolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.detail_toolbar);
//setSupportActionBar(aboveToolbar);
//getSupportActionBar().setDisplayHomeAsUpEnabled(true);
data = getIntent().getParcelableArrayListExtra("data");
pos = getIntent().getIntExtra("pos", 0);
setTitle(data.get(pos).getName());
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), data);
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setPageTransformer(true, new DepthPageTransformer());
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setCurrentItem(pos);
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
//noinspection ConstantConditions
setTitle(data.get(position).getName());
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public ArrayList<ImageGallery> data = new ArrayList<>();
public SectionsPagerAdapter(FragmentManager fm, ArrayList<ImageGallery> data) {
super(fm);
this.data = data;
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position, data.get(position).getName(), data.get(position).getUrl());
}
#Override
public int getCount() {
// Show 3 total pages.
return data.size();
}
// #Override
//public CharSequence getPageTitle(int position) {
//return data.get(position).getName();
// }
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
String name, url;
ImageView ImageView;
int pos;
private static final String ARG_SECTION_NUMBER = "section_number";
//private static final String ARG_IMG_TITLE = "image_title";
private static final String ARG_IMG_URL = "image_url";
#Override
public void setArguments(Bundle args) {
super.setArguments(args);
this.pos = args.getInt(ARG_SECTION_NUMBER);
//this.name = args.getString(ARG_IMG_TITLE);
this.url = args.getString(ARG_IMG_URL);
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber, String name, String url) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
//args.putString(ARG_IMG_TITLE, name);
args.putString(ARG_IMG_URL, url);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_image_detail, container, false);
this.ImageView = (ImageView) rootView.findViewById(R.id.detail_image);
Glide.with(getActivity()).load(url).thumbnail(0.1f).crossFade()
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.override(200,200).placeholder(R.drawable.tiara3)
.into(this.ImageView);
return rootView;
}
}
}
error log:
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.OutOfMemoryError
at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:501)
at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:354)
at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:785)
at android.content.res.Resources.loadDrawable(Resources.java:1970)
at android.content.res.Resources.getDrawable(Resources.java:660)
at com.bumptech.glide.request.GenericRequest.getPlaceholderDrawable(GenericRequest.java:416)
at com.bumptech.glide.request.GenericRequest.clear(GenericRequest.java:323)
at com.bumptech.glide.request.ThumbnailRequestCoordinator.clear(ThumbnailRequestCoordinator.java:106)
at com.bumptech.glide.manager.RequestTracker.clearRequests(RequestTracker.java:94)
at com.bumptech.glide.RequestManager.onDestroy(RequestManager.java:221)
at com.bumptech.glide.manager.ActivityFragmentLifecycle.onDestroy(ActivityFragmentLifecycle.java:64)
at com.bumptech.glide.manager.SupportRequestManagerFragment.onDestroy(SupportRequestManagerFragment.java:147)
at android.support.v4.app.Fragment.performDestroy(Fragment.java:2322)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1240)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1290)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1272)
at android.support.v4.app.FragmentManagerImpl.dispatchDestroy(FragmentManager.java:2186)
at android.support.v4.app.FragmentController.dispatchDestroy(FragmentController.java:271)
at android.support.v4.app.FragmentActivity.onDestroy(FragmentActivity.java:388)
at android.support.v7.app.AppCompatActivity.onDestroy(AppCompatActivity.java:209)
at android.app.Activity.performDestroy(Activity.java:5273)
at android.app.Instrumentation.callActivityOnDestroy(Instrumentation.java:1110)
at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3438)
at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:3469)
at android.app.ActivityThread.access$1200(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1287)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
real device result:
enter image description here
smulator result:
enter image description here
Add below line in Application tag in Menifest file:
android:largeHeap="true"

Setting images from url in ViewPager Android

I am following this tutorial for implementing ViewPager in my project. I have done that using static images successfully. Now I want to change it so that images are retrieved from urls and displayed in ViewPager. Below is my code.
Where should I add the method for downloading images and how to set it
to my ViewPager?
Any help will be greatly appreciated.
MainActivity:
public class MainActivity extends AppCompatActivity {
private ArrayList<Integer> images;
private BitmapFactory.Options options;
private ViewPager viewPager;
private View btnNext, btnPrev;
private FragmentStatePagerAdapter adapter;
private LinearLayout thumbnailsContainer;
private final static int[] resourceIDs = new int[]{R.mipmap.a, R.mipmap.b,
R.mipmap.c, R.mipmap.d, R.mipmap.e, R.mipmap.f, R.mipmap.g};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
images = new ArrayList<>();
//find view by id
viewPager = (ViewPager) findViewById(R.id.view_pager);
thumbnailsContainer = (LinearLayout) findViewById(R.id.container);
btnNext = findViewById(R.id.next);
btnPrev = findViewById(R.id.prev);
btnPrev.setOnClickListener(onClickListener(0));
btnNext.setOnClickListener(onClickListener(1));
setImagesData();
// init viewpager adapter and attach
adapter = new ViewPagerAdapter(getSupportFragmentManager(), images);
viewPager.setAdapter(adapter);
inflateThumbnails();
}
private View.OnClickListener onClickListener(final int i) {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
if (i > 0) {
//next page
if (viewPager.getCurrentItem() < viewPager.getAdapter().getCount() - 1) {
viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
}
} else {
//previous page
if (viewPager.getCurrentItem() > 0) {
viewPager.setCurrentItem(viewPager.getCurrentItem() - 1);
}
}
}
};
}
private void setImagesData() {
for (int i = 0; i < resourceIDs.length; i++) {
images.add(resourceIDs[i]);
}
}
private void inflateThumbnails() {
for (int i = 0; i < images.size(); i++) {
View imageLayout = getLayoutInflater().inflate(R.layout.item_image, null);
ImageView imageView = (ImageView) imageLayout.findViewById(R.id.img_thumb);
imageView.setOnClickListener(onChagePageClickListener(i));
options = new BitmapFactory.Options();
options.inSampleSize = 3;
options.inDither = false;
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), images.get(i), options );
imageView.setImageBitmap(bitmap);
//set to image view
imageView.setImageBitmap(bitmap);
//add imageview
thumbnailsContainer.addView(imageLayout);
}
}
private View.OnClickListener onChagePageClickListener(final int i) {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
viewPager.setCurrentItem(i);
}
};
}
}
PageFragment class:
public class PageFragment extends Fragment {
private int imageResource;
private Bitmap bitmap;
public static PageFragment getInstance(int resourceID) {
PageFragment f = new PageFragment();
Bundle args = new Bundle();
args.putInt("image_source", resourceID);
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
imageResource = getArguments().getInt("image_source");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_page, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ImageView imageView = (ImageView) view.findViewById(R.id.image);
BitmapFactory.Options o = new BitmapFactory.Options();
o.inSampleSize = 4;
o.inDither = false;
bitmap = BitmapFactory.decodeResource(getResources(), imageResource, o);
imageView.setImageBitmap(bitmap);
}
#Override
public void onDestroy() {
super.onDestroy();
bitmap.recycle();
bitmap = null;
}
}
ViewPager Adapter class:
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private List<Integer> images;
public ViewPagerAdapter(FragmentManager fm, List<Integer> imagesList) {
super(fm);
this.images = imagesList;
}
#Override
public Fragment getItem(int position) {
return PageFragment.getInstance(images.get(position));
}
#Override
public int getCount() {
return images.size();
}
}
To use ViewPager for images you have to make a adapter which extends PagerAdapter like as below:
public class ImagePagerAdapter extends PagerAdapter {
Context context;
LayoutInflater layoutInflater;
ArrayList<String> arrayList;
public ImagePagerAdapter(Context context, ArrayList<String> arrayList) {
this.context = context;
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.arrayList = arrayList;
}
#Override
public int getCount() {
if(arrayList != null){
return arrayList.size();
}
return 0;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((LinearLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
View itemView = layoutInflater.inflate(R.layout.image_viewpager_layout, container, false);
ImageView imageView = (ImageView) itemView.findViewById(R.id.viewPagerItem_image1);
Picasso.with(context).load(arrayList.get(position))
.placeholder(R.drawable.image_uploading)
.error(R.drawable.image_not_found).into(imageView);
container.addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((LinearLayout) object);
}
}
And xml layout for adapter is:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/viewPagerItem_image1"
android:layout_width="match_parent"
android:layout_height="250dp"
android:scaleType="fitXY"
android:src="#drawable/ic_launcher"/>
</LinearLayout>
For Download Images from URL you have to use AsyncTask.
For that follow below Example of DownloadImageFromAsyncTask.
new LoadImage().execute("http://www.sumtrix.com/images/sumtrix/Android-Wallpaper-HD.jpg");
Set your url to above url.
private class LoadImage extends AsyncTask<String, String, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Loading Image...");
dialog.show();
}
#Override
protected Bitmap doInBackground(String... params) {
try {
bitmap = BitmapFactory.decodeStream((InputStream) new URL(params[0]).getContent());
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
if (result != null) {
img.setImageBitmap(result);
dialog.dismiss();
} else {
dialog.dismiss();
Toast.makeText(getApplicationContext(), "Image Does Not Exist...",
Toast.LENGTH_LONG).show();
}
}
}
for that you have to add permission in AndroidManifest.xml file
<uses-permission android:name="android.permission.INTERNET" />
IMO you should set your image here, your imageResource is your imgUrl and using a lib such as: UniversalImageLoader, Volley, Picasso... we have many libs to support loading image with url.
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ImageView imageView = (ImageView) view.findViewById(R.id.image);
BitmapFactory.Options o = new BitmapFactory.Options();
o.inSampleSize = 4;
o.inDither = false;
bitmap = BitmapFactory.decodeResource(getResources(), imageResource, o);
imageView.setImageBitmap(bitmap);
}
you should call the picdownloadertask in onViewCreated()
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ImageView imageView = (ImageView) view.findViewById(R.id.image);
new PicDownladerTask().execute(url)
}
class PicDownloaderTask extends AsyncTask {
#Override
protected Bitmap doInBackground(String... strings) {
Bitmap bitmap = getBitmap(strings[0]);
return bitmap;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
BitmapFactory.Options o = new BitmapFactory.Options();
o.inSampleSize = 4;
o.inDither = false;
bitmap = BitmapFactory.decodeResource(getResources(), imageResource, o);
imageView.setImageBitmap(bitmap);
}
this is the method to get images from url
public static Bitmap getBitmap(String url)
{
try {
Bitmap bitmap=null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
conn.setConnectTimeout(70000);
conn.setReadTimeout(70000);
conn.setInstanceFollowRedirects(true);
InputStream is=conn.getInputStream();
// OutputStream os = new FileOutputStream(f);
// Utils.CopyStream(is, os);
// os.close();
bitmap = BitmapFactory.decodeStream(is);
conn.disconnect();
// bitmap = decodeFile(f);
return bitmap;
} catch (Throwable ex){
ex.printStackTrace();
if(ex instanceof OutOfMemoryError){}
// memoryCache.clear();
return null;
}
}
I use Picasso library when I need to show image from a URL. It is extremely simple to use.
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ImageView imageView = (ImageView) view.findViewById(R.id.image);
Picasso.with(this)
.load(image_url)
.into(imageView);
}
You can see references and download library from this, Picasso
Hope it's helpful.
Use this code to download and show on imageView.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout_here);
new DownloadImageTask((ImageView) findViewById(R.id.imageView1))
.execute("http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png");
}
public void onClick(View v) {
startActivity(new Intent(this, IndexActivity.class));
finish();
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
add internet permission in AndroidManifest.xml.
<uses-permission android:name="android.permission.INTERNET" />
see this link for more detail
create a async task and download the image in do in background
#Override
protected Bitmap doInBackground(String... url) {
this.url = url[0];
final DefaultHttpClient client = new DefaultHttpClient();
final org.apache.http.client.methods.HttpGet getRequest = new org.apache.http.client.methods.HttpGet(
url[0]);
try {
HttpResponse response = client.execute(getRequest);
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
LoggerUtils.logWarn("ImageDownloader", "Error "
+ statusCode + " while retrieving bitmap from "
+ url[0]);
return null;
}
final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = null;
try {
inputStream = entity.getContent();
final Bitmap bitmap = BitmapFactory
.decodeStream(inputStream);
return bitmap;
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (Exception e) {
getRequest.abort();
}

ViewPager shows the last images until the new images is not loading

My problem:At first time when i open item screen then the all images will be loaded into viewpager after that when i open new item screen then it is showing the old images untill the new images is not loading.
So i want to clear the old images on viewpager when i open a new item.
how can i clear the last images when i open new item screen?
i have written following code for display images in viewpager:
class productimages extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg) {
imageUlrList.clear();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", arg[0]));
JSONObject json = jParser.makeHttpRequest(url, "GET",
params);
try {
int success;
success = json.getInt(TAG_IMAGESUCCESS);
if (success == 1) {
JSONArray productObj = json.getJSONArray(TAG_PIMAGES);
for (int index = 0; index < productObj.length(); index++) {
JSONObject product = productObj.getJSONObject(index);
imageurl = product.getString(TAG_IMAGEURL);
imageUlrList.add(imageurl);
}
} else {
// product with pid not found
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
try {
mViewPager.setAdapter(null);
mViewSlidingImageAdapter = new ViewSlidingImageAdapter(
getSupportFragmentManager());
mViewPager.setAdapter(mViewSlidingImageAdapter);
mViewSlidingImageAdapter.notifyDataSetChanged();
} catch (Exception e) {
}
}
}
My adapter class:
class ViewSlidingImageAdapter extends FragmentStatePagerAdapter {
public ViewSlidingImageAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return imageUlrList.size();
}
#Override
public Fragment getItem(int position) {
return ViewSlidingImage.newInstance(position, product_url);
}
}
ViewSlidingImage:
public class ViewSlidingImage extends Fragment {
private String postionOfArray = "";
static ViewSlidingImage newInstance(int imageNum, String imagePathName) {
final ViewSlidingImage f = new ViewSlidingImage();
final Bundle args = new Bundle();
args.putString("postionOfArray", "" + imageNum);
f.setArguments(args);
return f;
}
public ViewSlidingImage() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
postionOfArray = getArguments().getString("postionOfArray");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.view_sliding_image, container,
false);
ImageView mImageView = (ImageView) v
.findViewById(R.id.tutorial_imageview);
try {
String imagePath = SingleProductscreen.imageUlrList.get(Integer
.parseInt(postionOfArray));
UrlImageViewHelper.setUrlDrawable(mImageView, imagePath);
} catch (Exception e) {
// TODO: handle exception
}
return v;
}
}
ViewSlidingImage loads the ImageView with the contents in the imageUrlList as below:
String imagePath = SingleProductscreen.imageUlrList.get(Integer.parseInt(postionOfArray));
So all you need to do is clear this SingleProductscreen.imageUlrList in the onPreExecute. This way you can make sure that once you call the productimages asynctask, the SingleProductscreen.imageUlrList is empty and hence there wont be any image to load and it will be blank.
protected void onPreExecute() {
super.onPreExecute();
SingleProductscreen.imageUlrList.clear();
mViewSlidingImageAdapter = new ViewSlidingImageAdapter(getSupportFragmentManager());
mViewPager.setAdapter(mViewSlidingImageAdapter);
mViewSlidingImageAdapter.notifyDataSetChanged();
}

Android RecyclerView freezes when image loading is done using Picasso

In my android app, on homepage there is a recyclerview consisting cardviews as each item. First,I call ParseServer to get data on server and pass it to the recyclerview adapter. I pass image url along with other details to adapter class.
Inside my MainActivity.java
Parse.initialize(this, "key1", "key2");
ParsePush.subscribeInBackground("", new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Log.d("com.parse.push", "successfully subscribed to the broadcast channel.");
} else {
Log.e("com.parse.push", "failed to subscribe for push", e);
}
}
});
if(haveNetworkConnection()){
new task().execute();
mRecyclerView = (RecyclerView)findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
Class task which fetches data from server:
public class task extends AsyncTask<Void, Void, Void>{
ProgressDialog mProgressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
rel.setVisibility(View.VISIBLE);
pro.setVisibility(View.VISIBLE);
titles.clear();
images.clear();
venues.clear();
timings.clear();
urgent.clear();
}
#Override
protected Void doInBackground(Void... params) {
ParseQuery<ParseObject> query = ParseQuery.getQuery("notices");
try {
List<ParseObject> ob = query.find();
for(ParseObject obj:ob){
String str = obj.getString("title");
String str1 = obj.getString("venue");
String str2 = obj.getString("timing");
ParseFile file = obj.getParseFile("images");
String str3 = obj.getString("urgent");
String url;
if(file!=null)
url = file.getUrl();
else{
url = "https://www.medidirect.com.au/MEDIstores/_images/no-thumb.png";
}
titles.add(str);
images.add(url);
venues.add(str1);
timings.add(str2);
urgent.add(str3);
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
AdapNotice mAdapter = new AdapNotice(MainActivity.this,titles,images,venues,timings,urgent);
if(titles.size()<1)
Toast.makeText(MainActivity.this, "Oops, Something went wrong. Please try again", 300).show();
mRecyclerView.setAdapter(mAdapter);
pro.setVisibility(View.GONE);
rel.setVisibility(View.GONE);
}
}
Inside AdapNotice class which is recyclerview adapter:
public class AdapNotice extends RecyclerView.Adapter<AdapNotice.ViewHolder>{
Activity activity;
ArrayList<String> _titles = new ArrayList<String>();
ArrayList<String> _images = new ArrayList<String>();
ArrayList<String> _venues = new ArrayList<String>();
ArrayList<String> _timings = new ArrayList<String>();
ArrayList<String> _urgents = new ArrayList<String>();
private int lastPosition = -1;
int pos;
public AdapNotice(Activity a, ArrayList<String> titles, ArrayList<String> images, ArrayList<String> venues, ArrayList<String> timings, ArrayList<String> urgent) {
activity = a;
_titles = titles;
_images = images;
_venues = venues;
_timings = timings;
_urgents = urgent;
}
public static class ViewHolder extends RecyclerView.ViewHolder{
// each data item is just a string in this case
public TextView title;
public ImageView imgview,urgent;
public TextView venue,venuetext,abctext;
public TextView timing,timingtext,abc1text;
public ViewHolder(View v) {
super(v);
title = (TextView) v.findViewById(R.id.title);
imgview = (ImageView) v.findViewById(R.id.img_notice);
venue = (TextView) v.findViewById(R.id.venue);
timing = (TextView) v.findViewById(R.id.timing);
venuetext = (TextView)v.findViewById(R.id.venuetext);
abctext = (TextView)v.findViewById(R.id.abctext);
timingtext = (TextView)v.findViewById(R.id.timingtext);
abc1text = (TextView)v.findViewById(R.id.abc1text);
urgent = (ImageView)v.findViewById(R.id.urgentstar);
}
}
#Override
public int getItemCount() {
// TODO Auto-generated method stub
if(_titles.size()<=0)
return 0;
return _titles.size();
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
// TODO Auto-generated method stub
try{
holder.title.setText(_titles.get(position));
if(_urgents.get(position).contains("yes")){
holder.urgent.setVisibility(View.VISIBLE);
}
pos = position;
if(!_venues.get(position).contentEquals("---")){
holder.venuetext.setVisibility(View.VISIBLE);
holder.venue.setVisibility(View.VISIBLE);
holder.abctext.setVisibility(View.VISIBLE);
holder.venue.setText(_venues.get(position));
}
if(!_timings.get(position).contentEquals("---")){
holder.timingtext.setVisibility(View.VISIBLE);
holder.timing.setVisibility(View.VISIBLE);
holder.abc1text.setVisibility(View.VISIBLE);
holder.timing.setText(_timings.get(position));
}
Target target = new Target() {
#Override
public void onPrepareLoad(Drawable arg0) {
// TODO Auto-generated method stub
Animation anim = AnimationUtils.loadAnimation(activity, R.anim.rotate);
holder.imgview.setImageResource(R.drawable.loading);
holder.imgview.startAnimation(anim);
}
#Override
public void onBitmapLoaded(Bitmap arg0, LoadedFrom arg1) {
// TODO Auto-generated method stub
holder.imgview.clearAnimation();
holder.imgview.setImageBitmap(arg0);
Log.i("completed", pos+" completed");
storeDB obj = new storeDB(_titles.get(pos), _venues.get(pos), _timings.get(pos), DbBitmapUtility.getBytes(arg0), _urgents.get(pos));
obj.execute();
}
#Override
public void onBitmapFailed(Drawable arg0) {
// TODO Auto-generated method stub
holder.imgview.clearAnimation();
holder.imgview.setImageResource(R.drawable.error);
}
};
Picasso.with(activity).load(_images.get(position)).into(target);
}catch(Exception e){
e.printStackTrace();
}
}
private class storeDB extends AsyncTask<Void, Void, Void>{
String title,venue,timing,urgent;
byte[] image;
public storeDB(String one, String two, String three, byte[] four, String five){
title = one;
venue = two;
timing = three;
image = four;
urgent = five;
}
#Override
protected Void doInBackground(Void... params) {
SQLiteHandler handler = new SQLiteHandler(activity);
handler.addNotice(title, venue, timing, image, urgent);
handler.close();
return null;
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int arg1) {
View v = LayoutInflater.from(parent.getContext()).inflate(
R.layout.item, parent, false);
Animation animation = AnimationUtils.loadAnimation(activity, (arg1>lastPosition)?R.anim.up_from_bottom:R.anim.down_from_top);
v.startAnimation(animation);
ViewHolder vh = new ViewHolder(v);
return vh;
}
}
I pass the image url to picasso library which loads image into target. Till image is not fetched by picasso, I am showing another loading image and giving it rotate animation effect.
Sometimes, even if image is loaded by picasso, it is not shown in imageview.I know this because on clicking that imageview full image is loaded in another activity which works fine. The rotating animation stops and loaded image also not shown in imageview. Also, the main view freezes sometimes when imageview is being loaded.
So, how can i solve this issue and make my app smoother in operation?
Thanks in advance.
UPDATE I found out that freezing issue was because of the weak reference to target. I solved it with strong reference but how do I solve hanging issue ? App gets hanged for some time when I am scrolling .
You can use a simple approach
Picasso.with(context)
.load(url)
.placeholder(R.drawable.user_placeholder)
.error(R.drawable.user_placeholder_error)
.into(imageView);
placholder image will be shown before loading the image and error image will be shown if error occur
UPDATE
to store in a database just write this much boiler plate code
class MyTarget implements Target {
private ImageView imageView;
public MyTarget(ImageView imageView) {
this.imageView = imageView;
}
#Override
public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
this.imageView.setImageBitmap(bitmap);
//store your bitmap as you were storing
}
}
and then
Picasso.with(context)
.load(url)
.placeholder(R.drawable.user_placeholder)
.error(R.drawable.user_placeholder_error)
.into(new MyTarget(imageView));

Unable to retrieve Array from Aync task in Activity Using Universal Image Loader for Android and Flickr

I am trying to fetch a list of photos from a photo set in flickr
using universal image loader
My Base Activity ImagePagerActivity calls FetchPhotos which extends Async Task.
Code Follows
public class ImagePagerActivity extends BaseActivity {
private static final String STATE_POSITION = "STATE_POSITION";
public static final String API_KEY="mykey";
public static final String USER_ID="myid";
DisplayImageOptions options;
private Photos thePhotoList;
ViewPager pager;
private String thePhotos="";
private final int[] timeout={3,10};
private String url="http://www.flickr.com/services/rest/?method=flickr.photosets.getPhotos&format=json&api_key="+API_KEY+"&photoset_id=111111111";
private String[] imageUrls;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ac_image_pager);
Bundle bundle = getIntent().getExtras();
String url="http://www.flickr.com/services/rest/?method=flickr.photosets.getPhotos&format=json&api_key="+API_KEY+"&photoset_id=72157633359614452";
setContentView(R.layout.pics);
try{
((ViewAnimator)findViewById(R.id.PictureAnimator)).removeAllViews();
}catch (Exception e) {}
thePhotoList = new Photos(url);
thePhotoList.execute();
imageUrls=thePhotoList.imageList;
//imageUrls = bundle.getStringArray(Extra.IMAGES);
int pagerPosition = bundle.getInt(Extra.IMAGE_POSITION, 0);
if (savedInstanceState != null) {
pagerPosition = savedInstanceState.getInt(STATE_POSITION);
}
options = new DisplayImageOptions.Builder()
.showImageForEmptyUri(R.drawable.ic_empty)
.showImageOnFail(R.drawable.ic_error)
.resetViewBeforeLoading()
.cacheOnDisc()
.imageScaleType(ImageScaleType.EXACTLY)
.bitmapConfig(Bitmap.Config.RGB_565)
.displayer(new FadeInBitmapDisplayer(300))
.build();
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(new ImagePagerAdapter(this.imageUrls));
pager.setCurrentItem(pagerPosition);
}
private class Photos extends com.flickr.FetchPhotos{
#Override
public void onFetchError() {}
public Photos(String url) {super(ImagePagerActivity.this, url);}
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putInt(STATE_POSITION, pager.getCurrentItem());
}
private class ImagePagerAdapter extends PagerAdapter {
private String[] images;
private LayoutInflater inflater;
ImagePagerAdapter(String[] images) {
this.images = images;
inflater = getLayoutInflater();
}
#Override
public void destroyItem(ViewGroup 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(ViewGroup view, int position) {
View imageLayout = inflater.inflate(R.layout.item_pager_image, view, false);
ImageView imageView = (ImageView) imageLayout.findViewById(R.id.image);
final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loading);
imageLoader.displayImage(images[position], 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;
}
Toast.makeText(ImagePagerActivity.this, message, Toast.LENGTH_SHORT).show();
spinner.setVisibility(View.GONE);
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
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) {
}
}
}
next is the FetchPhotos class
public abstract class FetchPhotos extends AsyncTask<Void, Void, Boolean>{
private Context context;
private ProgressDialog pd;
private String thePhotos="";
private String url;
private final int[] timeout={3,10};
public ArrayList<PictureInfo> thePics;
public String[] imageList;
public FetchPhotos(Context context,String url) {
this.context=context;
this.url=url;
}
public String[] fillGalery(JSONObject theFeed) {
// TODO Auto-generated method stub
String[] imageUrls = null;
try{
JSONArray Categories=theFeed.getJSONArray("photo");
imageUrls=new String[Categories.length()];
for (int i=0;i<(Categories.length()>15?15:Categories.length());i++){
JSONObject pic = Categories.getJSONObject(i);
String url1="http://farm"+pic.getString("farm")+".staticflickr.com/"+pic.getString("server")+"/"+
pic.getString("id")+"_"+pic.getString("secret")+".jpg";
imageUrls[i]=url1;
System.out.println(imageUrls[i]);
}
return imageUrls;
}
catch(Exception e){
}
return imageUrls;
}
#Override
protected void onPreExecute() {
pd=ProgressDialog.show(context, "downloading", "please wait");
super.onPreExecute();
}
#Override
protected Boolean doInBackground(Void... arg0) {
try{
thePhotos = new Internet().GetRequest(url, null, timeout);
return true;
}catch (Exception e) {
return false;
}
}
#Override
protected void onPostExecute(Boolean result) {
pd.dismiss();
if(result){
try {
thePhotos=thePhotos.split("\\(")[1];
thePhotos.replace("\\)", "");
imageList=fillGalery(new JSONObject(thePhotos).getJSONObject("photoset"));
} catch (Exception e) {Log.e("karp", "photolist2: "+e.getMessage());onFetchError();onFetchError();}
}else{
onFetchError();
}
super.onPostExecute(result);
}
public abstract void onFetchError();
public void LoadPhoto(PictureInfo pi){
Log.d("karp", "LoadPhoto");
if(!(pi.executed)){
new LoadPics(pi).execute();
pi.executed=true;
}
}
private class LoadPics extends RemoteImage{
private ImageView ivTarget;
private ProgressBar pb;
public LoadPics(PictureInfo pi) {
super(pi.url);
this.ivTarget=pi.iv;
this.pb=pi.pb;
}
#Override
public void onSuccess(Bitmap remoteBitmap) {
try{
pb.setVisibility(View.INVISIBLE);
ivTarget.setImageBitmap(remoteBitmap);
}catch (Exception e) {}
}
#Override
public void onFail() {pb.setVisibility(View.INVISIBLE);}
}
}
I have created Photos class in Image Pager
and then Im trying to access fill gallery
Now Im trying to fill a string array with the image urls from flickr
using the method fillGallery that reurns a string array
In my base activity im calling
thePhotoList = new Photos(url);
thePhotoList.execute();
imageUrls=thePhotoList.imageList;
but try as i may i cant get an array in imageUrls which is a String Array.
When i use a hard coded string array with urls for images in it, the code works.
Any help would be really appreciated.
Im sure im doing something very silly as I am new to this.
Many thanks . Cheers!
I got it to work . Needed to add a listener interface , call the method from onPostExecute,
Implement it in the activity, access the variable in the implementation of the listeners abstract method. Should have researched a bit more before posting,but was stuck with the problem too long . Apologies.

Categories

Resources