向下滚动时 Listview 崩溃

Listview Crashes When I scroll down

我有一个自定义列表视图,其中包含 header 部分。当用户点击搜索时,列表必须加载。该列表正在加载但是当我向下滚动列表视图时它会崩溃。我也用过viewholder。但我不知道如何解决它。

我的主要 activity 是:

private void loadVolleyData(String url) {
    String tag_json_obj = "json_obj_req";

    final ProgressDialog pDialog = new ProgressDialog(this);
    pDialog.setMessage("Loading...");
    pDialog.show();

    imageList1.clear();
    imageList2.clear();
    imageList3.clear();
    imageList4.clear();
    imageList5.clear();
    imageList6.clear();
    imageList7.clear();
    imageList8.clear();
    imageList9.clear();

    Log.d(TAG, "Search URL: " + url);
    JsonObjectRequest jsonObjReq = new JsonObjectRequest(url, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            Log.d(TAG, "Response Full: " + response);

            try {

                // One --------
                JSONArray categoryval = response.getJSONArray("allbrands");

                for (int j = 0; j < categoryval.length(); j++) {
                    allbrands = new HomeItem();
                    JSONObject object1 = categoryval.getJSONObject(j);
                    if (object1.getString("Status").equalsIgnoreCase("Success")) {
                        System.out.println("array" + object1.getString("imagepath"));
                        allbrands.setID(object1.getString("brandId"));
                        allbrands.setDesc(object1.getString("brandName"));
                        allbrands.setImage(object1.getString("imagepath"));
                        allbrands.setTag("ALL BRANDS");
                        imageList1.add(allbrands);
                    }

                }

                // Two ---------
                JSONArray deals = response.getJSONArray("dealsnoffers");
                System.out.println("Deals n Offres Array " + deals);

                for (int k = 0; k < deals.length(); k++) {
                    allbrands = new HomeItem();
                    JSONObject object1 = deals.getJSONObject(k);
                    if (object1.getString("Status").equalsIgnoreCase("Success")) {
                        allbrands.setID(object1.getString("brandId"));
                        //allbrands.setName(object1.getString("brandName"));
                        allbrands.setImage(object1.getString("imagepath"));
                        allbrands.setDesc(object1.getString("desc"));
                        allbrands.setContent(object1.getString("content"));
                        allbrands.setTag("DEALS & OFFERS");
                        imageList2.add(allbrands);
                    }
                }

                // Three ----------
                JSONArray Specials = response.getJSONArray("brandchildphotoimages");
                System.out.println("Brand Child Pic Images" + Specials);

                for (int k = 0; k < Specials.length(); k++) {
                    allbrands = new HomeItem();
                    JSONObject cuisine = Specials.getJSONObject(k);
                    if (cuisine.getString("Status").equalsIgnoreCase("Success")) {
                        allbrands.setID(cuisine.getString("brandId"));
                        //allbrands.setPhotoid(cuisine.getString("photoId"));
                        allbrands.setImage(cuisine.getString("imagepath"));
                        allbrands.setDesc(cuisine.getString("desc"));
                        allbrands.setContent(cuisine.getString("content"));
                        allbrands.setTag("MY SPECIALS");
                        imageList3.add(allbrands);
                    }
                }

                savngDataInList();

            } catch (JSONException e) {
                VolleyLog.e(TAG, "Response Handling: " + e);
            }

            pDialog.hide();

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d(TAG, "Response Error: " + error);
            pDialog.hide();

        }
    });

    jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(
            5000,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
}

而我的适配器 getView 方法是:

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

    final MyViewHolder viewHolder = new MyViewHolder();

    try {
        final HomeItem HomeItem = HomeItemList.get(position);
        final HomeItem HomeItem1 = HomeItemList1.get(position);


        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.all_brands_layout_search, null);

            viewHolder.imageOne = (DynamicHeightImageView) convertView.findViewById(R.id.my_brand_pinrest_view);
            viewHolder.descOne = (TextView) convertView.findViewById(R.id.bugket_textView);
            viewHolder.imageTwo = (DynamicHeightImageView) convertView.findViewById(R.id.my_brand_pinrest_view2);
            viewHolder.descTwo = (TextView) convertView.findViewById(R.id.bugket_textView2);

            convertView.setTag(viewHolder);
        }
        if (imageLoader == null)
            imageLoader = AppController.getInstance().getImageLoader();


        viewHolder.descOne.setText(HomeItem.getDesc());
        //CatTitle.setText(HomeItem.getHomeItemDescription());

        System.out.println("adapterrr" + HomeItem.getDesc());
        imageLoader.get(HomeItem.getImage(), new ImageListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("TAG_image", "Image Load Error: " + error.getMessage());
            }

            @Override
            public void onResponse(ImageContainer response, boolean arg1) {
                if (response.getBitmap() != null) {

                    // load image into imageview

                    viewHolder.imageOne.setImageBitmap(response.getBitmap());
                }
            }
        });
        System.out.println("adapterrr" + HomeItem.getImage());

        viewHolder.descTwo.setText(HomeItem1.getDesc());
        //CatTitle.setText(HomeItem.getHomeItemDescription());
        System.out.println("adapterrr" + HomeItem1.getDesc());
        imageLoader.get(HomeItem1.getImage(), new ImageListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("TAG_image", "Image Load Error: " + error.getMessage());
            }

            @Override
            public void onResponse(ImageContainer response, boolean arg1) {
                if (response.getBitmap() != null) {

                    // load image into imageview

                    viewHolder.imageTwo.setImageBitmap(response.getBitmap());
                }
            }
        });
        // imageLoader.DisplayImage(HomeItem1.getImage(), CatImage1);
        System.out.println("adapterrr" + HomeItem1.getImage());

    } catch (Exception e) {
        e.printStackTrace();
    }
    return convertView;
}

我的LogCat是

E/AndroidRuntime: FATAL EXCEPTION: main
                                                               Process: com.truetech.lola, PID: 22344
                                                               java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getImportantForAccessibility()' on a null object reference
                                                                   at android.widget.AbsListView.obtainView(AbsListView.java:2363)
                                                                   at android.widget.ListView.makeAndAddView(ListView.java:1875)
                                                                   at android.widget.ListView.fillDown(ListView.java:702)
                                                                   at android.widget.ListView.fillGap(ListView.java:666)
                                                                   at android.widget.AbsListView.trackMotionScroll(AbsListView.java:5036)
                                                                   at android.widget.AbsListView$FlingRunnable.run(AbsListView.java:4584)
                                                                   at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
                                                                   at android.view.Choreographer.doCallbacks(Choreographer.java:670)
                                                                   at android.view.Choreographer.doFrame(Choreographer.java:603)
                                                                   at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
                                                                   at android.os.Handler.handleCallback(Handler.java:746)
                                                                   at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                   at android.os.Looper.loop(Looper.java:148)
                                                                   at android.app.ActivityThread.main(ActivityThread.java:5443)
                                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
03-02 12:34:39.500 22344-22375/com.truetech.lola D/Volley: [10331] BasicNetwork.logSlowRequests: HTTP response for request=<[ ] http://166.62.88.68:8080/lolaPrjct/repo/photoimages/342.jpg 0x9d2d6d5b LOW 18> [lifetime=9981], [size=1030852], [rc=200], [retryCount=1]

而 activity_main.xml 是

<?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">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:background="@color/header_grey"
    android:orientation="horizontal"
    android:weightSum="100">

    <ImageView
        android:id="@+id/slidedrawer"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:layout_weight="20"
        android:contentDescription="@string/showmy"
        android:padding="12dp"
        android:src="@drawable/actionbar_back" />

    <TextView
        android:id="@+id/title_text"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginEnd="6dp"
        android:layout_marginStart="6dp"
        android:layout_weight="60"
        android:text="@string/app_name_search"
        android:textAllCaps="true"
        android:textColor="@color/dark_red"
        android:textStyle="bold" />

    <ImageView
        android:id="@+id/lolahomelick"
        android:layout_width="0dp"
        android:layout_height="38dp"
        android:layout_gravity="center"
        android:layout_weight="20"
        android:padding="8dp"
        android:src="@drawable/lola_home" />
</LinearLayout>

<LinearLayout
    android:id="@+id/layout_search"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp"
    android:layout_marginTop="10dp"
    android:background="@drawable/rounded_border_search"
    android:orientation="horizontal"
    android:weightSum="100">

    <EditText
        android:id="@+id/search_edittext"
        android:layout_width="wrap_content"
        android:layout_height="50dp"
        android:layout_gravity="center"
        android:layout_weight="95"
        android:background="@drawable/edittext_noborder"
        android:gravity="center"
        android:hint="Enter your search..."
        android:maxLines="1"
        android:textColorHint="@color/grey_grey"
        android:textStyle="italic" />

    <ImageView
        android:id="@+id/action_search"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_gravity="center"
        android:layout_marginRight="2dp"
        android:layout_weight="5"
        android:src="@drawable/searchgry" />
</LinearLayout>

<ListView
    android:id="@+id/Listview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_marginTop="5dp"
    android:divider="@null" />
<!--<GridView
    android:id="@+id/gridView"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_marginTop="5dp"
    android:numColumns="2"
    android:divider="@null" />-->
</LinearLayout>

还有 all_brands_search.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/rounded_border"
android:orientation="vertical">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:weightSum="2"
    android:orientation="horizontal">

    <LinearLayout
        android:id="@+id/itemContainer"
        android:layout_width="0dip"
        android:layout_height="210dp"
        android:layout_margin="5dp"
        android:layout_weight="1"
        android:orientation="vertical"
        android:tag="1">

        <com.etsy.android.grid.util.DynamicHeightImageView
            android:id="@+id/my_brand_pinrest_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="2dp"
            android:scaleType="centerCrop" />

        <TextView
            android:id="@+id/bugket_textView"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_gravity="center"
            android:layout_marginBottom="5dp"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:layout_marginTop="5dp"
            android:layout_weight="4"
            android:gravity="center"
            android:text=""
            android:textColor="@color/red" />

    </LinearLayout>

    <LinearLayout
        android:id="@+id/itemContainer2"
        android:layout_width="0dip"
        android:layout_height="210dp"
        android:layout_margin="5dp"
        android:layout_weight="1"
        android:orientation="vertical"
        android:tag="2">

        <com.etsy.android.grid.util.DynamicHeightImageView
            android:id="@+id/my_brand_pinrest_view2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="2dp"
            android:scaleType="centerCrop" />s

        <TextView
            android:id="@+id/bugket_textView2"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_gravity="center"
            android:layout_marginBottom="5dp"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:layout_marginTop="5dp"
            android:layout_weight="4"
            android:gravity="center"
            android:text=""
            android:textColor="@color/red" />
    </LinearLayout>
</LinearLayout>
</LinearLayout>

更新适配器Class

package com.truetech.lola.search;


public class HomeListAdapter extends ArrayAdapter<HomeItem> implements OnClickListener {
public Context context;
public List<HomeItem> HomeItemList, HomeItemList1;
com.android.volley.toolbox.ImageLoader imageLoader;

public HomeListAdapter(Context context, int resource, List<HomeItem> HomeItemLst, List<HomeItem> HomeItemLst1) {
    super(context, resource, HomeItemLst);
    this.context = context;
    this.HomeItemList = HomeItemLst;
    this.HomeItemList1 = HomeItemLst1;
    imageLoader = AppController.getInstance().getImageLoader();
}

static class ViewHolder {
    DynamicHeightImageView imageOne, imageTwo;
    TextView descOne, descTwo;
}

@Override
public int getCount() {
    if (HomeItemList != null)
        return HomeItemList.size();
    if (HomeItemList1 != null)
        return HomeItemList1.size();

    return 0;
}

@Override
public HomeItem getItem(int position) {
    if (position >= HomeItemList.size())
        return HomeItemList1.get(position);
    return HomeItemList.get(position);
}


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

    View row;
    row = convertView;
    final ViewHolder viewHolder;

    try {
        /*final HomeItem homeItem = HomeItemList.get(position);
        final HomeItem homeItem1 = HomeItemList1.get(position);*/

        if (convertView == null) {

            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.all_brands_layout_search, null);

            viewHolder = new ViewHolder();

            viewHolder.imageOne = (DynamicHeightImageView) row.findViewById(R.id.my_brand_pinrest_view);
            viewHolder.descOne = (TextView) row.findViewById(R.id.bugket_textView);
            viewHolder.imageTwo = (DynamicHeightImageView) row.findViewById(R.id.my_brand_pinrest_view2);
            viewHolder.descTwo = (TextView) row.findViewById(R.id.bugket_textView2);

            convertView.setTag(viewHolder);
        }else {
            viewHolder = (ViewHolder) row.getTag();
        }
        if (imageLoader == null)
            imageLoader = AppController.getInstance().getImageLoader();



       /* final DynamicHeightImageView CatImage = (DynamicHeightImageView) convertView.findViewById(R.id.my_brand_pinrest_view);
        TextView CatHeader = (TextView) convertView.findViewById(R.id.itemSubHeaderText1);
        final DynamicHeightImageView CatImage1 = (DynamicHeightImageView) convertView.findViewById(R.id.my_brand_pinrest_view1);
        TextView CatHeader1 = (TextView) convertView.findViewById(R.id.itemSubHeaderText2);
        //TextView CatTitle = (TextView) myConvertView.findViewById(R.id.description);*/

        /*final DynamicHeightImageView CatImage = (DynamicHeightImageView) convertView.findViewById(R.id.my_brand_pinrest_view);
        TextView CatHeader = (TextView) convertView.findViewById(R.id.bugket_textView);
        final DynamicHeightImageView CatImage1 = (DynamicHeightImageView) convertView.findViewById(R.id.my_brand_pinrest_view2);
        TextView CatHeader1 = (TextView) convertView.findViewById(R.id.bugket_textView2);*/

        HomeItem homeItem;
        HomeItem homeItem1;

        homeItem = (HomeItem) this.getItem(position);
        homeItem1 = (HomeItem) this.getItem(position);

        viewHolder.descOne.setText(homeItem.getDesc());
        //CatTitle.setText(HomeItem.getHomeItemDescription());

        System.out.println("adapterrr" + homeItem.getDesc());
        imageLoader.get(homeItem.getImage(), new ImageListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("TAG_image", "Image Load Error: " + error.getMessage());
                viewHolder.imageOne.setImageResource(R.drawable.lolg_placehold);
            }

            @Override
            public void onResponse(ImageContainer response, boolean arg1) {
                if (response.getBitmap() != null) {
                    // load image into imageview
                    viewHolder.imageOne.setImageBitmap(response.getBitmap());
                }
            }
        });
        System.out.println("adapterrr" + homeItem.getImage());

        viewHolder.descTwo.setText(homeItem1.getDesc());
        //CatTitle.setText(HomeItem.getHomeItemDescription());
        System.out.println("adapterrr" + homeItem1.getDesc());
        imageLoader.get(homeItem1.getImage(), new ImageListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("TAG_image", "Image Load Error: " + error.getMessage());
                viewHolder.imageTwo.setImageResource(R.drawable.lolg_placehold);
            }

            @Override
            public void onResponse(ImageContainer response, boolean arg1) {
                if (response.getBitmap() != null) {
                    // load image into imageview
                    viewHolder.imageTwo.setImageBitmap(response.getBitmap());
                }
            }
        });
        // imageLoader.DisplayImage(HomeItem1.getImage(), CatImage1);
        System.out.println("adapterrr " + homeItem1.getImage());

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

    return row;
}

@Override
public long getItemId(int position) {
    return position;
}

public void onClick(View v) {
    // TODO Auto-generated method stub

}

}

你需要在设置标签后获取那个 viewHolder,你没有执行 that.Put 这段代码并检查..

MyViewHolder viewHolder = null;

if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        viewHolder = new MyViewHolder();;
        convertView = inflater.inflate(R.layout.all_brands_layout_search, null);

        viewHolder.imageOne = (DynamicHeightImageView) convertView.findViewById(R.id.my_brand_pinrest_view);
        viewHolder.descOne = (TextView) convertView.findViewById(R.id.bugket_textView);
        viewHolder.imageTwo = (DynamicHeightImageView) convertView.findViewById(R.id.my_brand_pinrest_view2);
        viewHolder.descTwo = (TextView) convertView.findViewById(R.id.bugket_textView2);

        convertView.setTag(viewHolder);
    }else{
 viewHolder= (MyViewHolder)convertView.getTag();
 }

您错误地使用了 ViewHolder 模式。你需要做这样的事情:

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

    final MyViewHolder viewHolder;
    final HomeItem HomeItem = HomeItemList.get(position);
    final HomeItem HomeItem1 = HomeItemList1.get(position);
    if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.all_brands_layout_search, parent, false);
        viewHolder = new MyViewHolder();
        viewHolder.imageOne = (DynamicHeightImageView) convertView.findViewById(R.id.my_brand_pinrest_view);
        viewHolder.descOne = (TextView) convertView.findViewById(R.id.bugket_textView);
        viewHolder.imageTwo = (DynamicHeightImageView) convertView.findViewById(R.id.my_brand_pinrest_view2);
        viewHolder.descTwo = (TextView) convertView.findViewById(R.id.bugket_textView2);
        convertView.setTag(viewHolder);
    } else {
        viewHolder = (MyViewHolder)convertView.getTag();
    }
    ///rest of your code
    return convertView;
}

你完全错了。如果你的视图为空,那么你创建新的 ViewHolder,如果没有,那么你从中获取 ViewHolder。

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

    final MyViewHolder viewHolder;

    if (convertView == null) {

        viewHolder = new MyViewHolder();

        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.all_brands_layout_search, parent, false);
        //find all views..
        //find all views..
        //find all views..
        convertView.setTag(viewHolder);
    } else {
        // the view holder already exist
        viewHolder = (MyViewHolder) convertView.getTag();
    }

    ...
}