-2

I have a custom Listview with section header in it. And when the user click search the list has to load. The list is getting load but when I scroll down the listview its getting crash. I used viewholder also. But I didn't know how to fix it.

And my main activity is:

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);
}

And My Adapter getView Method is:

@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;
}

And My LogCat is

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]

And the activity_main.xml is

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

And the 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>

Updated Adapter 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

}

}
Encipherer
  • 411
  • 7
  • 23

3 Answers3

1

U need get that viewHolder after u set the tag, u r not doing that.Put this code and check..

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();
 }
Naveen Shriyan
  • 1,266
  • 1
  • 9
  • 15
  • @SanjayAD use my above code and comment everything below viewHolder.descOne.setText(HomeItem.getDesc()) but keep this line and above codes this line of code, jus to check where the problem exist. – Naveen Shriyan Mar 02 '16 at 08:53
  • same error bro E/AndroidRuntime: FATAL EXCEPTION: main Process: com.truetech.lola, PID: 7248 java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getImportantForAccessibility()' on a null object reference – Encipherer Mar 02 '16 at 10:02
  • Sure bro. Few min pls – Encipherer Mar 02 '16 at 10:09
  • and also check HomeItem and HomeItem1 size pls, in getCount() method u r returning the size rit, pls check that too... – Naveen Shriyan Mar 02 '16 at 10:10
  • Thanks for your time and effort bro. I tried both but still the problem is occurring. – Encipherer Mar 02 '16 at 10:23
  • HomeItem and HomeItem1 size? check before returning "convertView" null or not? – Naveen Shriyan Mar 02 '16 at 10:27
  • can u give me some example – Encipherer Mar 02 '16 at 10:30
  • only look at the adapter code and compare urs, follow the same approach but with ur contents. This should work....I doubt ur HomeList and HomeList1 is not populated properly it is empty it seems. – Naveen Shriyan Mar 02 '16 at 10:38
  • actually in this method its not crashing but the listview is not displaying its content. But the length of the listview row is populating correctly. I think I made a mistake in this MoveDataProvider dataProvider; dataProvider=(MoveDataProvider)this.getItem(position); – Encipherer Mar 02 '16 at 11:50
  • its not displaying any data now – Encipherer Mar 02 '16 at 11:51
  • bro any way to fix it? – Encipherer Mar 02 '16 at 12:32
  • could you remove HomeITemList1 from code completly for while and test once ? so that we can confirm the prob is not with two list. – Naveen Shriyan Mar 02 '16 at 13:41
0

You are Using ViewHolder pattern wrongly. You need to do something like that:

@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;
}
yshahak
  • 4,996
  • 1
  • 31
  • 37
0

You get it all wrong.. If your view is null then you create new ViewHolder, and if it doesn't then you get the ViewHolder from it.

@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();
    }

    ...
}
nbaroz
  • 1,795
  • 13
  • 14