Android studio “ Attempt to invoke virtual method on a null object reference”

前端 未结 2 1770
心在旅途
心在旅途 2020-12-20 21:53

when i create the custom view of each items of the list view, i get a null pointer exception and i dont know why, the layout id seems correct

import android.         


        
相关标签:
2条回答
  • 2020-12-20 22:00

    In your code

    itemView = getLayoutInflater().inflate(R.layout.item_view, parent, false);
    

    the getLayoutInflater() method is not usable in The inner adapter class. Hence you should try creating an Variable to have the Layout inflater object of the parent class and hence access it ,or you can send in the context of the calling class in the constructor of the adapter class.

    Hence you can use either like this:

    public class ActivityMainWish extends Activity {
    
    LayoutInflate inflater;
    private List<Wish> myWishs = new ArrayList<>();
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    inflater=getLayoutInflater()
    ...
    }
    

    and use this inflater variable over here: itemView = inflater.inflate(R.layout.item_view, parent, false);

    Or like this:

    private class MyListAdapter extends ArrayAdapter<Wish>{
    private Context mContext;
    public MyListAdapter(Context ctx){
        super(ActivityMainWish.this, R.layout.item_view, myWishs);
        mContext=ctx;
    }
    
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View itemView = convertView;
        if (itemView==null)
            itemView = LayoutInflater.from(mContext).inflate(R.layout.item_view, parent, false);
    

    and send the Context object like:

    ArrayAdapter<Wish> adapter = new MyListAdapter(getApplicationContext());
    
    0 讨论(0)
  • 2020-12-20 22:17

    Try changing the relevant code inside your Adapter class to the following

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View itemView;
        if (convertView == null) {
           itemView = inflater.inflate(R.layout.item_view, parent, false); 
        } else {
           itemView = convertView;
        }
        ...
        ...
        return itemView;
    }
    
    0 讨论(0)
提交回复
热议问题