How to display remote images in ListView using BaseAdapter? - android

I am using the following code to display images on ListView using BaseAdapter .The code displays images from inside drawable folder. But I want to modify the code so it displays remote images from following Array:
String flags[] ={"http://www.website.com/images/usa.png","http://www.website.com/images/china.png","http://www.website.com/images/australia.png","http://www.website.com/images/portugle.png","http://www.website.com/images/norway.png","http://www.website.com/images/new_zealand.png"};
Could an expert show me what part needs to be change.Thanks in advance.
MainActivity.java:
public class MainActivity extends Activity {
ListView simpleList;
String countryList[] = {"USA", "China", "australia", "Portugle", "Norway", "NewZealand"};
int flags[] = {R.drawable.usa, R.drawable.china, R.drawable.australia, R.drawable.portugle, R.drawable.norway, R.drawable.new_zealand};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
simpleList = (ListView) findViewById(R.id.simpleListView);
CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), countryList, flags);
simpleList.setAdapter(customAdapter);
simpleList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "Hello " + countryList[position], Toast.LENGTH_LONG).show();
}
});
}
}
CustomAdapter.java:
Public class CustomAdapter extends BaseAdapter {
Context context;
String countryList[];
int flags[];
LayoutInflater inflter;
public CustomAdapter(Context applicationContext, String[] countryList, int[] flags) {
this.context = context;
this.countryList = countryList;
this.flags = flags;
inflter = (LayoutInflater.from(applicationContext));
}
#Override
public int getCount() {
return countryList.length;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = inflter.inflate(R.layout.activity_listview, null);
TextView country = (TextView) view.findViewById(R.id.textView);
ImageView icon = (ImageView) view.findViewById(R.id.icon);
country.setText(countryList[i]);
icon.setImageResource(flags[i]);
return view;
}
}

You need to:
1) Fetch those images in a separate thread, you can use volley, retrofit, robospice for this.
2) On the response of any of those methods from 1) you have to pass the list of values you obtained from the service to your adapter's constructor. You will need to create a POJO for the model, this structure will hold all the elements from the REST webservice.
3) It is recommended to use a viewholder for your listview's adapter, to avoid inflating the views again and again.

The easiest thing to do is use Glide or Picasso:
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = inflter.inflate(R.layout.activity_listview, null);
TextView country = (TextView) view.findViewById(R.id.textView);
ImageView icon = (ImageView) view.findViewById(R.id.icon);
country.setText(countryList[i]);
// Assuming flags is now the list of Strings of image urls
GlideApp.with(view.getContext()).load(flags[i]).into(icon);
return view;
}

you can also use some third party library like Picasso or Glide to load images right into your adapter's get view method
Picasso.with(this).load(flags[adapter's
position]).into(imageView);
same in glide.
here is simple tutorial https://www.simplifiedcoding.net/picasso-android-tutorial-picasso-image-loader-library/

Related

How to show loading image with progress bar and image also want to counting number in my gridview andriod studio

I have created android app like gallery which have some images using gridview fragment.
Functionality of my application is working fine and image showing in fragment gridview and also my second activity open when i click on item but i want to show loading image with progress bar when my image not load or take time for loading complete.
Also i want to show image counting number in gridview.
But i want to progress bar on loading images like this : WANT LINK THIS SCREENSHOT
My gridview looks like this : My gridview looks like this
already to find the
Here is my application fragment code :
public class CallFragment extends Fragment {
GridView grid;
String[] plan = {
"Student Bundle",
"SMS Plus Bundle",
"Instagram",
"Facebook",
"Flickr"
} ;
String[] web = {
"*3000",
"*106*1",
"Instagram",
"Facebook",
"Flickr"
} ;
int[] imageId = {
R.drawable.calla,
R.drawable.smsb,
R.drawable.person7,
R.drawable.person7,
R.drawable.person7
};
int[] fullimg = {
R.drawable.callaa,
R.drawable.smsbb,
R.drawable.person7,
R.drawable.person7,
R.drawable.person7
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true);
View view = inflater.inflate(R.layout.fragment_call,container,false);
CustomGrid adapter = new CustomGrid(getActivity(), plan, web, imageId, fullimg);
grid=(GridView) view.findViewById(R.id.grid);
grid.setAdapter(adapter);
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String value=(String)grid.getItemAtPosition(i);
Intent intent=new Intent(getActivity(),Book.class);
intent.putExtra("web", web[i]);
intent.putExtra("plan", plan[i]);
intent.putExtra("imageId", imageId[i]);
intent.putExtra("fullimg", fullimg[i]);
startActivity(intent);
}
});
return view;
}
Here is my application CustomAdapter code :
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {
ArrayList<String> personNames;
ArrayList<String> personCode;
ArrayList<Integer> personImages;
ArrayList<Integer> personImages1;
Context context;
public CustomAdapter(Context context, ArrayList<String> personNames, ArrayList<String> personCode, ArrayList<Integer> personImages, ArrayList<Integer> personImages1) {
this.context = context;
this.personCode = personCode;
this.personNames = personNames;
this.personImages = personImages;
this.personImages1 = personImages1;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// infalte the item Layout
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.rowlayout, parent, false);
// set the view's size, margins, paddings and layout parameters
MyViewHolder vh = new MyViewHolder(v); // pass the view to View Holder
return vh;
}
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
// set the data in items
//holder.name.setText(personNames.get(position));
holder.image.setImageResource(personImages.get(position));
//holder.image.setImageResource(personImages1.get(position));
// implement setOnClickListener event on item view.
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// open another activity on item click
Intent intent = new Intent(context, SecondActivity.class);
//intent.putExtra("image", personImages.get(position)); // put image data in Intent
intent.putExtra("name", personNames.get(position)); // put image data in Intent
intent.putExtra("code", personCode.get(position)); // put image data in Intent
intent.putExtra("image", personImages1.get(position)); // put image data in Intent
context.startActivity(intent); // start Intent
}
});
}
#Override
public int getItemCount() {
return personNames.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
// init the item view's
TextView name;
TextView code;
ImageView image;
public MyViewHolder(View itemView) {
super(itemView);
// get the reference of item view's
name = (TextView) itemView.findViewById(R.id.name);
code = (TextView) itemView.findViewById(R.id.code);
image = (ImageView) itemView.findViewById(R.id.image);
}
}
}
Also if it is easier default image in place of loading images instead of progress bar will be fine.
Please provide me solution to implement this.
i hope you get my main point which i want and Thanks for help.

custom adapter isn't showing any items

This is a follow on from an earlier question: ImageButton within row of ListView android not working
But after suggestions from SO gurus it has been suggested I post a new question.
The issue is that I have a custom adapter that is not showing any data. I have looked into other questions, but it didn't provide a solution.
In my Main Activity I have a couple of buttons, one of them: ToDo, should create a row that displays data from a SQLite database, and depending on some factors (dates mainly), it shows a type of traffic light that is stored as a drawable.
Part of the Items in this Row is an Image Button that I want the user to be able to click and the image should change. The user should be able also to click on the actual row and a new activity starts.
The issue I have is that NO DATA is being displayed.
So, here is my code:
public class MainActivity extends Activity {
// definitions etc ...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// definitions etc ...
}
public void ToDo(View v){ // the user has clicked in the ToDo button
IgroDatabaseHelper helper = new IgroDatabaseHelper(getBaseContext()); // create instance of SQLIte database
numRows = helper.NumEntries("ToDo"); // Get the number of rows in table
int i = 1;
ArrayList<RowItem> rowItems = new ArrayList<>();
RowItem myItem1;
while (i <= numRows){
// get items from database
// depending on value select different drawable
// put data into List Array of RowItem
myItem1 = new RowItem(TheWhat, R.drawable.teamworka, R.drawable.redtrafficlight, R.drawable.checkbox, TheWhenBy);
rowItems.add(myItem1);
//
i = i+ 1;
}
ListView yourListView = (ListView) findViewById(R.id.list);
CustomListViewAdapter customAdapter = new CustomListViewAdapter(this, R.layout.todo_row, rowItems);
yourListView.setAdapter(customAdapter);
}
The CustomListViewAdapter looks like this:
public class CustomListViewAdapter extends ArrayAdapter<RowItem> {
Context context;
ArrayList<RowItem> _rowItems;
public CustomListViewAdapter(Context context, int resourceId,
ArrayList<RowItem> rowItems) {
super(context, resourceId);
this.context = context;
_rowItems = rowItems;
System.out.println("I am in the custom Adapter class "+ _rowItems);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
System.out.println("This is the get view");
View row = convertView;
RowItem item = _rowItems.get(position);
// you can now get your string and drawable from the item
// which you can use however you want in your list
String columnName = item.getColumnName();
int drawable = item.getDrawable();
if (row == null) {
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = mInflater.inflate(R.layout.todo_row, parent, false);
}
ImageButton chkDone = (ImageButton) row.findViewById(R.id.chkDone);
chkDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View parentRow = (View) v.getParent();
ListView listView = (ListView) parentRow.getParent();
final int position = listView.getPositionForView(parentRow);
System.out.println("I am in position "+ position);
}
});
return row;
}
}
The RowItem Class looks like:
public class RowItem {
private String _heading;
private int _icon;
private int _lights;
private int _chkdone;
private String _date;
public RowItem(String heading, int icon, int lights, int chkDone, String date) {
_heading = heading;
_icon = icon;
_lights = lights;
_chkdone = chkDone;
_date = date;
System.out.println("adding stuff to my rows");
System.out.println("my column Name is " + heading);
System.out.println("My drawable int is "+ icon);
}
public String getColumnName() {
System.out.println("column Names is "+ _heading);
return _heading;
}
public int getDrawable() {
return _icon;
}
public int getLights(){
return _lights;
}
public int getchkDone(){
return _chkdone;
}
public String getDate(){
return _date;
}
}
I am obviously missing something, as I mentioned earlier, no data gets shown. I know that there are 2 row items that get passed to the CustomListViewAdapter. But I also know that the View getView inside the CustomListViewAdapter does not actually get called.
I hope I have put enough information/code, but if you feel I need to explain something further, please say.
Thanking all very much in advance!
I don't see a getCount() method. You should be overriding it like this:
#Override
public int getCount() {
return _rowItems.getCount();
}
Alternatively, calling super(context, resourceId, rowItems); should also fix it.
Your ListView thinks there are no items to display. If you are using your own array, you must override the getCount() method to indicate the number of items you want to display.

Refresh GridView contents with custom BaseAdapter

I've tried searching for a solution for this problem for a couple of days and I'm stumped.
Here's what I have so far:
Custom BaseAdapter class:
public static class ImageAdapter extends BaseAdapter {
private static LayoutInflater mInflater;
// Keep all Images in array
private static Bitmap[] mThumbIds;
private static int mViewResourceId, pos;
private static CheckBox cb;
// Constructor
public ImageAdapter(Context ctx, int viewResourceId, Bitmap[] pics) {
mInflater = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mThumbIds = pics;
mViewResourceId = viewResourceId;
}
#Override
public int getCount() {
return mThumbIds.length;
}
#Override
public Object getItem(int position) {
return mThumbIds[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#SuppressWarnings("deprecation")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = mInflater.inflate(mViewResourceId, list, false);
cb = (CheckBox) convertView.findViewById(R.id.select);
Drawable background = new BitmapDrawable(mThumbIds[position]);
cb.setBackgroundDrawable(background);
pos = position;
System.out.println("Setting checkbox set: "+imageIsDup[pos]);
cb.setChecked(imageIsDup[pos]);
System.out.println("Has checkbox been set? "+cb.isChecked());
cb.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (cb.isChecked()) {
imageIsDup[pos] = true;
} else
imageIsDup[pos] = false;
}
});
return convertView;
}
}
Code for setting the gridView:
final Dialog dialog = new Dialog(longOperationContext);
dialog.setContentView(R.layout.activity_list);
TextView no = (TextView) dialog
.findViewById(R.id.noOfDups);
no.setText("Found " + noOfImages
+ " duplicates. Please verify.");
dialog.setTitle("Images Found");
dialog.setCancelable(false);
list = (GridView) dialog
.findViewById(R.id.grid_view);
ImageAdapter empty=new ImageAdapter(longOperationContext, R.layout.row, new Bitmap[0]);
imageAdapter = new ImageAdapter(
longOperationContext, R.layout.row, thumb);
dialog.show();
imageAdapter.notifyDataSetChanged();
list.invalidateViews();
list.setAdapter(empty);
list.setEmptyView(new View(longOperationContext));
list.invalidateViews();
list.setAdapter(imageAdapter);
I assumed that this code would set the gridView to an empty view in the beginning and then to the adapter's contents.
I read from the documentation that the removeView functions cannot be called as they throw an Unsupported Exception. How do I clear the previous contents of the grid view if any and set the new contents?
The whole idea with refreshing adapter's elements in Android is just repopulate them using the same array of objects. For example if I have a GridView like in your case and I want to repopulate the objects the thing you need to do is declare an array of objects first :
private ArrayList<Object> mMyObjects;
populate it with data and create your adapter.
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
mMyObjects = new ArrayList<Object>();
mMyObject.add("StringObject"); // just an example
mMyAdapter = new MyCustomAdapter(this, mMyObject);
mMyGridView.setAdapter(mMyAdapter);
}
So we populate the array of objects and create our adapter. The thing we should do before updating the adapter / gridview's children is just repopulate your array :
mMyObjects.clear();
mMyObjects.add("NewStringObject");
and call : mMyAdapter.notifySetDataChanged(); Doing that BaseAdapter knows that there are changes in out data and it's redrawing it's views and your ListView / GridView will get updated with the new items.
So in your case, to update your GridView just need to clear your array of bitmaps and repopulate it.
I solved my problem with this piece of code:
try{
imageAdapter.notifyDataSetChanged();
}
catch(NullPointerException e)
{
imageAdapter = new ImageAdapter(
longOperationContext, R.layout.row, thumb);
}

How to let OnClick in ListView's Adapter call Activity's function

I have an Android application with a ListView in it, the ListView will setup fine but now I want a image in the ListView to be clickable. I do this by using 2 classes, the Activity class (parent) and an ArrayAdapter to fill the list. In the ArrayAdapter I implement a OnClickListener for the image in the list that I want to be clickable.
So far it all works.
But now I want to run a function from the activity class when the onClick, for the image in the list, is run but I do not know how. Below are the 2 classes that I use.
First the Activity class:
public class parent_class extends Activity implements OnClickListener, OnItemClickListener
{
child_class_list myList;
ListView myListView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// setup the Homelist data
myList = new child_class_list (this, Group_Names, Group_Dates);
myListView = (ListView) findViewById(R.id.list);
// set the HomeList
myListView.setAdapter( myList );
myListView.setOnItemClickListener(this);
}
void function_to_run()
{
// I want to run this function from the LiscView Onclick
}
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
// do something
}
}
And the ArrayAdapter from where I want to call a function from the Activity class:
public class child_class_list extends ArrayAdapter<String>
{
// private
private final Context context;
private String[] mName;
private String[] mDate;
public child_class_list (Context context, String[] Name, String[] Date)
{
super(context, R.layout.l_home, GroupName);
this.context = context;
this.mName = Name;
this.mDate = Date;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.l_home, parent, false);
ImageView selectable_image = (ImageView) rowView.findViewById(R.id.l_selectable_image);
selectable_image.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
// I want to run the function_to_run() function from the parant class here
}
}
);
// get the textID's
TextView tvName = (TextView) rowView.findViewById(R.id.l_name);
TextView tvDate = (TextView) rowView.findViewById(R.id.l_date);
// set the text
tvName.setText (mName[position]);
tvDate.setText (mDate[position]);
return rowView;
}
}
If anyone knows how to run the function in the activity class from the arrayadapter or how to set the image onClickListener in the Activity Class I would greatly apriciate the help.
Inside onClick() Do something like this:
((ParentClass) context).functionToRun();
Just for clarity to expand on provided answers
In a BaseAdapter you can get the parent class by calling this.getActivity();If you then typecast this to the actual activity class you can then call a function as per #AdilSoomro answer below so you actually end up with something like this
public class MyAdapter extends BaseAdapter<Long> {
public MyAdapter(Activity activity,
TreeStateManager<Long> treeStateManager, int numberOfLevels) {
super(activity, treeStateManager, numberOfLevels);
}
#Override
public void handleItemClick(final View view, final Object id) {
((MyActivity) this.activity).someFunction();
}
}
Then just declare someFunction in MyActivity to do what you want
protected void someFunction(){
// Do something here
}

Android listview item doesn't appear

I should write in the title instead of 'doesn't work' something like 'I
don't know how to do it' but the first version feels better :).
What I am trying to do is the following:
Download the xml from the web, parse it and create ArrayList of some
objects (done and working)
Display the objects using custom Adapter (doesn't work)
The second one works if I add the items to my ArrayList before I add it to
the view using
m_orderAdapter = new OrderAdapter(this,m_orders); //code for orderadapter
below
setListAdapter(m_orderAdapter);
I have found on the web something like this: (in my onCreate method)
handler = new Handler();
viewOrders = new Runnable(){
#Override
public void run() {
getOrders();
}
};
new Thread(){
#Override
public void run(){
handler.post(viewOrders);
}
}.start();
then, the following code for the methods:
private void getOrders(){
try{
OrderManager om = new OrderManager();
m_orders = om.getOrdersFromWeb();
Log.i("ARRAY", ""+ m_orders.size());
} catch (Exception e) {
Log.e("BACKGROUND_PROC", e.getMessage());
}
runOnUiThread(returnRes);
}
OrderManager downloads and parse the xml into Order objects and returns
array list of those. Then I set this list to my member array list m_orders.
Once downloading and parsing is done I run returnRes method on the ui thread
using runOnUiThread method
private Runnable returnRes = new Runnable() {
#Override
public void run() {
if(m_orders != null && m_orders.size() > 0){
Log.i("ORDER",m_orders.get(0).getOrder_id());
setListAdapter(m_orderAdapter);
m_orderAdapter.notifyDataSetChanged();
}
m_orderAdapter.notifyDataSetChanged();
}
};
and I call notifyDataSetChanged() on my adapter.
The view I do all this stuff extends ListView and the code for the adapter
itself is listed below:
public class OrderAdapter extends BaseAdapter{
private Context ctx;
private List<Order> orders;
public OrderAdapter(Context ctx, List<Order> orderLst){
this.ctx = ctx;
this.orders = orderLst;
}
#Override
public int getCount() {
return orders.size();
}
#Override
public Object getItem(int pos) {
return orders.get(pos);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Order o = orders.get(position);
return new OrderListAdapterView(this.ctx,o);
}
}
When I debug I have the data inside my m_orders list but when I call
notifyDataSetChanged nothing happens, I've read that I have to execute that
on the UI thread which I think I do. So whats the problem ?
any help highly appreciated, or maybe just a link to the nice tutorial on
the web explaining this issue on how to update the list view at runtime ?
Hey Arutha - why don't you see my answer for this post - I think it is what you need.
Or just let me repost it here
You can extend ArrayAdapter. Here's code example for you. In this example - SearchItem is some custom POJO. Basically you need to override getView() method to build your row by inflating row layout and then populating values based on List of items and current position
class SearchItemsAdapter extends ArrayAdapter<SearchItem> {
Activity context;
List<SearchItem> items;
SearchHeader header;
#SuppressWarnings("unchecked")
public SearchItemsAdapter(final Activity context,
final Map<SearchHeader, List<SearchItem>> result) {
super(context, R.layout.item, (List) ((Object[]) result.values()
.toArray())[0]);
this.context = context;
this.header = result.keySet().iterator().next();
this.items = result.get(this.header);
}
#Override
public View getView(final int position, final View convertView,
final ViewGroup parent) {
final View view = this.context.getLayoutInflater().inflate(
R.layout.item, null);
final SearchItem item = this.items.get(position);
((TextView) view.findViewById(R.id.jt)).setText(item.jt);
((TextView) view.findViewById(R.id.dp)).setText(item.dp);
((TextView) view.findViewById(R.id.cn)).setText(item.cn);
((TextView) view.findViewById(R.id.loc)).setText(item.loc.name);
final TextView body = ((TextView) view.findViewById(R.id.e));
body.setText(item.e);
body.setTag(item.src[0]);
((TextView) view.findViewById(R.id.src)).setText(item.src[1]);
return view;
}
}

Categories

Resources