由于致命异常而调用方法时应用程序崩溃

时间:2016-07-16 12:47:14

标签: android indexoutofboundsexception fatal-error

我的代码严重问题!!由于 IndexOutOfBoundException

,它会因很多错误而崩溃

我创建了一个显示来自params的数据的活动......

现在,当我尝试运行我的应用程序(运行该活动)时,它说:

07-16 17:14:42.483 10250-10250/ir.homa E/AndroidRuntime: FATAL EXCEPTION: main
                                                         Process: ir.homa, PID: 10250
                                                         java.lang.RuntimeException: Unable to start activity ComponentInfo{ir.homa/ir.homa.HotelPageAdapter}: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
                                                             at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2658)
                                                             at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2723)
                                                             at android.app.ActivityThread.access$900(ActivityThread.java:172)
                                                             at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1422)
                                                             at android.os.Handler.dispatchMessage(Handler.java:102)
                                                             at android.os.Looper.loop(Looper.java:145)
                                                             at android.app.ActivityThread.main(ActivityThread.java:5832)
                                                             at java.lang.reflect.Method.invoke(Native Method)
                                                             at java.lang.reflect.Method.invoke(Method.java:372)
                                                             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
                                                          Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
                                                             at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
                                                             at java.util.ArrayList.get(ArrayList.java:308)
                                                             at ir.homa.HotelPageAdapter.prepareHotels(HotelPageAdapter.java:100)
                                                             at ir.homa.HotelPageAdapter.onCreate(HotelPageAdapter.java:61)
                                                             at android.app.Activity.performCreate(Activity.java:6221)
                                                             at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
                                                             at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2611)
                                                             at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2723) 
                                                             at android.app.ActivityThread.access$900(ActivityThread.java:172) 
                                                             at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1422) 
                                                             at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                             at android.os.Looper.loop(Looper.java:145) 
                                                             at android.app.ActivityThread.main(ActivityThread.java:5832) 
                                                             at java.lang.reflect.Method.invoke(Native Method) 
                                                             at java.lang.reflect.Method.invoke(Method.java:372) 
                                                             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399) 
                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)  07-16 17:14:42.513 4085-12738/? E/android.os.Debug: ro.product_ship = true 07-16 17:14:42.513 4085-12738/? E/android.os.Debug: ro.debug_level = 0x4f4c

我认为,因为 preparehotel(),所以应用程序每次都会崩溃......

这是我的活动代码:

package ir.homa;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;

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

/**
 * Created by SMQ on 7/13/2016.
 */
public class HotelPageAdapter extends Activity {
    private Context mContext;
    private RecyclerView recyclerView;
    private HotelListAdapter adapter;
    private List<HotelList> hotelList;

    public String name1;
    public int thumbnail1;
    public int count1;
    public int position1;

    public HotelPageAdapter() {
    }

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

        Bundle extras =  getIntent().getExtras();
         name1 = extras.getString("name");
         thumbnail1 = extras.getInt("thumbnail");
         count1 = extras.getInt("count");
         position1 = extras.getInt("position1");

        if ( extras != null ) {
            Log.i("LOG", String.valueOf(thumbnail1));
            Log.i("LOG", String.valueOf(count1));
            Log.i("LOG", String.valueOf(position1));
            Log.i("LOG", name1);
        }


        hotelList = new ArrayList<>();
        adapter = new HotelListAdapter(this, hotelList);
        final LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);

        prepareHotels();

        class MyViewHolder extends RecyclerView.ViewHolder {

            public TextView name, count;
            public ImageView thumbnail;


            public MyViewHolder(View view) {
                super(view);

                count = (TextView) view.findViewById(R.id.count1);
                name = (TextView) view.findViewById(R.id.title1);
                thumbnail = (ImageView) view.findViewById(R.id.thumbnail1);

            }

        }
    }

    private int dpToPx(int dp) {
        Resources r = getResources();
        return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
    }

    public void onBindViewHolder(final HotelListAdapter.MyViewHolder holder, int position) {

        this.position1 = position;
        final HotelList hotel = hotelList.get(position);

        holder.title.setText(name1);
        holder.count.setText(count1 + " اتاق");

        Glide.with(mContext).load(thumbnail1).into(holder.thumbnail);
    }

    private void prepareHotels() {


        final HotelList hotel = hotelList.get(position1);

        int[] covers = new int[] {


                R.mipmap.bandar_homa,
                R.mipmap.mashhad_homa1,
                R.mipmap.mashhad_homa,
                R.mipmap.shiraz_homa,
                R.mipmap.tehran_homa,


        };
        HotelList B = new HotelList( name1 , count1, covers[thumbnail1]);
        hotelList.add(B);
        adapter.notifyDataSetChanged();


    }
    /**
     * RecyclerView item decoration - give equal margin around grid item
     */
    public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {

        private int spanCount;
        private int spacing;
        private boolean includeEdge;

        public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
            this.spanCount = spanCount;
            this.spacing = spacing;
            this.includeEdge = includeEdge;
        }


    }
}

这是同一活动的xml文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:clickable="true">

    <android.support.v7.widget.CardView
        android:id="@+id/card_view1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:layout_margin="@dimen/card_margin"
        android:elevation="3dp"
        card_view:cardCornerRadius="0dp">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/card"
            android:focusable="true"
            android:contextClickable="true">

            <ImageView
                android:id="@+id/thumbnail1"
                android:layout_width="match_parent"
                android:layout_height="160dp"
                android:background="?attr/selectableItemBackgroundBorderless"
                android:clickable="true"
                android:scaleType="fitXY"
                android:contextClickable="true" />

            <TextView
                android:id="@+id/title1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:paddingLeft="10dp"
                android:paddingRight="25dp"
                android:paddingTop="10dp"
                android:textColor="@color/cardview_dark_background"
                android:textSize="15dp"
                android:layout_centerVertical="true"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true" />

            <TextView
                android:id="@+id/count1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/title"
                android:paddingBottom="5dp"
                android:paddingLeft="10dp"
                android:paddingRight="25dp"
                android:textSize="12dp" />

            <ImageView
                android:id="@+id/overflow"
                android:layout_width="20dp"
                android:layout_height="30dp"
                android:layout_alignParentRight="true"
                android:layout_below="@id/thumbnail"
                android:layout_marginTop="10dp"
                android:scaleType="centerCrop"
                android:src="@android:drawable/ic_menu_sort_by_size" />

        </RelativeLayout>

    </android.support.v7.widget.CardView>

</LinearLayout>

我该如何解决?

1 个答案:

答案 0 :(得分:2)

您的问题是您正在尝试获取不存在的索引0的值。

通过阅读堆栈跟踪,您可以轻松查看正在发生的行:

ir.homa.HotelPageAdapter.prepareHotels(HotelPageAdapter.java:100)
方法HotelPageAdapter.java中的

100prepareHotels您正在调用以下方法:

final HotelList hotel = hotelList.get(position1);

position10,但hotelList不包含任何条目。

因此,您需要先添加条目,或在继续之前检查它是否为空:

private void prepareHotels() {
    // Check if hotelList is empty. If true, go back, if false, continue.
    if(hotelList == null || hotelList.size() == 0) return;

    final HotelList hotel = hotelList.get(position1);
    // ...
}

如果prepareHotels为空,则hotelList只会执行此操作。否则它会继续正常。

但我建议检查是否可以使用position1,所以请改为写下:

// Check if the index position1 is in the bounds of hotelList, and continue if they are, otherwise go back to prevent a crash.
if(hotelList == null || hotelList.size() <= position1) return;