2015-04-14 6 views
1

Я пытаюсь реализовать view pager, на мой взгляд, изображения пейджера поступают с сервера, я могу отображать и прокручивать, но когда я достигаю последнего изображения, он показывает ошибку и приложение получило аварию, следующее моего сниппета кодаjava.lang.IndexOutOfBoundsException: Invalid index 7, size is 7

public class Test_Pager extends Activity{ 


private String strtd; 
String[] imgStr; 
ImageView imageView; 
ArrayList<String> userImgArrayList; 
String[] myURLs; 


/*country list*/ 
JSONArray country_list=null; 
private ServiceHandler sh; 
private String jsonStr; 
private JSONObject jsonObj; 
private String user_img; 
private String user_pro; 
private static String PROFILE_VIEW_URL = ""; 

private static final String USER_IMG="product_images"; 


@Override 
protected void onCreate(Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.test_pagerss); 

    userImgArrayList = getIntent().getStringArrayListExtra("user_images"); 
    ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager); 
     ImageAdapter adapter = new ImageAdapter(this); 
     viewPager.setAdapter(adapter); 

    imageView = (ImageView) findViewById(R.id.full_image_view); 


    PROFILE_VIEW_URL=""; 
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
    StrictMode.setThreadPolicy(policy); 
    sh = new ServiceHandler(); 

     // Making a request to url and getting response 
     jsonStr = sh.makeServiceCall(PROFILE_VIEW_URL, ServiceHandler.GET); 

     Log.d("Response: ", "> " + jsonStr); 

    try { 
     jsonObj = new JSONObject(jsonStr); 


      /*proview_business = jsonObj.getString(PROFILE_VIEW_BUSINESS); 
      proview_subcat = jsonObj.getString(PROFILE_VIEW_SUB_CATAGORY); 
      proview_mainpro = jsonObj.getString(PROFILE_VIEW_MAINPRODUCTS); 
      proview_expr = jsonObj.getString(PROFILE_VIEW_EXPERIENCE); 
      proview_cmpname = jsonObj.getString(PROFILE_VIEW_COMPANYNAME); 
      proview_website = jsonObj.getString(PROFILE_VIEW_WEBSITE);*/ 

      // user_img=jsonObj.getString(USER_IMG); 



      user_img=jsonObj.getString(USER_IMG); 
      user_img = ""; 
      userImgArrayList = new ArrayList<String>();//declare userImgArrayList globally like ArrayList<String> userImgArrayList; 
      JSONArray picarray = jsonObj.getJSONArray(USER_IMG); 
      for(int i=0;i< picarray.length();i++) 
      { 
       user_img = picarray.getString(i); 
       userImgArrayList.add(user_img); 
       Log.d("mylog", "curent pro pic = " + user_img); 
      } 


    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 

} 
public class ImageAdapter extends PagerAdapter { 
    Context context; 
     ImageAdapter(Context context) 
    { 
    this.context=context; 
    } 
     @Override 
     public int getCount() { 
     return USER_IMG.length(); 
     } 

     @Override 
     public void destroyItem(View container, int position, Object object) { 
      ((ViewPager) container).removeView((View) object); 
     } 
    @Override 
    public boolean isViewFromObject(View view, Object object) { 
    return view == ((ImageView) object); 
    } 

    @Override 
     public Object instantiateItem(ViewGroup container, int position) { 
      ImageView imageView = new ImageView(context); 
      int padding = context.getResources().getDimensionPixelSize(
        R.dimen.activity_horizontal_margin); 
      imageView.setPadding(padding, padding, padding, padding); 
      //imageView.setScaleType(ImageView.ScaleType.FIT_CENTER); 
      //Picasso.with(context).load(userImgArrayList.get(position)).into(imageView); 
      Picasso.with(context).load(userImgArrayList.get(position)).resize(200, 200) .into(imageView); 

      /*for(int i=0; i<myURLs.length;i++) 
      { 

       try { 
        url = new URL(myURLs[i]); 
       } catch (MalformedURLException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 

       try { 
        bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream()); 
       } catch (IOException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
       imageView.setImageBitmap(bmp); 
      } 
      */ 
      // imageView.setImageURI(Uri.parse(imgStr[position])); 
      ((ViewPager) container).addView(imageView, 0); 
      return imageView; 
     } 
    } 

    } 

Myxml

 <RelativeLayout 
     android:layout_height="wrap_content" 
     android:layout_width="wrap_content" 
     android:background="@android:color/white" 
     xmlns:android="http://schemas.android.com/apk/res/android"> 







     <ScrollView 
      android:layout_height="match_parent" 
      android:layout_width="match_parent" 
      android:layout_below="@+id/lnr" 
      android:fillViewport="true" 

       > 

      <LinearLayout 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      android:orientation="vertical" > 

      <LinearLayout 
       android:layout_height="wrap_content" 
       android:layout_width="wrap_content" 
      android:orientation="vertical" 
       > 
      <android.support.v4.view.ViewPager 
     android:id="@+id/view_pager" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" /> 

<ImageView android:id="@+id/full_image_view" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content"/></LinearLayout> 

<LinearLayout 
    android:layout_height="wrap_content" 
    android:layout_width="fill_parent" 
    android:orientation="vertical" 
    android:background="@drawable/secondpart" 
    android:layout_marginLeft="5dp" 
    android:layout_marginRight="5dp" 
    android:layout_marginTop="5dp" 
    > 
     <TableLayout 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:shrinkColumns="*" android:stretchColumns="*" > 
     <TableRow 
         android:layout_height="wrap_content" 
         android:layout_width="wrap_content" 
         android:gravity="center_horizontal"> 

     <TextView 
      android:layout_height="wrap_content" 
      android:layout_width="fill_parent" 
      android:text="Product Name" 
      android:layout_marginLeft="5dp" 
      android:textColor="@android:color/black" 
      /> 


     <TextView 
      android:layout_height="wrap_content" 
      android:layout_width="fill_parent" 
      android:id="@+id/txtageprofile" 

      android:textColor="@android:color/black" 
      android:layout_marginLeft="5dp" 
      /></TableRow> 
     <TableRow 
         android:layout_height="wrap_content" 
         android:layout_width="wrap_content" 
         android:gravity="center_horizontal" 
         android:paddingTop="5dp" 
         > 
     <TextView 
      android:layout_height="wrap_content" 
      android:layout_width="fill_parent" 
      android:text="Code" 
      android:layout_marginLeft="5dp" 
      android:textColor="@android:color/black" 
      /> 


     <TextView 
      android:layout_height="wrap_content" 
      android:layout_width="fill_parent" 

      android:id="@+id/txtheightprofile" 

      android:textColor="@android:color/black" 
      android:layout_marginLeft="5dp" 
      /></TableRow> 
     <TableRow 
         android:layout_height="wrap_content" 
         android:layout_width="wrap_content" 
         android:gravity="center_horizontal" 
         android:paddingTop="5dp" 
         > 
     <TextView 
      android:layout_height="wrap_content" 
      android:layout_width="fill_parent" 
      android:text="Purchase Rate" 
      android:layout_marginLeft="5dp" 
      android:textColor="@android:color/black" 
      /> 


     <TextView 
      android:layout_height="wrap_content" 
      android:layout_width="fill_parent" 

      android:id="@+id/txtmrgprofile" 

      android:textColor="@android:color/black" 
      android:layout_marginLeft="5dp" 
      /></TableRow> 
      <TableRow 
         android:layout_height="wrap_content" 
         android:layout_width="wrap_content" 
         android:gravity="center_horizontal" 
         android:paddingTop="5dp"> 
     <TextView 
      android:layout_height="wrap_content" 
      android:layout_width="fill_parent" 
      android:text="Weight" 
      android:layout_marginLeft="5dp" 
      android:textColor="@android:color/black" 
      /> 

     <TextView 
      android:layout_height="wrap_content" 
      android:layout_width="fill_parent" 

      android:id="@+id/txtworkingprofile" 

      android:textColor="@android:color/black" 
      android:layout_marginLeft="5dp" 
      /></TableRow> 
      <TableRow 
         android:layout_height="wrap_content" 
         android:layout_width="wrap_content" 
         android:gravity="center_horizontal" 
         android:paddingTop="5dp" 
         > 
     <TextView 
      android:layout_height="wrap_content" 
      android:layout_width="fill_parent" 
      android:text="Sales Rate" 
      android:layout_marginLeft="5dp" 
      android:textColor="@android:color/black" 
      /> 

     <TextView 
      android:layout_height="wrap_content" 
      android:layout_width="fill_parent" 
      android:id="@+id/txtplaceprofile" 
      android:textColor="@android:color/black" 
      android:layout_marginLeft="5dp" 
      /></TableRow> 
      </TableLayout> 
      </LinearLayout> 
      <LinearLayout 
    android:layout_height="wrap_content" 
    android:layout_width="fill_parent" 
    android:orientation="vertical" 
    android:background="@drawable/secondpart" 
    android:layout_marginLeft="5dp" 
    android:layout_marginRight="5dp" 
    android:layout_marginTop="5dp" 
    > 
      <TextView 
      android:layout_height="wrap_content" 
      android:layout_width="wrap_content" 
      android:layout_gravity="center_vertical|right" 

      android:id="@+id/txteatprofile" 
      android:textColor="@android:color/black" 
      android:layout_marginLeft="5dp" 
      android:layout_marginRight="5dp" 
      /> 
      </LinearLayout> 


     </LinearLayout> 
     </ScrollView> 
     </RelativeLayout> 
+1

USER_IMG.length() возвращает длину строки, вместо того, чтобы использовать массив изображений для выборки отсчет –

ответ

0

USER_IMG.length(); возвращает длину String (количества символов в "product_images"). Вместо этого вы должны вернуть размер набора данных. Изменение

@Override 
public int getCount() { 
     return USER_IMG.length(); 
} 

к

@Override 
public int getCount() { 
     if (userImgArrayList == null) { 
     return 0; 
     } 
     return userImgArrayList.size(); 
} 
+0

он показывает java.lang.IllegalStateException : PagerAdapter приложения изменил содержимое адаптера, не вызывая PagerAdapter # notifyDataSetChanged! Ожидаемое количество элементов адаптера: 0, найдено: 7 Идентификатор пейджера: com.example.tab_with_list: id/view_pager Класс пейджера: класс android.support.v4.view.ViewPager Проблемный адаптер: класс com.example.tab_with_list.Test_Pager $ ImageAdapter –

+0

call 'viewPager.notifyDataSetChanged();' ** после ** цикла for, который заполняет 'userImgArrayList' – Blackbelt

+0

, он говорит, что метод notifyDataSetChanged() не определен для типа ViewPager ... i добавлен после цикла for..for (int i = 0; i

0

изменить свой GetCount() для

@Override 
    public int getCount() { 
    int count =0 
    if (userImgArrayList != null) { 
    count=userImgArrayList.size(); 
    } 
    return count; 

}

А также добавить notifyDataSetChanged после заполнения ArrayList, как это ..

for(int i=0;i< picarray.length();i++) 
      { 
       user_img = picarray.getString(i); 
       userImgArrayList.add(user_img); 
       Log.d("mylog", "curent pro pic = " + user_img); 
      } 
adapter.notifyDataSetChanged() 
+0

У меня есть ответ ... я проголосую –

0

заменить,

Picasso.with(context).load(userImgArrayList.get(position)).resize(200, 200) .into(imageView);

с,

try{Picasso.with(context).load(userImgArrayList.get(position)).resize(200, 200) .into(imageView);}catch(Exception e){ 

e.printStackTrace();} 
Смежные вопросы