0

I have an array adapter for setting messages in a texting app. Upon either sending or receiving one message the app works fine. However, once a second message is sent or received, the app crashes and displays a NullPointerException error:

java.lang.NullPointerException
            at com.example.feastapp.ChatBoxUi.DiscussArrayAdapter.getView(DiscussArrayAdapter.java:114)
            at android.widget.AbsListView.obtainView(AbsListView.java:2255)
            at android.widget.ListView.makeAndAddView(ListView.java:1790)
            at android.widget.ListView.fillUp(ListView.java:725)
            at android.widget.ListView.layoutChildren(ListView.java:1611)
            at android.widget.AbsListView.onLayout(AbsListView.java:2087)
            at android.view.View.layout(View.java:14817)
            at android.view.ViewGroup.layout(ViewGroup.java:4631)
            at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1055)
            at android.view.View.layout(View.java:14817)
            at android.view.ViewGroup.layout(ViewGroup.java:4631)
            at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
            at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
            at android.view.View.layout(View.java:14817)
            at android.view.ViewGroup.layout(ViewGroup.java:4631)
            at com.android.internal.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:374)

on line: holder.countryName.setText(countries.get(position).comment);

The new comments are added to the adapter using the inialization:

adapter.add(new OneComment(false, "from: person" + ": " + message.toString(), "0", "0"));

How can I reconfigure so that the NullPointer does not occur?

The ArrayAdapter class:

public class DiscussArrayAdapter extends ArrayAdapter<OneComment> {

    class ViewHolder {
        TextView countryName;
        ImageView sharedSpecial;
        LinearLayout wrapper;
    }

    private TextView countryName;
    private ImageView sharedSpecial;


    private List<OneComment> countries = new ArrayList<OneComment>();
    private LinearLayout wrapper;

    private JSONObject resultObject;
    private JSONObject imageObject;

    String getSharedSpecialURL = null;
    String getSharedSpecialWithLocationURL = null;

    String specialsActionURL = "http://" + Global.getIpAddress()
            + ":3000/getSharedSpecial/";

    String specialsLocationActionURL = "http://" + Global.getIpAddress()
            + ":3000/getSharedSpecialWithLocation/";

    String JSON = ".json";

    @Override
    public void add(OneComment object) {
        countries.add(object);
        super.add(object);
    }

    public DiscussArrayAdapter(Context context, int textViewResourceId) {
        super(context, textViewResourceId);
    }

    public int getCount() {
        return this.countries.size();
    }

    private OneComment comment = null;

    public OneComment getItem(int index) {
        return this.countries.get(index);
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;

        View row = convertView;
        if (row == null) {
            LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = inflater.inflate(R.layout.message_list_item, parent, false);

            holder = new ViewHolder();
            holder.wrapper = (LinearLayout) row.findViewById(R.id.wrapper);
            holder.countryName = (TextView) row.findViewById(R.id.comment);
            holder.sharedSpecial = (ImageView) row.findViewById(R.id.sharedSpecial);

        } else {
            holder = (ViewHolder) row.getTag();
        }

        Log.v("COMMENTING","Comment is " + countries.get(position).comment);

        //OneComment comment = getItem(position);
        holder.countryName.setText(countries.get(position).comment);

        // Initiating Volley
        final RequestQueue requestQueue = VolleySingleton.getsInstance().getRequestQueue();

        // Check if message has campaign or campaign/location attached
        if (countries.get(position).campaign_id == "0" && countries.get(position).location_id == "0") {

            holder.sharedSpecial.setImageResource(0);

            Log.v("TESTING", "It is working");

        } else if (countries.get(position).campaign_id != "0" && countries.get(position).location_id != "0") {

            // If both were shared
            getSharedSpecialWithLocationURL = specialsLocationActionURL + countries.get(position).campaign_id + "/" + countries.get(position).location_id + JSON;

            // GET JSON data and parse
            JsonObjectRequest getCampaignLocationData = new JsonObjectRequest(Request.Method.GET, getSharedSpecialWithLocationURL, null,
                    new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject response) {

                            // Parse the JSON:
                            try {
                                resultObject = response.getJSONObject("shared");

                                imageObject = resultObject.getJSONObject("image");
                                adImageURL = imageObject.getString("url");



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

                            // Get and set image
                            Picasso.with(getContext()).load("http://" + Global.getIpAddress() + ":3000" + adImageURL).into(holder.sharedSpecial);


                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Log.d("Error.Response", error.toString());
                        }
                    }
            );

            requestQueue.add(getCampaignLocationData);

        } else if (countries.get(position).campaign_id != "0" && countries.get(position).location_id == "0") {

            // Just the campaign is shared
            getSharedSpecialURL = specialsActionURL + countries.get(position).campaign_id + JSON;



            JsonObjectRequest getCampaignData = new JsonObjectRequest(Request.Method.GET, getSharedSpecialURL, null,
                    new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject response) {

                            // Parse the JSON:
                            try {
                                resultObject = response.getJSONObject("special_shared");
                                adId = resultObject.getString("id");
                                adCaption = resultObject.getString("ad_caption");
                                adDetail = resultObject.getString("ad_details");
                                adRestaurant = resultObject.getString("restaurant_name");

                                imageObject = resultObject.getJSONObject("image");
                                adImageURL = imageObject.getString("url");

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

                            // Get and set image
                            Picasso.with(getContext()).load("http://" + Global.getIpAddress() + ":3000" + adImageURL).into(holder.sharedSpecial);

                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Log.d("Error.Response", error.toString());
                        }
                    }
            );

            requestQueue.add(getCampaignData);

            // Location set to empty
        }

        // If left is true, then yellow, if not then set to green bubble
        holder.countryName.setBackgroundResource(countries.get(position).left ? R.drawable.bubble_yellow : R.drawable.bubble_green);
        holder.wrapper.setGravity(countries.get(position).left ? Gravity.LEFT : Gravity.RIGHT);

        return row;
    }

}
1
  • add Log.d("countries is null", "" + checkIfCountriesIsNull), Log.d("countries.get(position) is null", "" + checkIfgetposIsNull) ... or just use f... debugger Commented Feb 24, 2015 at 2:54

1 Answer 1

1

You forgot to save the ViewHolder as a tag whenever you create a new view.

The first if statement in getView() should look like:

    if (row == null) {
        LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        row = inflater.inflate(R.layout.message_list_item, parent, false);

        holder = new ViewHolder();
        holder.wrapper = (LinearLayout) row.findViewById(R.id.wrapper);
        holder.countryName = (TextView) row.findViewById(R.id.comment);
        holder.sharedSpecial = (ImageView) row.findViewById(R.id.sharedSpecial);

        // Store the ViewHolder as a tag.
        row.setTag(holder);

    } else {
        holder = (ViewHolder) row.getTag();
    }

Even better, you should use the setTag(int key, Object tag) and getTag(int key) variants of setTag and getTag, to avoid clashes with any other code that might use the shared tag in their own way. You should use one of your app's resource IDs as the key (to ensure uniqueness) -- say R.layout.message_list_item.

Sign up to request clarification or add additional context in comments.

1 Comment

Quote: The first thing you should do after reading someone's answer to your question is vote on the answer, What a terrible advice. like any other user (with sufficient reputation) does . Well that is not true. hardly any user does this luckily. Hmmmm... I always vote by not up or down voting ;-). But ok, now i know why you asked

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.