Chiggins Chiggins - 6 days ago 6
Android Question

ArrayAdapter getView() position only at 0

Sorry if this seems silly, I just cannot understand this runtime error I'm getting. For reference, here is my code:

MainActivity.java

MainListViewRecordAdapter.java

Currently, I'm getting a NullPointerException on line 27 of the MainListViewRecordAdapter. When I run the debugger, the int position has always been 0, which leads the code to not grad an item out of the ArrayList, causing the NullPointerException. The only thing is, I don't understand why that's happening, why is position always having the value 0?

Answer

you havent initialized Arraylist items and remove line position=1;. do as follows:

package com.chigstuff.fun;

import java.util.ArrayList;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class MainListViewRecordAdapter extends ArrayAdapter<MainListViewRecord> {
    private ArrayList<MainListViewRecord> items;

    public MainListViewRecordAdapter(Context context, int textViewResourceId, ArrayList<MainListViewRecord> items) {
        super(context, textViewResourceId, items);
this.items=items;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
        if (v == null) {
            LayoutInflater vi = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(R.layout.main_list_view_record, null);
        }
        MainListViewRecord item = items.get(position);
        if (item != null) {
            TextView main_list_view_text = (TextView) v.findViewById(R.id.main_list_view_text);

            if (main_list_view_text != null) {
                main_list_view_text.setText("What text");
            }
        }

        return v;
    }
}