androidcustom-adaptergetview

Custom adatper getView returns null pointer


In my app I have a listview with a custom adapter which is reloaded after a message was send. The app chrashes at some of the installations. I have in the app console the stack traces. Here the code:

class IconicAdapter extends ArrayAdapter<Integer> {
        Activity context;

        IconicAdapter(Activity context) {
            super(context, R.layout.message_layout, listItems);

            this.context = context;
        }

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


                //you can access layout inflater by accessing hosting activity
                convertView = getActivity().getLayoutInflater().inflate(R.layout.message_layout, parent, false);


            JSONObject json_data = null;
            try {
                json_data = jArray.getJSONObject(position);
            } catch (JSONException e) {
            }

            try {
                tv = (TextView) convertView.findViewById(R.id.username);
                tv.setText(json_data.getString("username"));

Here stack trace:

java.lang.NullPointerException: 
  at com.testing.gold.CommunityFragment$IconicAdapter.getView (CommunityFragment.java:945)
  at android.widget.HeaderViewListAdapter.getView (HeaderViewListAdapter.java:232)

The line 945: tv.setText(json_data.getString("username"));


Solution

  • Use following code: class IconicAdapter extends ArrayAdapter { Activity context;

    IconicAdapter(Activity context) {
        super(context, R.layout.message_layout, listItems);
    
        this.context = context;
    }
    
    public View getView(int position, View convertView, ViewGroup parent) {
         convertView=LayoutInflater.inflate(R.layout.message_layout, null);
         JSONObject json_data = null;
         try {
            json_data = jArray.getJSONObject(position);
    
        } catch (JSONException e) {
             e.printStackTrace();
        }
     tv = (TextView) convertView.findViewById(R.id.username);
    
    if(json_data!=null)
       tv.setText(json_data.getString("username"));
    else
       tv.setText("")