Reputation: 540
I'm newbie at Android Development, I have been learning this about 4 months.
I'm trying to get my application context to use an library called picasso. I built a costume adapter to load images to my imageview.
But I'm having some issues getting the application context, I tried to use getBaseContext, getActivity(), and I created a variable to get the context, but it didn't work.
I'm building my app using fragments, my code:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
final ArrayList alEvents = new ArrayList<String>();
eventsAdapter = new costumeadapter(getActivity(), alEvents,
R.layout.list, new String[] { ITEM_NAME, ITEM_EVENT },
new int[] { R.id.name, R.id.current_event });
lvEvents.setAdapter(eventsAdapter);
...
}
My costume adapter:
public class costumeadapter extends SimpleAdapter {
Context context;
public costumeadapter(FragmentActivity fragmentActivity,
List<? extends Map<String, ?>> data, int resource, String[] from,
int[] to) {
super(fragmentActivity, data, resource, from, to);
// TODO Auto-generated constructor stub
}
public View getView(final int position, final View convertView,
final ViewGroup parent) {
View v = super.getView(position, convertView, parent);
ImageView bg_image = (ImageView) v.findViewById(R.id.bg_image);
Picasso.with(context)
.load("http://pplware.sapo.pt/wp-content/uploads/2015/06/Wallpaper_10.jpg")
.into(bg_image);
return v;
}
}
Can you guys give me any solution? Thanks.
Upvotes: 0
Views: 289
Reputation: 11
You can transmit Activity to fragment. At the fragment class, override onActivityCreated to get Activity which is contained fragment. Then getting context from this activity
Upvotes: 0
Reputation: 441
You should have include how you have tried to get the context that is not working for you but I think this will work
public View getView(final int position, final View convertView,
final ViewGroup parent) {
View v = super.getView(position, convertView, parent);
ImageView bg_image = (ImageView) v.findViewById(R.id.bg_image);
context = parent.getContext();
Picasso.with(context)
.load("http://pplware.sapo.pt/wp-content/uploads/2015/06/Wallpaper_10.jpg")
.into(bg_image);
return v;
}
Upvotes: 0
Reputation: 132992
Use convertView.getContext()
or v.getContext()
to get Context for passing to Picasso.with
method as:
Picasso.with(convertView.getContext())
.load("<IMAGE_URL>")
.into(bg_image);
Upvotes: 1
Reputation: 2729
In your adapter, declare:
final Context localContext;
and after:
public costumeadapter(FragmentActivity fragmentActivity,
List<? extends Map<String, ?>> data, int resource, String[] from,
int[] to) {
super(fragmentActivity, data, resource, from, to);
this.localContext = fragmentActivity;
}
in localContext variable you will have a context.
Upvotes: 0