mhrzn mhrzn - 4 months ago 40
Android Question

Android arrayAdapter and BaseAdapter getContext ? why getContext works on array adapter but not on base adapter?

Why does the getContext() method works on ArrayAdapter inside getView method.

convertView = LayoutInflater.from(getContext()).inflate(R.layout.row,parent,false);


why the same code does work on BaseAdapter ?

Code Class extending ArrayAdapter ?

package com.example.manis.mylist3;

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

import java.util.ArrayList;

/**
* Created by Manis on 8/6/2016.
*/

public class NoteAdapter extends ArrayAdapter{

public NoteAdapter(Context context, ArrayList<Note> notes) {
super(context, 0 ,notes);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Log.v("adapter","called"+position);
Note note = (Note) getItem(position);

if(convertView==null){
// Log.v("noteAdapter","ConvertView was null");
convertView = LayoutInflater.from(getContext()).inflate(R.layout.row,parent,false);
}
TextView noteTitle= (TextView) convertView.findViewById(R.id.rowTitle);
TextView noteSubText= (TextView) convertView.findViewById(R.id.rowSubText);
ImageView img = (ImageView) convertView.findViewById(R.id.rowImg);

noteTitle.setText(note.getTitle());
noteSubText.setText(note.getSubtext());
img.setImageResource(note.getAssociatedDrawable());

return convertView;
}


}


Code for NoteBaseAdapter Class Extending BaseAdapter

package com.example.manis.mylist3;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.ArrayList;


public class NoteBaseAdapter extends BaseAdapter {

ArrayList<Note> notes;
Context context;
public NoteBaseAdapter(Context c, ArrayList<Note> notes)
{
this.context=c;
this.notes=notes;
}

@Override
public int getCount() {
return notes.size();
}

@Override
public Object getItem(int position) {
return notes.get(position);
}

@Override
public long getItemId(int position) {
return position;
}

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

//error
convertView = LayoutInflater.from(getContext()).inflate(R.layout.row,parent,false);

}
}

Answer

Well, the ArrayAdapter extends BaseAdapter and has a context variable in its constructor which is saved and can be accessed using getContext(). Whereas, BaseAdapter has an empty constructor. You don't provide one to it, so you can't get it from the base class. If you need one, make your own constructor like the ArrayAdapter class did and save your context there.