1

I have an adapter, I want to inflate a view but I can't.

This is my class code:

private static class RandomsAdapter extends BaseAdapter{
    private Randoms randoms;
    private RandomsAdapter(Randoms randoms) {
        this.randoms=randoms;
    }
    public void updateRandoms(Randoms randoms) {
        this.randoms=randoms;
        notifyDataSetChanged();
    }
    @Override
    public int getCount() {
        return randoms.size();
    }
    @Override
    public Random getItem(int position) {
        return randoms.get(position);
    }
    @Override
    public long getItemId(int position) {
        return 0;
    }
    public View getView(int position,View convertView,ViewGroup parent) {
        View view=convertView;

        if (convertView == null) {
            convertView=getLayoutInflater().inflate(R.layout.random_bars,parent,false);
        }
    }
}

I am getting an error for this line: convertView=getLayoutInflater().inflate(R.layout.random_bars,parent,false);

Error: Cannot make a static reference to the non-static method getLayoutInflater() from the type Activity

How can I resolve it?

Wyetro
  • 8,439
  • 9
  • 46
  • 64
Serkay Sarıman
  • 465
  • 1
  • 10
  • 17
  • [If you're not within an Activity, you need to get a layout inflater from some other Context](http://stackoverflow.com/questions/7803771/call-to-getlayoutinflater-in-places-not-in-activity). – Matt Gibson Sep 06 '14 at 14:35

2 Answers2

0

you need Context inside this class& add it to constructor as

private RandomsAdapter(Randoms randoms, Context context) {
        this.randoms=randoms;
        this.mContext = context;
}

or remove "static" word from RandomsAdapter class definition

ant
  • 397
  • 1
  • 5
  • 19
0

You need to pass Activity Context to your adapter. In the constructor:

private LayoutInflater inflater;

public RandomsAdapter(Context context, Randoms randoms) {
        this.randoms=randoms;
        this.inflater = LayoutInflater.from(context);
    }

Then you inflate layout as:

convertView=inflater.inflate(R.layout.random_bars,parent,false);
Alexander Zhak
  • 9,140
  • 4
  • 46
  • 72
  • Now I am getting error for this line:ListAdapter randomsAdapter=new RandomsAdapter(randoms); Error:The constructor MainActivity.RandomsAdapter(MainActivity.Randoms) is undefined I think I have to pass context but how ? – Serkay Sarıman Sep 06 '14 at 15:00
  • @SerkaySarıman `ListAdapter randomsAdapter=new RandomsAdapter(this, randoms);` or `ListAdapter randomsAdapter=new RandomsAdapter(MainActivity.this, randoms);` – Alexander Zhak Sep 06 '14 at 15:10