1

My aim is to downloading the images from server and displays it in ViewPager without any UI Freezing. Initially loads data from Network, that time UI is Freezing for a moment after downloading everything it works fine. But i need to resolve that initial loads data from network freeze UI in ViewPager.

This is my viewPagerActivity class:

public class ViewPagerActivity extends Activity {
ViewPager pager;
String[] URL;
PagerAdapter objPagerAdapter;
ArrayList<String> _arrayImagePath=new ArrayList<String>();


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_view_pager);
    pager=(ViewPager)findViewById(R.id.pagerView);

    // Setting the 70 images URL 
    URL= new String[] { "http://vignette3.wikia.nocookie.net/dragonball/images/7/71/PollutionAura2.png/revision/latest?cb=20101211235024",
            "http://vignette2.wikia.nocookie.net/aread/images/6/6f/V02_Back.jpg/revision/latest?cb=20140501154842", 
            "http://vignette1.wikia.nocookie.net/tmnt/images/d/d5/Tnmt-disneyscreencaps_com-5817.jpg/revision/latest?cb=20130428155629",
            "https://upload.wikimedia.org/wikipedia/commons/2/27/Sunset_at_Selsey_beach_4.jpg",
            "http://img1.wikia.nocookie.net/__cb20140806200752/disney/images/d/d8/Little-mermaid-1080p-disneyscreencaps.com-782.jpg",
            "http://img3.wikia.nocookie.net/__cb20141022183927/howtotrainyourdragon/images/c/c5/When_gothi_drops_that_flag_we_race.jpg",
            "http://img.gawkerassets.com/img/17jy4w1lonvyijpg/original.jpg",
            "http://vignette3.wikia.nocookie.net/dragonball/images/7/71/PollutionAura2.png/revision/latest?cb=20101211235024",
            "http://vignette2.wikia.nocookie.net/aread/images/6/6f/V02_Back.jpg/revision/latest?cb=20140501154842", 
            "http://vignette1.wikia.nocookie.net/tmnt/images/d/d5/Tnmt-disneyscreencaps_com-5817.jpg/revision/latest?cb=20130428155629",
            "https://upload.wikimedia.org/wikipedia/commons/2/27/Sunset_at_Selsey_beach_4.jpg",
            "http://img1.wikia.nocookie.net/__cb20140806200752/disney/images/d/d8/Little-mermaid-1080p-disneyscreencaps.com-782.jpg",
            "http://img3.wikia.nocookie.net/__cb20141022183927/howtotrainyourdragon/images/c/c5/When_gothi_drops_that_flag_we_race.jpg",
            "http://img.gawkerassets.com/img/17jy4w1lonvyijpg/original.jpg",
            "http://vignette3.wikia.nocookie.net/dragonball/images/7/71/PollutionAura2.png/revision/latest?cb=20101211235024",
            "http://vignette2.wikia.nocookie.net/aread/images/6/6f/V02_Back.jpg/revision/latest?cb=20140501154842", 
            "http://vignette1.wikia.nocookie.net/tmnt/images/d/d5/Tnmt-disneyscreencaps_com-5817.jpg/revision/latest?cb=20130428155629",
            "https://upload.wikimedia.org/wikipedia/commons/2/27/Sunset_at_Selsey_beach_4.jpg",
            "http://img1.wikia.nocookie.net/__cb20140806200752/disney/images/d/d8/Little-mermaid-1080p-disneyscreencaps.com-782.jpg",
            "http://img3.wikia.nocookie.net/__cb20141022183927/howtotrainyourdragon/images/c/c5/When_gothi_drops_that_flag_we_race.jpg",
            "http://img.gawkerassets.com/img/17jy4w1lonvyijpg/original.jpg",
            "http://vignette3.wikia.nocookie.net/dragonball/images/7/71/PollutionAura2.png/revision/latest?cb=20101211235024",
            "http://vignette2.wikia.nocookie.net/aread/images/6/6f/V02_Back.jpg/revision/latest?cb=20140501154842", 
            "http://vignette1.wikia.nocookie.net/tmnt/images/d/d5/Tnmt-disneyscreencaps_com-5817.jpg/revision/latest?cb=20130428155629",
            "https://upload.wikimedia.org/wikipedia/commons/2/27/Sunset_at_Selsey_beach_4.jpg",
            "http://img1.wikia.nocookie.net/__cb20140806200752/disney/images/d/d8/Little-mermaid-1080p-disneyscreencaps.com-782.jpg",
            "http://img3.wikia.nocookie.net/__cb20141022183927/howtotrainyourdragon/images/c/c5/When_gothi_drops_that_flag_we_race.jpg",
            "http://img.gawkerassets.com/img/17jy4w1lonvyijpg/original.jpg",
            "http://vignette3.wikia.nocookie.net/dragonball/images/7/71/PollutionAura2.png/revision/latest?cb=20101211235024",
            "http://vignette2.wikia.nocookie.net/aread/images/6/6f/V02_Back.jpg/revision/latest?cb=20140501154842", 
            "http://vignette1.wikia.nocookie.net/tmnt/images/d/d5/Tnmt-disneyscreencaps_com-5817.jpg/revision/latest?cb=20130428155629",
            "https://upload.wikimedia.org/wikipedia/commons/2/27/Sunset_at_Selsey_beach_4.jpg",
            "http://img1.wikia.nocookie.net/__cb20140806200752/disney/images/d/d8/Little-mermaid-1080p-disneyscreencaps.com-782.jpg",
            "http://img3.wikia.nocookie.net/__cb20141022183927/howtotrainyourdragon/images/c/c5/When_gothi_drops_that_flag_we_race.jpg",
            "http://img.gawkerassets.com/img/17jy4w1lonvyijpg/original.jpg",
            "http://vignette3.wikia.nocookie.net/dragonball/images/7/71/PollutionAura2.png/revision/latest?cb=20101211235024",
            "http://vignette2.wikia.nocookie.net/aread/images/6/6f/V02_Back.jpg/revision/latest?cb=20140501154842", 
            "http://vignette1.wikia.nocookie.net/tmnt/images/d/d5/Tnmt-disneyscreencaps_com-5817.jpg/revision/latest?cb=20130428155629",
            "https://upload.wikimedia.org/wikipedia/commons/2/27/Sunset_at_Selsey_beach_4.jpg",
            "http://img1.wikia.nocookie.net/__cb20140806200752/disney/images/d/d8/Little-mermaid-1080p-disneyscreencaps.com-782.jpg",
            "http://img3.wikia.nocookie.net/__cb20141022183927/howtotrainyourdragon/images/c/c5/When_gothi_drops_that_flag_we_race.jpg",
            "http://img.gawkerassets.com/img/17jy4w1lonvyijpg/original.jpg",
            "http://vignette3.wikia.nocookie.net/dragonball/images/7/71/PollutionAura2.png/revision/latest?cb=20101211235024",
            "http://vignette2.wikia.nocookie.net/aread/images/6/6f/V02_Back.jpg/revision/latest?cb=20140501154842", 
            "http://vignette1.wikia.nocookie.net/tmnt/images/d/d5/Tnmt-disneyscreencaps_com-5817.jpg/revision/latest?cb=20130428155629",
            "https://upload.wikimedia.org/wikipedia/commons/2/27/Sunset_at_Selsey_beach_4.jpg",
            "http://img1.wikia.nocookie.net/__cb20140806200752/disney/images/d/d8/Little-mermaid-1080p-disneyscreencaps.com-782.jpg",
            "http://img3.wikia.nocookie.net/__cb20141022183927/howtotrainyourdragon/images/c/c5/When_gothi_drops_that_flag_we_race.jpg",
            "http://img.gawkerassets.com/img/17jy4w1lonvyijpg/original.jpg",
            "http://vignette3.wikia.nocookie.net/dragonball/images/7/71/PollutionAura2.png/revision/latest?cb=20101211235024",
            "http://vignette2.wikia.nocookie.net/aread/images/6/6f/V02_Back.jpg/revision/latest?cb=20140501154842", 
            "http://vignette1.wikia.nocookie.net/tmnt/images/d/d5/Tnmt-disneyscreencaps_com-5817.jpg/revision/latest?cb=20130428155629",
            "https://upload.wikimedia.org/wikipedia/commons/2/27/Sunset_at_Selsey_beach_4.jpg",
            "http://img1.wikia.nocookie.net/__cb20140806200752/disney/images/d/d8/Little-mermaid-1080p-disneyscreencaps.com-782.jpg",
            "http://img3.wikia.nocookie.net/__cb20141022183927/howtotrainyourdragon/images/c/c5/When_gothi_drops_that_flag_we_race.jpg",
            "http://img.gawkerassets.com/img/17jy4w1lonvyijpg/original.jpg",
            "http://vignette3.wikia.nocookie.net/dragonball/images/7/71/PollutionAura2.png/revision/latest?cb=20101211235024",
            "http://vignette2.wikia.nocookie.net/aread/images/6/6f/V02_Back.jpg/revision/latest?cb=20140501154842", 
            "http://vignette1.wikia.nocookie.net/tmnt/images/d/d5/Tnmt-disneyscreencaps_com-5817.jpg/revision/latest?cb=20130428155629",
            "https://upload.wikimedia.org/wikipedia/commons/2/27/Sunset_at_Selsey_beach_4.jpg",
            "http://img1.wikia.nocookie.net/__cb20140806200752/disney/images/d/d8/Little-mermaid-1080p-disneyscreencaps.com-782.jpg",
            "http://img3.wikia.nocookie.net/__cb20141022183927/howtotrainyourdragon/images/c/c5/When_gothi_drops_that_flag_we_race.jpg",
            "http://img.gawkerassets.com/img/17jy4w1lonvyijpg/original.jpg",
            "http://vignette3.wikia.nocookie.net/dragonball/images/7/71/PollutionAura2.png/revision/latest?cb=20101211235024",
            "http://vignette2.wikia.nocookie.net/aread/images/6/6f/V02_Back.jpg/revision/latest?cb=20140501154842", 
            "http://vignette1.wikia.nocookie.net/tmnt/images/d/d5/Tnmt-disneyscreencaps_com-5817.jpg/revision/latest?cb=20130428155629",
            "https://upload.wikimedia.org/wikipedia/commons/2/27/Sunset_at_Selsey_beach_4.jpg",
            "http://img1.wikia.nocookie.net/__cb20140806200752/disney/images/d/d8/Little-mermaid-1080p-disneyscreencaps.com-782.jpg",
            "http://img3.wikia.nocookie.net/__cb20141022183927/howtotrainyourdragon/images/c/c5/When_gothi_drops_that_flag_we_race.jpg",
            "http://img.gawkerassets.com/img/17jy4w1lonvyijpg/original.jpg"
             };

    objPagerAdapter=new ViewPagerAdapter(ViewPagerActivity.this, _arrayImagePath);
    pager.setAdapter(objPagerAdapter);

    // Calling Volley Library to Download the Image for each URLi

    for(int i=0;i<URL.length;i++)
    {
        DownloadImages(URL[i], i);
    }


}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.view_pager, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}
void DownloadImages(String imageURL_in,final int counter_in)
{
    final String counter=String.valueOf(counter_in);
    ImageRequest imageRequest = new ImageRequest(imageURL_in,
            new Response.Listener<Bitmap>() {

        @Override
        public void onResponse(final Bitmap response) {
            try{
                Log.v("Response Received =",""+counter_in);
                // Saved in SD Card and getting the Path
                String imagePath = SavedInSDCard(response, counter + "_hires"); 
                //Added ImagePath 
                _arrayImagePath.add(imagePath);
                // Notifying the Adapter
                objPagerAdapter.notifyDataSetChanged();


            } catch (Exception e) {e.printStackTrace();}
        }
    }, 0, 0, null, null);
    ApplicationController.getInstance().addToRequestQueue(imageRequest);



}
public String SavedInSDCard(Bitmap bitmap2, String dishId) {

    File dir = new File(ApplicationController.getAppContext()
            .getExternalFilesDir("ViewPager_POC") + "/Cache");
    // Create the storage directory if it does not exist
    if (!dir.exists()) {
        dir.mkdirs();
    }
    String stDishID = dishId;
    String formatedDsihID = stDishID.replace(":", "R");
    File file = new File(dir, formatedDsihID);
    try {
        FileOutputStream out = new FileOutputStream(file);
        bitmap2.compress(Bitmap.CompressFormat.JPEG, 100, out);
        out.flush();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    String imgPath = dir + "/" + formatedDsihID;
    return imgPath;
}


}

This is my ViewPagerAdapter class:

public class ViewPagerAdapter extends PagerAdapter{
Context _context;
LayoutInflater inflater;

ArrayList<String> _arrayImagePath;

public ViewPagerAdapter(Context context_in, ArrayList<String> imagePath_in) {
    _arrayImagePath=imagePath_in;
    _context = context_in;
}

@Override
public int getCount() {
    return _arrayImagePath.size();
}

@Override
public void destroyItem(View container, int position, Object object) {
    // TODO Auto-generated method stub
    ((ViewPager) container).removeView((View) object);
}

@Override
public Object instantiateItem(ViewGroup container, int position) {

    // Declare Variables
    TextView txtCounter;
    ImageView imgView;

    inflater = (LayoutInflater) _context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View itemView = inflater.inflate(R.layout.view_pager_item, container,
            false);

    txtCounter = (TextView) itemView.findViewById(R.id.counter);
    imgView= (ImageView) itemView.findViewById(R.id.images);

    //Setting the values for Image and textview
    txtCounter.setText(""+(position+1));        

    BitmapWorkerTask task = new BitmapWorkerTask(imgView);
    task.execute(_arrayImagePath.get(position));

    // Add viewpager_item.xml to ViewPager
    ((ViewPager) container).addView(itemView);

    return itemView;
}
@Override
public boolean isViewFromObject(View view, Object object) {
    return view == ((RelativeLayout) object);
}

class BitmapWorkerTask extends AsyncTask<String, Void, Bitmap> {
    private final WeakReference<ImageView> imageViewReference;

    public BitmapWorkerTask(ImageView imageView) {
        imageViewReference = new WeakReference<ImageView>(imageView);
    }
    @Override
    protected Bitmap doInBackground(String... params) {
        String path = params[0];
        return BitmapFactory.decodeFile(path);
    }

    @Override
    protected void onPostExecute(Bitmap bitmap) {
        if (imageViewReference != null && bitmap != null) {
            final ImageView imageView = imageViewReference.get();
            if (imageView != null) {
                imageView.setImageBitmap(bitmap);
        }
    }
}
}

}

This is my xml view_pager_activity.xml file :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.poc_viewpager.ViewPagerActivity" >

     <android.support.v4.view.ViewPager
    android:id="@+id/pagerView"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
</RelativeLayout>

This is my view pager item xml file:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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/images"
    android:layout_width="match_parent"
    android:layout_height="300dp"
    android:layout_alignParentLeft="true" />

<TextView
    android:id="@+id/counter"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="44dp"
    android:text="Large Text"
    android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>

Can anyone suggest any ideas to resolve this issue??
Thanks In Advance

Ashok
  • 839
  • 10
  • 21

2 Answers2

0

You should implement FragmentPagerAdapter or FragmentStatePagerAdapter in your ViewPagerActivity.

After that move your image loading async task into your custom Fragment's onCreateView method.

UI freezing is due to your instantiateItem in ViewPager is still waiting for UI to be ready before inflating it, although you have already made your image loading task asynchronous.

It's always better to leave the implementation of ViewPager as it is, as per mentioned in Android Developers documentation:

ViewPager is most often used in conjunction with Fragment, which is a convenient way to supply and manage the lifecycle of each page. There are standard adapters implemented for using fragments with the ViewPager, which cover the most common use cases. These are FragmentPagerAdapter and FragmentStatePagerAdapter; each of these classes have simple code showing how to build a full user interface with them.

Ken Tan
  • 700
  • 6
  • 15
0
  1. Tip: Never block the main thread, Do network operations on background threads, and update the main thread after completion, or on progress It seems that you are making a download synchronously on main thread, thats why it freezes.
  2. Suggestions: You could use the most abused threading mechanism in android AsyncTask
  3. Also check this answer
Community
  • 1
  • 1
abdimuna
  • 775
  • 9
  • 16