Thursday 25 July 2013

GridView with ViewPager like Android Menu


Hi everyone there, this is my first attempt to write a blog, bare with me for any mistakes. A few days back I had this requirement of creating a Grid view which will be able to slide and also indicate how many screens the grid view has in total, just like we do in the Menu option of any Android phone. So after lot of research I made a solution with the help of an library which will be helpful to show the number of pages just like we get in menu option of android phone and so thought of putting it up on my blog so that others would be benefited from it.

Firstly I would like you to thank Jake Wharton for his library "Android-ViewPagerIndicator" which can be downloaded from here https://github.com/JakeWharton/Android-ViewPagerIndicator

We need to download and import it in our project work space. I hope you guys wont be having much of trouble doing that. Firstly i would like to show how the output will look like. Please see it in full screen where you will see the total number of dots equal to total number of pages at the bottom.




The next step is start writing our code for the actual project. So lets first start with the XML files required. Total we will need 3 layout files.

1) activity_main.xml : - which holds the viewpager and also the PagerIndicator.
2) grid.xml: - which holds the gridview
3) custom.xml - which holds the gridview custom layout (A gridview with a Image and text in our case).

The activity_main.xml looks like this:

<LinearLayout 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:background="@android:color/black"
      android:orientation="vertical"
      tools:context=".MainActivity" >

      <android.support.v4.view.ViewPager
           android:id="@+id/pager"
           android:layout_width="fill_parent"
           android:layout_height="400dp" />

      <com.viewpagerindicator.CirclePageIndicator
           android:id="@+id/pagerIndicator"
           android:layout_width="fill_parent"
           android:layout_height="wrap_content"
           android:layout_marginBottom="5dp"
           android:layout_marginTop="5dp"
           android:padding="3dp" />
</LinearLayout>

It holds a LinearLayout which will hold our GridView a ViewPager and a PagerIndicator. The grid.xml looks like this:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:orientation="vertical" >

     <GridView
          android:id="@+id/gridView"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:layout_margin="1dp"
          android:layout_marginTop="2dp"
          android:horizontalSpacing="2dp"
          android:listSelector="@android:color/transparent"
          android:numColumns="3"
          android:stretchMode="columnWidth"
          android:verticalSpacing="2dp" />
</LinearLayout>

It has a GridView with 3 columns. You can specify as much as you want. The last xml file is the custom.xml which holds a ImageView and TextView for every grid item. The custom.xml looks like this:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:orientation="vertical"
      android:padding="5dp" >

      <ImageView
           android:id="@+id/grid_item_image"
           android:layout_width="50dp"
           android:layout_height="50dp"
           android:layout_marginRight="10dp"
           android:src="@drawable/ic_launcher" >
      </ImageView>

      <TextView
           android:id="@+id/grid_item_label"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:layout_marginTop="5dp"
           android:textColor="@android:color/white"
           android:textSize="15sp" >
      </TextView>
</LinearLayout>

The following are the class files we require. The first file is the MainActivity.class file which looks like below:

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;

import com.viewpagerindicator.PagerIndicator;

public class MainActivity extends FragmentActivity {

 public PagerIndicator mIndicator;
 private ViewPager awesomePager;
 private PagerAdapter pm;

 ArrayList codeCategory;

 String deviceNames[] = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
   "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W",
   "X", "Y", "Z" };

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  awesomePager = (ViewPager) findViewById(R.id.pager);
  mIndicator = (PagerIndicator) findViewById(R.id.pagerIndicator);

  ArrayList a = new ArrayList();

  Category m = new Category();
  for (int i = 0; i < deviceNames.length; i++) {
   a.add(i, deviceNames[i]);
   m.name = a.get(i);
  }

  codeCategory = new ArrayList();
  codeCategory.add(m);

  Iterator it = a.iterator();

  List gridFragments = new ArrayList();
  it = a.iterator();

  int i = 0;
  while (it.hasNext()) {
   ArrayList itmLst = new ArrayList();

   GridItems itm = new GridItems(0, it.next());
   itmLst.add(itm);
   i = i + 1;

   if (it.hasNext()) {
    GridItems itm1 = new GridItems(1, it.next());
    itmLst.add(itm1);
    i = i + 1;
   }

   if (it.hasNext()) {
    GridItems itm2 = new GridItems(2, it.next());
    itmLst.add(itm2);
    i = i + 1;
   }

   if (it.hasNext()) {
    GridItems itm3 = new GridItems(3, it.next());
    itmLst.add(itm3);
    i = i + 1;
   }

   if (it.hasNext()) {
    GridItems itm4 = new GridItems(4, it.next());
    itmLst.add(itm4);
    i = i + 1;
   }

   if (it.hasNext()) {
    GridItems itm5 = new GridItems(5, it.next());
    itmLst.add(itm5);
    i = i + 1;
   }

   if (it.hasNext()) {
    GridItems itm6 = new GridItems(6, it.next());
    itmLst.add(itm6);
    i = i + 1;
   }

   if (it.hasNext()) {
    GridItems itm7 = new GridItems(7, it.next());
    itmLst.add(itm7);
    i = i + 1;
   }

   if (it.hasNext()) {
    GridItems itm8 = new GridItems(8, it.next());
    itmLst.add(itm8);
    i = i + 1;
   }

   GridItems[] gp = {};
   GridItems[] gridPage = itmLst.toArray(gp);
   gridFragments.add(new GridFragment(gridPage, MainActivity.this));
  }

  pm = new PagerAdapter(getSupportFragmentManager(), gridFragments);
  awesomePager.setAdapter(pm);
  mIndicator.setViewPager(awesomePager);

 }

 private class PagerAdapter extends FragmentStatePagerAdapter {
  private List fragments;

  public PagerAdapter(FragmentManager fm, List fragments) {
   super(fm);
   this.fragments = fragments;
  }

  @Override
  public Fragment getItem(int position) {
   return this.fragments.get(position);
  }

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

As you can see we have to create objects of PagerIndicator, ViewPager & PagerAdapter.
The PagerIndicator to indicate the current page
The ViewPager is just another view like any other view. We will set the PagerAdapter to it.

Another important class is GridFragment class which will add our gridview to our layout. It looks as shown below:

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;

@SuppressLint("ValidFragment")
public class GridFragment extends Fragment {

 private GridView mGridView;
 private GridAdapter mGridAdapter;
 GridItems[] gridItems = {};
 private Activity activity;

 public GridFragment(GridItems[] gridItems, Activity activity) {
  this.gridItems = gridItems;
  this.activity = activity;
 }

 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
   Bundle savedInstanceState) {
  View view;
  view = inflater.inflate(R.layout.grid, container, false);
  mGridView = (GridView) view.findViewById(R.id.gridView);
  return view;
 }

 @Override
 public void onActivityCreated(Bundle savedInstanceState) {
  super.onActivityCreated(savedInstanceState);

  if (activity != null) {

   mGridAdapter = new GridAdapter(activity, gridItems);
   if (mGridView != null) {
    mGridView.setAdapter(mGridAdapter);
   }

   mGridView.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView parent, View view,
      int position, long id) {
     onGridItemClick((GridView) parent, view, position, id);
    }
   });
  }
 }

 public void onGridItemClick(GridView g, View v, int position, long id) {
  Toast.makeText(
    activity,
    "Position Clicked: - " + position + " & " + "Text is: - "
      + gridItems[position].title, Toast.LENGTH_LONG).show();
  Log.e("TAG", "POSITION CLICKED " + position);
 }
}

Here we have inflated our grid.xml and set adapter to the gridview. Also to check which item in the gridview was clicked we have used the setOnItemClickListener method. Next is the GridAdapter class to set the adapter to GridView. It looks as shown below:

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class GridAdapter extends BaseAdapter {

 Context context;
 int images[] = { R.drawable.ic_launcher, R.drawable.ios,
   R.drawable.windows, R.drawable.ic_launcher, R.drawable.ios,
   R.drawable.windows, R.drawable.ic_launcher, R.drawable.ios,
   R.drawable.windows };

 public class ViewHolder {
  public ImageView imageView;
  public TextView textTitle;
 }

 private GridItems[] items;
 private LayoutInflater mInflater;

 public GridAdapter(Context context, GridItems[] locations) {

  mInflater = (LayoutInflater) context
    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  this.context = context;
  items = locations;

 }

 public GridItems[] getItems() {
  return items;
 }

 public void setItems(GridItems[] items) {
  this.items = items;
 }

 @Override
 public int getCount() {
  if (items != null) {
   return items.length;
  }
  return 0;
 }

 @Override
 public void notifyDataSetChanged() {
  super.notifyDataSetChanged();
 }

 @Override
 public Object getItem(int position) {
  if (items != null && position >= 0 && position < getCount()) {
   return items[position];
  }
  return null;
 }

 @Override
 public long getItemId(int position) {
  if (items != null && position >= 0 && position < getCount()) {
   return items[position].id;
  }
  return 0;
 }

 public void setItemsList(GridItems[] locations) {
  this.items = locations;
 }

 @Override
 public View getView(int position, View convertView, ViewGroup parent) {

  View view = convertView;
  ViewHolder viewHolder;

  if (view == null) {

   view = mInflater.inflate(R.layout.custom, parent, false);
   viewHolder = new ViewHolder();
   viewHolder.imageView = (ImageView) view
     .findViewById(R.id.grid_item_image);
   viewHolder.textTitle = (TextView) view
     .findViewById(R.id.grid_item_label);
   view.setTag(viewHolder);
  } else {
   viewHolder = (ViewHolder) view.getTag();
  }

  GridItems gridItems = items[position];
  setCatImage(position, viewHolder, gridItems.title);
  return view;
 }

 private void setCatImage(int pos, ViewHolder viewHolder, String catTitle) {
  viewHolder.imageView.setImageResource(images[pos]);
  viewHolder.textTitle.setText(catTitle);
 }
} 
Below are the other GetterSetter classes. First is the GridItems.class
public class GridItems {

 public int id;
 public String title;

 public GridItems(int id, String address) {
  this.id = id;
  this.title = address;
 }
}

The next is the Category.class

public class Category {
 int id;
 String name;

 public Category(int id, String name) {
  this.id = id;
  this.name = name;
 }

 public Category() {
 }

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }
}

79 comments:

  1. Thanks for your blog, I too working on this type page indicator, I have used your codes but I have getting this exception
    11-07 12:29:44.102: E/AndroidRuntime(17301): FATAL EXCEPTION: main
    11-07 12:29:44.102: E/AndroidRuntime(17301): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.exam.gridview/com.exam.gridview.MainActivity}: android.view.InflateException: Binary XML file line #14: Class is not a View com.exam.gridview.PageIndicator
    11-07 12:29:44.102: E/AndroidRuntime(17301): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
    11-07 12:29:44.102: E/AndroidRuntime(17301): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2211)
    11-07 12:29:44.102: E/AndroidRuntime(17301): at android.app.ActivityThread.access$600(ActivityThread.java:149)
    11-07 12:29:44.102: E/AndroidRuntime(17301): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1300)
    11-07 12:29:44.102: E/AndroidRuntime(17301): at android.os.Handler.dispatchMessage(Handler.java:99)
    11-07 12:29:44.102: E/AndroidRuntime(17301): at android.os.Looper.loop(Looper.java:153)
    11-07 12:29:44.102: E/AndroidRuntime(17301): at android.app.ActivityThread.main(ActivityThread.java:5086)
    11-07 12:29:44.102: E/AndroidRuntime(17301): at java.lang.reflect.Method.invokeNative(Native Method)
    11-07 12:29:44.102: E/AndroidRuntime(17301): at java.lang.reflect.Method.invoke(Method.java:511)
    11-07 12:29:44.102: E/AndroidRuntime(17301): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:821)
    11-07 12:29:44.102: E/AndroidRuntime(17301): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
    11-07 12:29:44.102: E/AndroidRuntime(17301): at dalvik.system.NativeStart.main(Native Method)
    11-07 12:29:44.102: E/AndroidRuntime(17301): Caused by: android.view.InflateException: Binary XML file line #14: Class is not a View com.exam.gridview.PageIndicator
    11-07 12:29:44.102: E/AndroidRuntime(17301): at android.view.LayoutInflater.createView(LayoutInflater.java:604)
    11-07 12:29:44.102: E/AndroidRuntime(17301): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:687)
    11-07 12:29:44.102: E/AndroidRuntime(17301): at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
    11-07 12:29:44.102: E/AndroidRuntime(17301): at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
    11-07 12:29:44.102: E/AndroidRuntime(17301): at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
    11-07 12:29:44.102: E/AndroidRuntime(17301): at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
    11-07 12:29:44.102: E/AndroidRuntime(17301): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:258)
    11-07 12:29:44.102: E/AndroidRuntime(17301): at android.app.Activity.setContentView(Activity.java:1867)
    11-07 12:29:44.102: E/AndroidRuntime(17301): at com.exam.gridview.MainActivity.onCreate(MainActivity.java:29)
    11-07 12:29:44.102: E/AndroidRuntime(17301): at android.app.Activity.performCreate(Activity.java:5020)
    11-07 12:29:44.102: E/AndroidRuntime(17301): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
    11-07 12:29:44.102: E/AndroidRuntime(17301): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
    11-07 12:29:44.102: E/AndroidRuntime(17301): ... 11 more
    11-07 12:29:44.102: E/AndroidRuntime(17301): Caused by: java.lang.ClassCastException: com.exam.gridview.PageIndicator cannot be cast to android.view.View
    11-07 12:29:44.102: E/AndroidRuntime(17301): at java.lang.Class.asSubclass(Class.java:1380)
    11-07 12:29:44.102: E/AndroidRuntime(17301): at android.view.LayoutInflater.createView(LayoutInflater.java:552)
    11-07 12:29:44.102: E/AndroidRuntime(17301): ... 22 more

    please tell me the solution.

    ReplyDelete
  2. Nagesh can you tell me when do you get this exception???
    or how can i replicate it because it is running fine with me..

    ReplyDelete
    Replies
    1. when I am going to launch the application its always crash. I think rather using PageIndicator, I have to use CirclePageIndicator. here log cat saying that "Caused by: java.lang.ClassCastException: com.exam.gridview.PageIndicator cannot be cast to android.view.View".. so I am thinking to use CirclePageIndicator.

      Delete
    2. Hey Shrikant Sonar if you have overall project bundle please send me....

      Delete
  3. Hi Nagesh, in order to make the above code executable you need to make a change in activity_main.xml, as from the error log says it cannot find PagerIndicator Class from the library so instead of that class try to use CirclePageIndicator class
    Basically change your line no 14 of the xml
    from com.viewpagerindicator.PagerIndicator to

    com.viewpagerindicator.CirclePageIndicator
    .

    Hope this solves your issue.

    ReplyDelete
  4. hello sir,

    i refer ur code its very usable..i am trying to develop a magazine application for that i had use a view pager for sliding the pages..now i wanted to add a sliding pages at the bottom of layout like we were seen in digital magazines...but i couldnt understand how it will be done..can you suggest me a code..please give me a guidance..i am awating..my email id is[rajashri.thorat73@gmail.com]

    Thank you

    ReplyDelete
  5. Hi,
    I am a beginner, and working for my app. This function(Gridview with indicator) is what I want to add into my app, but I'm not be able to reuse your code, coz I don't understand some of the code, I'd greatly appreciate for your help!!
    please contact me via caseofr@gmail.com

    ReplyDelete
  6. please.
    how to add images dynamically as deviceNames

    ReplyDelete
  7. Your code is working fine but, when orientation changes it crashes. As Fragment doesnot contain empty constructor. How to handle it, without placing android:configChanges="orientation|screenSize|keyboardHidden" in Manifest.xml

    ReplyDelete
  8. I solved this issue by keeping fragment.setRetainInstance(true);

    ReplyDelete
  9. Thank you for blog, i am facing this error, please help me out.

    java.lang.NullPointerException
    02-10 11:41:09.041: E/AndroidRuntime(30139): at android.support.v4.app.FragmentStatePagerAdapter.instantiateItem(FragmentStatePagerAdapter.java:116)
    02-10 11:41:09.041: E/AndroidRuntime(30139): at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:649)
    02-10 11:41:09.041: E/AndroidRuntime(30139): at android.support.v4.view.ViewPager.populate(ViewPager.java:783)
    02-10 11:41:09.041: E/AndroidRuntime(30139): at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1016)
    02-10 11:41:09.041: E/AndroidRuntime(30139): at android.view.View.measure(View.java:15524)
    02-10 11:41:09.041: E/AndroidRuntime(30139): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5109)
    02-10 11:41:09.041: E/AndroidRuntime(30139): at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1396)
    02-10 11:41:09.041: E/AndroidRuntime(30139): at android.widget.LinearLayout.measureVertical(LinearLayout.java:681)
    02-10 11:41:09.041: E/AndroidRuntime(30139): at android.widget.LinearLayout.onMeasure(LinearLayout.java:574)
    02-10 11:41:09.041: E/AndroidRuntime(30139): at android.view.View.measure(View.java:15524)
    02-10 11:41:09.041: E/AndroidRuntime(30139): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5109)
    02-10 11:41:09.041: E/AndroidRuntime(30139): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
    02-10 11:41:09.041: E/AndroidRuntime(30139): at android.view.View.measure(View.java:15524)
    02-10 11:41:09.041: E/AndroidRuntime(30139): at android.widget.LinearLayout.measureVertical(LinearLayout.java:833)
    02-10 11:41:09.041: E/AndroidRuntime(30139): at android.widget.LinearLayout.onMeasure(LinearLayout.java:574)
    02-10 11:41:09.041: E/AndroidRuntime(30139): at android.view.View.measure(View.java:15524)
    02-10 11:41:09.041: E/AndroidRuntime(30139): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5109)
    02-10 11:41:09.041: E/AndroidRuntime(30139): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
    02-10 11:41:09.041: E/AndroidRuntime(30139): at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2397)
    02-10 11:41:09.041: E/AndroidRuntime(30139): at android.view.View.measure(View.java:15524)
    02-10 11:41:09.041: E/AndroidRuntime(30139): at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1986)
    02-10 11:41:09.041: E/AndroidRuntime(30139): at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1227)
    02-10 11:41:09.041: E/AndroidRuntime(30139): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1400)
    02-10 11:41:09.041: E/AndroidRuntime(30139): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1120)
    02-10 11:41:09.041: E/AndroidRuntime(30139): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4604)

    ReplyDelete
    Replies
    1. I am facing problem here, its asking for gridfragment return type.
      public Fragment getItem(int arg0) {
      return this.fragments.get(arg0);
      }

      Delete
    2. hey archana,
      can you please check your imports.
      They should be android.support.v4 throughout all the classes.
      I guess that is the issue.
      Please let me know if this solves it.

      Delete
  10. Replies
    1. I am facing problem here, its asking for gridfragment return type.
      public Fragment getItem(int arg0) {
      return this.fragments.get(arg0);
      }

      how to solve
      have you any idea ?

      Delete
  11. This is the perfect which I am looking for. thanks for this best example..
    I got some error when app is on resume mode.. Some time not every time.. My log cat is here,
    05-05 10:29:20.744: W/dalvikvm(8427): threadid=1: thread exiting with uncaught exception (group=0x41020258)
    05-05 10:29:20.787: E/AndroidRuntime(8427): FATAL EXCEPTION: main
    05-05 10:29:20.787: E/AndroidRuntime(8427): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.grid_viewpager/com.example.grid_viewpager.MainActivity}: android.support.v4.app.Fragment$InstantiationException: Unable to instantiate fragment com.example.grid_viewpager.GridFragment: make sure class name exists, is public, and has an empty constructor that is public
    05-05 10:29:20.787: E/AndroidRuntime(8427): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2077)
    05-05 10:29:20.787: E/AndroidRuntime(8427): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2104)
    05-05 10:29:20.787: E/AndroidRuntime(8427): at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3510)
    05-05 10:29:20.787: E/AndroidRuntime(8427): at android.app.ActivityThread.access$700(ActivityThread.java:134)
    05-05 10:29:20.787: E/AndroidRuntime(8427): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1251)
    05-05 10:29:20.787: E/AndroidRuntime(8427): at android.os.Handler.dispatchMessage(Handler.java:99)
    05-05 10:29:20.787: E/AndroidRuntime(8427): at android.os.Looper.loop(Looper.java:154)
    05-05 10:29:20.787: E/AndroidRuntime(8427): at android.app.ActivityThread.main(ActivityThread.java:4624)
    05-05 10:29:20.787: E/AndroidRuntime(8427): at java.lang.reflect.Method.invokeNative(Native Method)
    05-05 10:29:20.787: E/AndroidRuntime(8427): at java.lang.reflect.Method.invoke(Method.java:511)
    05-05 10:29:20.787: E/AndroidRuntime(8427): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:809)
    05-05 10:29:20.787: E/AndroidRuntime(8427): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
    05-05 10:29:20.787: E/AndroidRuntime(8427): at dalvik.system.NativeStart.main(Native Method)
    05-05 10:29:20.787: E/AndroidRuntime(8427): Caused by: android.support.v4.app.Fragment$InstantiationException: Unable to instantiate fragment com.example.grid_viewpager.GridFragment: make sure class name exists, is public, and has an empty constructor that is public
    05-05 10:29:20.787: E/AndroidRuntime(8427): at android.support.v4.app.Fragment.instantiate(Fragment.java:395)
    05-05 10:29:20.787: E/AndroidRuntime(8427): at android.support.v4.app.FragmentState.instantiate(Fragment.java:96)
    05-05 10:29:20.787: E/AndroidRuntime(8427): at android.support.v4.app.FragmentManagerImpl.restoreAllState(FragmentManager.java:1726)
    05-05 10:29:20.787: E/AndroidRuntime(8427): at android.support.v4.app.FragmentActivity.onCreate(FragmentActivity.java:198)
    05-05 10:29:20.787: E/AndroidRuntime(8427): at com.example.grid_viewpager.MainActivity.onCreate(MainActivity.java:30)
    05-05 10:29:20.787: E/AndroidRuntime(8427): at android.app.Activity.performCreate(Activity.java:4479)
    05-05 10:29:20.787: E/AndroidRuntime(8427): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1050)
    05-05 10:29:20.787: E/AndroidRuntime(8427): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2041)
    05-05 10:29:20.787: E/AndroidRuntime(8427): ... 12 more
    05-05 10:29:20.787: E/AndroidRuntime(8427): Caused by: java.lang.InstantiationException: can't instantiate class com.example.grid_viewpager.GridFragment; no empty constructor
    05-05 10:29:20.787: E/AndroidRuntime(8427): at java.lang.Class.newInstanceImpl(Native Method)
    05-05 10:29:20.787: E/AndroidRuntime(8427): at java.lang.Class.newInstance(Class.java:1319)
    05-05 10:29:20.787: E/AndroidRuntime(8427): at android.support.v4.app.Fragment.instantiate(Fragment.java:384)
    05-05 10:29:20.787: E/AndroidRuntime(8427): ... 19 more

    ReplyDelete
    Replies
    1. add a blank constructor to GridFragment class as below.

      public GridFragment () {

      }

      Hope this resolves your issue.

      Delete
  12. I am facing problem here, its asking for gridfragment return type.
    public Fragment getItem(int arg0) {
    return this.fragments.get(arg0);
    }

    how to solve
    have you any idea ?

    ReplyDelete
    Replies
    1. Hi mayank,
      As posted in one of the above replies,
      can you please check your imports.
      They should be android.support.v4 throughout all the classes.
      I guess that is the issue.
      Please let me know if this solves it. Or the steps to reproduce the error.

      Delete
    2. my issue is not resolve ..
      n i import android.support.v4.*; in all the classes
      same issues.

      Delete
    3. plz check if you are passing List to PagerAdapter class. Maybe it is null so you are getting the exception. Also let me know the steps to reproduce the crash.

      Delete
  13. Can we load images from url using this code?

    ReplyDelete
  14. type mis match: cannot convert from GridFragment to Fragment
    @Override
    public Fragment getItem(int arg0) {


    return this.fragments.get(arg0);

    }

    ReplyDelete
  15. I found this exception

    @Override
    public Fragment getItem(int arg0) {
    return this.fragments.get(arg0);}


    can' t create new class of gridfragments. Create static class gridfragments inside the mainactivity.

    ReplyDelete
  16. Hi Sir,
    Pls can u mail me the full project saravananchandru7@gmail.com
    Thanks in advance...!!!

    ReplyDelete
  17. For those have some problems on importing Library (including me)
    May try just copy the required classes & xmls to your project
    Its work to me
    Really an awesome example!!
    thanks a lot!!

    ReplyDelete
  18. How we can use "Android-ViewPagerIndicator" to my project and which folder i must import to , please answer its critical for me

    ReplyDelete
  19. Hi

    when i change orientation it crashes. How we can fixed it?

    ReplyDelete
  20. How to do this as dynamic.I'm gettting all the gridview datas from backend but iam geting first nine items in a gridview instead iam getting all the datas in a horizontall view.How to overcome this.Any idea

    ReplyDelete
  21. Thank you for taking the time to make the post.

    I'm finding a lot of typos in the code as posted, but no mention in any of the comments. I wonder if you've somehow posted an incomplete version of the code. I can probably work through the typos, but you may want to take a look. If there is a up-to-date version, I'd love to see it.

    Some examples: using string instead of String. Using category instead of Category. Using PagerIndicator instead of PageIndicator. (The last may reflect a change in the ViewPagerIndicator library).

    In addition, none of the graphics are available. This my not be resolvable, but perhaps you meant to include links for them.

    ReplyDelete
  22. This comment has been removed by the author.

    ReplyDelete
  23. Great Article… I love to read your articles because your writing style is too good, its is very very helpful for all of us and I never get bored while reading your article because, they are becomes a more and more interesting from the starting lines until the end.


    rpa Training in Chennai

    rpa Training in bangalore

    rpa Training in pune

    blueprism Training in Chennai

    blueprism Training in bangalore

    blueprism Training in pune

    rpa online training

    ReplyDelete
  24. This comment has been removed by the author.

    ReplyDelete
  25. It's interesting that many of the bloggers to helped clarify a few things for me as well as giving.Most of ideas can be nice content.The people to give them a good shake to get your point and across the command
    Data Science Training in Chennai
    Data science training in bangalore
    Data science online training
    Data science training in pune
    Data science training in kalyan nagar
    selenium training in chennai

    ReplyDelete
  26. I was recommended this web site by means of my cousin. I am now not certain whether this post is written through him as nobody else recognise such precise about my difficulty. You're amazing! Thank you!

    java training in tambaram | java training in velachery

    java training in omr | oracle training in chennai

    java training in annanagar | java training in chennai

    ReplyDelete
  27. I prefer to study this kind of material. Nicely written information in this post, the quality of content is fine and the conclusion is lovely. Things are very open and intensely clear explanation of issues
    python training in tambaram
    python training in annanagar
    python training in OMR
    python training in chennai

    ReplyDelete
  28. Good Post, I am a big believer in posting comments on sites to let the blog writers know that they ve added something advantageous to the world wide web.
    python training in tambaram
    python training in annanagar
    python training in OMR
    python training in chennai

    ReplyDelete
  29. Inspiring writings and I greatly admired what you have to say , I hope you continue to provide new ideas for us all and greetings success always for you..Keep update more information..

    rpa training in Chennai | best rpa training in chennai

    rpa training in pune

    rpa online training | rpa training in bangalore

    ReplyDelete
  30. It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...
    Blueprism online training

    Blue Prism Training in Pune

    Blueprism training in tambaram

    ReplyDelete
  31. Excellant post!!!. The strategy you have posted on this technology helped me to get into the next level and had lot of information in it.
    Blueprism training in annanagar

    Blueprism training in velachery

    Blueprism training in marathahalli

    ReplyDelete
  32. Thank you for allowing me to read it, welcome to the next in a recent article. And thanks for sharing the nice article, keep posting or updating news article.
    angularjs

    Training in chennai


    angularjs-Training in chennai

    angularjs Training in chennai

    angularjs-Training in tambaram

    angularjs-Training in sholinganallur

    ReplyDelete
  33. Some us know all relating to the compelling medium you present powerful steps on this blog and therefore strongly encourage contribution from other ones on this subject while our own child is truly discovering a great deal. Have fun with the remaining portion of the year.
    python training in rajajinagar
    Python training in btm
    Python training in usa

    ReplyDelete
  34. I am really happy with your blog because your article is very unique and powerful for new reader.
    Click here:
    selenium training in chennai
    selenium training in bangalore
    selenium training in Pune
    selenium training in pune
    Selenium Online Training



    https://sapnagiyanwani.blogspot.com/2013/09/adrotator-control-in-aspnet.html

    ReplyDelete
  35. I am really happy with your blog because your article is very unique and powerful for new reader.
    Click here:
    selenium training in chennai
    selenium training in bangalore
    selenium training in Pune
    selenium training in pune
    Selenium Online Training

    http://simpleandroidtutorials.blogspot.com/2012/06/fetching-data-from-server-and-setting.html

    ReplyDelete
  36. It is a great post. Keep sharing such kind of useful information.

    Education
    Technology

    ReplyDelete
  37. indeed, I’m just always astounded concerning the remarkable things served by you. Some four facts on this page are undeniably the most effective I’ve had.
    SOFTWARE TRAINING IN CHENNAI
    POWERBI TRAINING IN CHENNAI
    CCNA TRAINING IN CHENNAI
    ANDROID TRAINING IN CHENNAI

    ReplyDelete
  38. Very nice blog. A great and very informative post, Keep up the good work!


    Data Science Bangalore

    ReplyDelete
  39. I like viewing web sites which comprehend the price of delivering the excellent useful resource free of charge. I truly adored reading your posting. Thank you!



    DATA SCIENCE COURSE MALAYSIA

    ReplyDelete

  40. I have to search sites with relevant information on given topic and provide them to teacher our opinion and the article. I appreciate your post and look forward tomorrow.data science course in singapore

    ReplyDelete
  41. I just got to this amazing site not long ago. I was actually captured with the piece of resources you have got here. Big thumbs up for making such wonderful blog page digital marketing course in singapore

    ReplyDelete

  42. I am looking for and I love to post a comment that "The content of your post is awesome" Great work!
    love it

    ReplyDelete
  43. Just saying thanks will not just be sufficient, for the fantasti c lucidity in your writing. I will instantly grab your rss feed to stay informed of any updates.
    big data course malaysia

    ReplyDelete
  44. Really awesome blog!!! Thanks for sharing valuable information.
    Data Science Course Training in Bangalore

    ReplyDelete
  45. I read this post two times, I like it so much, please try to keep posting & Let me introduce other material that may be good for our community.

    ReplyDelete
  46. This Was An Amazing! I Haven't Seen This Type of Blog Ever! Thank you for Sharing, data scientist course in Hyderabad with placement

    ReplyDelete
  47. Extremely good content, i enjoyed alot and gain some knowledge as well.Thanks for this.
    Data Science Training in Pune

    ReplyDelete
  48. Amazing Article! I would like to thank you for the efforts you had made for writing this awesome article. This article inspired me to read more. keep it up.If you are Searching for info click on given link
    Data science course in pune

    ReplyDelete
  49. Thank you for sharing such detailed Blog. I am learning a lot from you. Visit my website to get best Information About Best IAS coaching in Mumbai
    Best IAS coaching in Mumbai
    Top IAS coaching in Mumbai

    ReplyDelete
  50. The King Casino | Ventureberg
    Discover the rise and fall of www.jtmhub.com the worrione.com king casino, ventureberg.com/ one of the world's largest https://septcasino.com/review/merit-casino/ The Casino is operated by the King Casino Group. You can

    ReplyDelete