Using Picasso library with ListView - android

What I'm trying to do is adapt my custom ListView adapter to use images fetched from the web by the Picasso library. I believe I have my adapter changed in order to accept an image from Picasso, but I am unsure how to change my implementation to accept it using a ListView. I believe I have to access holder.imageIcon, but I am not sure how to get it up and running. My code is as follows.
History.java
public class History {
public String score;
public String gametype;
public Picasso icon;
public History() {
super();
}
public History(String score, String gametype, Picasso icon) {
super();
this.score = score;
this.gametype = gametype;
this.icon = icon;
}
}
HistoryAdapter.java
public class HistoryAdapter extends ArrayAdapter<History> {
Context context;
int layoutResId;
History data[] = null;
public HistoryAdapter(Context context, int layoutResId, History[] data) {
super(context, layoutResId, data);
this.layoutResId = layoutResId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
HistoryHolder holder = null;
if(convertView == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
convertView = inflater.inflate(layoutResId, parent, false);
holder = new HistoryHolder();
holder.imageIcon = (ImageView)convertView.findViewById(R.id.icon);
holder.textTitle = (TextView)convertView.findViewById(R.id.gameType);
holder.textScore = (TextView)convertView.findViewById(R.id.score);
convertView.setTag(holder);
}
else
{
holder = (HistoryHolder)convertView.getTag();
}
History history = data[position];
holder.textScore.setText(history.score);
holder.textTitle.setText(history.gametype);
holder.imageIcon.setImageResource(history.icon);
return convertView;
}
static class HistoryHolder
{
ImageView imageIcon;
TextView textTitle;
TextView textScore;
}
}
Implementation
History[] historyData = new History[games.length()];
for(int i = 0; i < games.length(); i++) {
JSONObject c = games.getJSONObject(i);
JSONObject gameStats = games.getJSONObject(i).getJSONObject(TAG_STATS);
type[i] = c.getString(TAG_TYPE);
champId[i] = c.getString("championId");
cs[i] = gameStats.getString("minionsKilled");
kills[i] = gameStats.getString("championsKilled");
deaths[i] = gameStats.getString("numDeaths");
assists[i] = gameStats.getString("assists");
win[i] = gameStats.getString("win");
if(win[i].equals("true"))
win[i] = "Victory";
else
win[i] = "Defeat";
if(type[i].equals("RANKED_SOLO_5x5"))
type[i] = "Ranked (Solo)";
if(type[i].equals("CAP_5x5"))
type[i] = "TeamBuilder";
if(type[i].equals("NORMAL"))
type[i] = "Unranked";
score[i] = kills[i] +"/" + deaths[i] + "/" + assists[i];
historyData[i] = new History(score[i], champId[i], R.drawable.ic_launcher); // Placeholder image
}
if(historyData == null) {
historyData[0] = new History("No game found", "N/A", R.drawable.ic_launcher); // Use Picasso placeholder
Log.i("Data", "" + historyData);
}
adapter = new HistoryAdapter(MatchHistoryActivity.this,
R.layout.list_adapter,
historyData);
list.setAdapter(adapter);
list_item.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:background="#111111"
android:padding="6dip" >
<ImageView
android:id="#+id/icon"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
android:layout_marginRight="6dip"
android:contentDescription="TODO"
android:src="#drawable/ic_launcher" />
<TextView
android:id="#+id/score"
android:textColor="#C49246"
android:layout_width="fill_parent"
android:layout_height="26dip"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#id/icon"
android:ellipsize="marquee"
android:singleLine="true"
android:text="0/0/0 KDA"
android:textSize="12sp" />
<TextView
android:id="#+id/gameType"
android:textColor="#C49246"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#id/score"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_alignWithParentIfMissing="true"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#id/icon"
android:gravity="center_vertical"
android:textSize="16sp" />
</RelativeLayout>

There are 2 things you need to change:
1) History.icon should be the String url of the icon, not a Picasso object. You can also use a File, Uri, or int, but a String url is probably what you want.
2) Modify your Adapter's getView() method to load the icon using Picasso (see the last line before getView() returns the convertView):
public class HistoryAdapter extends ArrayAdapter<History> {
Context context;
int layoutResId;
History data[] = null;
public HistoryAdapter(Context context, int layoutResId, History[] data) {
super(context, layoutResId, data);
this.layoutResId = layoutResId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
HistoryHolder holder = null;
if(convertView == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
convertView = inflater.inflate(layoutResId, parent, false);
holder = new HistoryHolder();
holder.imageIcon = (ImageView)convertView.findViewById(R.id.icon);
holder.textTitle = (TextView)convertView.findViewById(R.id.gameType);
holder.textScore = (TextView)convertView.findViewById(R.id.score);
convertView.setTag(holder);
}
else
{
holder = (HistoryHolder)convertView.getTag();
}
History history = data[position];
holder.textScore.setText(history.score);
holder.textTitle.setText(history.gametype);
Picasso.with(this.context).load(history.icon).into(holder.imageIcon)
return convertView;
}
static class HistoryHolder
{
ImageView imageIcon;
TextView textTitle;
TextView textScore;
}
}

Related

want to add two textview in a custom listview

I am trying to add two textviews in a custom listview. It shows the data but not combined them. It shows as a different layouts.
This is the custom listview.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/rollnoText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
android:layout_marginRight="5dip"
android:layout_marginLeft="5dip"
android:background="#drawable/custom_stuadd_drawable"
android:paddingLeft="10dip"
android:textColor="#android:color/primary_text_light"
/>
<TextView
android:id="#+id/stunameText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="0dip"
android:background="#00dcdcdc"
android:paddingLeft="10dip"
android:textColor="#b9dcdcdc"
android:layout_below="#+id/rollnoText"
/>
</RelativeLayout>
This is CustomAdapter class
public CustomStuDataAdapter(Context context, int resource, List<String> objects) {
super(context, R.layout.custom_student_data, objects);
}
static class ViewHolder{
TextView Roll_No;
TextView Stu_Name;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
LayoutInflater StuInflater = LayoutInflater.from(getContext());
convertView = StuInflater.inflate(R.layout.custom_student_data, parent, false);
viewHolder = new ViewHolder();
//String str = getItem(position);
viewHolder.Roll_No = (TextView) convertView.findViewById(R.id.rollnoText);
viewHolder.Stu_Name = (TextView)convertView.findViewById(R.id.stunameText);
// System.out.println(stnm);
// rno=getItem(position);
viewHolder.Roll_No.setText(getItem(position));
// stnm=getItem(position);
//viewHolder.Stu_Name.setText(getItem(position));
convertView.setTag(viewHolder);
return convertView;
}
This is the main class
List<String> details = new ArrayList<String>();
studbhandler = new CourseDbHandler(this, null, null, 1);
Cursor c = studbhandler.stuData(tbnm);
c.moveToFirst();
if(c.equals(null)){
System.out.println("NO DATA");
}
else {
if(c.moveToFirst()) {
do {
rn=c.getString(0);
details.add(rn);
nm=c.getString(1);
details.add(nm);
} while (c.moveToNext());
studlist = (ListView)findViewById(R.id.studentList);
ListAdapter stuAdapter = new CustomStuDataAdapter(this,R.layout.activity_add_student,details);
studlist.setAdapter(stuAdapter);
}
}
output comes as this
here i want to combine two rows like first and second then third and fourth and so on...
use this layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation:"horizontal" >
<TextView
android:id="#+id/rollnoText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
android:layout_marginRight="5dip"
android:layout_marginLeft="5dip"
android:background="#drawable/custom_stuadd_drawable"
android:paddingLeft="10dip"
android:textColor="#android:color/primary_text_light"
/>
<TextView
android:id="#+id/stunameText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
android:background="#00dcdcdc"
android:paddingLeft="10dip"
android:textColor="#b9dcdcdc"
android:layout_below="#+id/rollnoText"
/>
</LinearLayout>
Add your custom layout Textview
android:layout_toLeftOf="#+id/rollnoText"
Remove
android:layout_below="#+id/rollnoText"
TextView like as below
<TextView
android:id="#+id/stunameText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="0dip"
android:background="#00dcdcdc"
android:paddingLeft="10dip"
android:textColor="#b9dcdcdc"
android:layout_toLeftOf="#+id/rollnoText"
/>
You need to create your model class first I assumed you are making it for student so name it to StudentModel :
public class StudentModel
{
public String name;
public String rollno;
public StudentModel(String _name,String _rollno)
{
name = _name;
rollno = _rollno;
}
}
Now your custome List Adapter Class
public class CustomStuDataAdapter extends ArrayAdapter<StudentModel> {
Context _context;
private ArrayList<StudentModel> objects;
LayoutInflater inflater;
public CustomStuDataAdapter (Context context,
ArrayList<StudentModel> objects) {
super(context,0, objects);
this.objects = objects;
_context = context;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
static class ViewHolder{
TextView Roll_No;
TextView Stu_Name;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
int viewType = this.getItemViewType(position);
StudentModel item = objects.get(position);
// convertView = null;
View rootView = convertView;
final ViewHolder viewHolder;
if (rootView == null) {
viewHolder= new ViewHolder();
rootView = inflater.inflate(R.layout.you_list_view_row,
parent, false);
viewHolder.Roll_No = (TextView) rootView .findViewById(R.id.rollnoText);
viewHolder.Stu_Name = (TextView)rootView .findViewById(R.id.stunameText);
rootView.setTag(viewHolder);
}
else {
viewHolder= (ViewHolder) rootView.getTag();
}
viewHolder.Roll_No.setText(item.rollno);
viewHolder.Stu_Name.setText(item.name);
return rootview;
}
}
Now how to call it :
ArrayList<StudentModel> details = new ArrayList<StudentModel>();
studbhandler = new CourseDbHandler(this, null, null, 1);
Cursor c = studbhandler.stuData(tbnm);
c.moveToFirst();
while(c.isAfterLast() == false){
rn=c.getString(0);
nm=c.getString(1);
details.add(new StudentModel(nm,rn));
c.moveToNext();
}
CustomStuDataAdapter adapter = new CustomStuDataAdapter(this, details);
listview.setAdapter(adapter);
Create custom model class like this,
public class Details {
private String rollNo;
private String stuName;
public Details(String rollNo, String surName){
this.rollNo = rollNo;
this.stuName = stuName;
}
public String getRollNo(){
return this.rollNo;
}
public String getStuName(){
return this.stuName;
}
}
And change your List<String> to List<Details> detailsList = new ArrayList<Details>();
And your do while method should be like this.
Details details;
do {
details = new Details(c.getString(0),c.getString(1));
detailsList.add(details);
} while (c.moveToNext());
And your CustomStuDataAdapter should start like this,
public CustomStuDataAdapter(Context context, int resource, List<Details> objects) {
And in your getView,
viewHolder.Roll_No.setText(getItem(position).getRollNo());
viewHolder.Stu_Name.setText(getItem(position).getStuName());
That's all.

Listview adapter doesnt show textview

I got a ListView Adapter. In this adapter , i fill it with some data .My problem is that it shows my date only after i scroll down and don't understand what's the problem , any ideas??
public class EventsAdapter extends ArrayAdapter<Article> {
EventsAdapter adapter = this;
Context context;
int layoutResourceId;
ArrayList<Article> cartItems = new ArrayList<Article>();
Date time;
public EventsAdapter(Context context, int layoutResourceId,
ArrayList<Article> galleries) {
super(context, layoutResourceId, galleries);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.cartItems = galleries;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final Article eventItem = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.event_item_row, parent, false);
}
Typeface cFont2 = Typeface.createFromAsset(context.getAssets(), "fonts/berthold_baskerville_bold-webfont.ttf");
final RecordHolder holder = new RecordHolder();
holder.eventImage = (ImageView) convertView.findViewById(R.id.event_image);
holder.eventTitle = (TextView) convertView.findViewById(R.id.event_title);
holder.eventTitleDescription = (TextView) convertView.findViewById(R.id.event_title_description);
holder.eventCountries = (TextView) convertView.findViewById(R.id.event_countries);
holder.eventRegions = (TextView) convertView.findViewById(R.id.event_regions);
holder.eventCategory = (TextView) convertView.findViewById(R.id.event_category);
holder.eventType = (TextView) convertView.findViewById(R.id.event_type);
holder.eventDate = (TextView) convertView.findViewById(R.id.event_date);
holder.salary = (TextView) convertView.findViewById(R.id.job_salary);
holder.eventTitle.setTypeface(cFont2);
holder.salary.setVisibility(View.GONE);
holder.eventImage.setVisibility(View.GONE);
if (!eventItem.getImageURL().equals("")) {
holder.eventImage.setVisibility(View.VISIBLE);
Picasso.with(context)
.load(eventItem.getImageURL())
.resize(250, 175)
.into(holder.eventImage);
}
holder.eventTitle.setText(eventItem.getName());
if (eventItem.getCountry() == null) {
holder.eventCountries.setText(context.getString(R.string.all_countries));
} else {
holder.eventCountries.setText(eventItem.getCountry().getName());
}
if (eventItem.getRegion() == null) {
holder.eventRegions.setText(context.getString(R.string.all_regions));
} else {
holder.eventRegions.setText(eventItem.getRegion().getName());
}
boolean startDate = false;
boolean endDate = false;
String endDateString = "";
String startDateString = "";
for (int i = 0; i < eventItem.getExtraFields().size(); i++) {
if (eventItem.getExtraFields().get(i).getName().equals("EVENTENDDATE") && !eventItem.getExtraFields().get(i).getValue().getValue().equals("")) {
endDate = true;
endDateString = new SimpleDateFormat("dd/MM/yyyy").format(getDate(eventItem.getExtraFields().get(i).getValue().getValue()));
}
}
for (int i = 0; i < eventItem.getExtraFields().size(); i++) {
if (eventItem.getExtraFields().get(i).getName().equals("EVENTSTARTDATE") && !eventItem.getExtraFields().get(i).getValue().getValue().equals("")) {
startDate = true;
startDateString = new SimpleDateFormat("dd/MM/yyyy").format(getDate(eventItem.getExtraFields().get(i).getValue().getValue()));
}
}
if (startDate && endDate) {
holder.eventDate.setText(startDateString + " - " + endDateString);
holder.eventDate.setVisibility(View.VISIBLE);
} else if (startDate) {
holder.eventDate.setText(startDateString);
holder.eventDate.setVisibility(View.VISIBLE);
} else {
holder.eventDate.setVisibility(View.VISIBLE);
}
for (int i = 0; i < eventItem.getExtraFields().size(); i++) {
if (eventItem.getExtraFields().get(i).getName().equals("EVENTORGANISER")) {
holder.eventTitleDescription.setText(eventItem.getExtraFields().get(i).getValue().getValue());
} else if (eventItem.getExtraFields().get(i).getName().equals("EVENTTYPE")) {
holder.eventType.setVisibility(View.VISIBLE);
holder.eventType.setText(eventItem.getExtraFields().get(i).getValue().getValue());
}
}
holder.eventCategory.setText(eventItem.getCategories().get(0).getName());
return convertView;
}
private Date getDate(String date) {
String json = date;
String timeString = json.substring(json.indexOf("(") + 1, json.indexOf(")"));
String[] timeSegments = timeString.split("\\+");
// May have to handle negative timezones
int timeZoneOffSet = Integer.valueOf(timeSegments[1]) * 36000; // (("0100" / 100) * 3600 * 1000)
long millis = Long.valueOf(timeSegments[0]);
time = new Date(millis + timeZoneOffSet);
return time;
}
static class RecordHolder {
TextView salary;
ImageView eventImage;
TextView eventTitle;
TextView eventTitleDescription;
TextView eventCountries;
TextView eventRegions;
TextView eventCategory;
TextView eventType;
TextView eventDate;
}
}
Have i done something wrong or it is an android visual bug ??
UPDATED:
event_item_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#ebf5fb"
android:padding="10dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:visibility="gone"
android:id="#+id/event_image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="10dp"
android:layout_centerInParent="true"/>
</RelativeLayout>
<TextView
android:id="#+id/event_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#043c5b"
android:textStyle="bold"
android:singleLine="true"
android:textSize="17sp"
android:paddingBottom="10dp"/>
<TextView
android:id="#+id/event_title_description"
android:layout_width="wrap_content"
android:singleLine="true"
android:layout_height="wrap_content"
android:textColor="#7c7f7e"/>
<TextView
android:id="#+id/event_countries"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#7c7f7e"/>
<TextView
android:id="#+id/event_regions"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#7c7f7e"/>
<TextView
android:id="#+id/event_category"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#7c7f7e"/>
<TextView
android:visibility="gone"
android:id="#+id/event_type"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#7c7f7e"/>
<TextView
android:visibility="gone"
android:id="#+id/job_salary"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#7c7f7e"
android:text="#string/salary"/>
<TextView
android:visibility="gone"
android:id="#+id/event_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#7c7f7e"/>
</LinearLayout>
Got it ,Please update your null checking .
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater=(LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ViewHolder holder;
convertView = null;
if(convertView == null){
holder = new ViewHolder();
convertView = inflater.from(activity).inflate(R.layout.community_common_tab_layout, null);
holder.DashBoard_Tab_List_Root=(LinearLayout)convertView.findViewById(R.id.Community_Common_Root);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.name.setText( dataArray.get(position).countryName);
holder.language.setText( dataArray.get(position).language);
holder.Capital.setText( dataArray.get(position).capital);
return convertView;
}
public static class ViewHolder {
public LinearLayout DashBoard_Tab_List_Root;
public TextView Tv_Badge_View;
}
}

Nothing showing on screen with custom listview adapter

As the title states, I'm having some troubles getting my custom listview adapter to work properly. The app displays nothing on the list, and gives just a blank white screen. I tested my data with a simple list I already have setup, and that worked just fine.
History.java
public class History {
public String score;
public String gametype;
public int icon;
public History() {
super();
}
public History(String score, String gametype, int icon) {
super();
this.score = score;
this.gametype = gametype;
this.icon = icon;
}
}
HistoryAdapter.java
public class HistoryAdapter extends ArrayAdapter<History> {
Context context;
int layoutResId;
History data[] = null;
public HistoryAdapter(Context context, int layoutResId, History[] data) {
super(context, layoutResId, data);
this.layoutResId = layoutResId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
HistoryHolder holder = null;
if(convertView == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
convertView = inflater.inflate(layoutResId, parent, false);
holder = new HistoryHolder();
holder.imageIcon = (ImageView)convertView.findViewById(R.id.icon);
holder.textTitle = (TextView)convertView.findViewById(R.id.gameType);
holder.textScore = (TextView)convertView.findViewById(R.id.score);
convertView.setTag(holder);
}
else
{
holder = (HistoryHolder)convertView.getTag();
}
History history = data[position];
holder.textScore.setText(history.score);
holder.textTitle.setText(history.gametype);
holder.imageIcon.setImageResource(history.icon);
return convertView;
}
static class HistoryHolder
{
ImageView imageIcon;
TextView textTitle;
TextView textScore;
}
}
Implementation
for(int i = 0; i < games.length(); i++) {
JSONObject c = games.getJSONObject(i);
JSONObject gameStats = games.getJSONObject(i).getJSONObject(TAG_STATS);
type[i] = c.getString(TAG_TYPE);
champId[i] = c.getString("championId");
cs[i] = gameStats.getString("minionsKilled");
kills[i] = gameStats.getString("championsKilled");
deaths[i] = gameStats.getString("numDeaths");
assists[i] = gameStats.getString("assists");
win[i] = gameStats.getString("win");
if(win[i].equals("true"))
win[i] = "Victory";
else
win[i] = "Defeat";
if(type[i].equals("RANKED_SOLO_5x5"))
type[i] = "Ranked (Solo)";
if(type[i].equals("CAP_5x5"))
type[i] = "TeamBuilder";
if(type[i].equals("NORMAL"))
type[i] = "Unranked";
score[i] = kills[i] +"/" + deaths[i] + "/" + assists[i];
historyData[i] = new History(score[i], champId[i], R.drawable.ic_launcher); // Placeholder image
}
adapter = new HistoryAdapter(MatchHistoryActivity.this,
R.layout.list_adapter,
historyData);
list.setAdapter(adapter);
listview.xml
<?xml version="1.0" encoding="utf-8"?>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/list"
android:background="#111111">
</ListView>
list_item.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:background="#111111"
android:padding="6dip" >
<ImageView
android:id="#+id/icon"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
android:layout_marginRight="6dip"
android:contentDescription="TODO"
android:src="#drawable/ic_launcher" />
<TextView
android:id="#+id/score"
android:textColor="#C49246"
android:layout_width="fill_parent"
android:layout_height="26dip"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#id/icon"
android:ellipsize="marquee"
android:singleLine="true"
android:text="0/0/0 KDA"
android:textSize="12sp" />
<TextView
android:id="#+id/gameType"
android:textColor="#C49246"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#id/score"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_alignWithParentIfMissing="true"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#id/icon"
android:gravity="center_vertical"
android:textSize="16sp" />
</RelativeLayout>
I think you should replace ArrayAdapter by BaseAdapter and implement all required method e.g. getItemId(), getItem(), getCount(), getView().
It should work fine!.
Below is example code of mine, dont care about what is MusicModel.
protected class MusicCustomAdapter extends BaseAdapter {
private Activity context;
private List<MusicModel> musicModelList;
private SimpleDateFormat sdf = new SimpleDateFormat("mm:ss");
public MusicCustomAdapter(Activity context, List<MusicModel> musicModelList) {
this.context = context;
this.musicModelList = musicModelList;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public Object getItem(int position) {
return this.musicModelList.get(position);
}
#Override
public int getCount() {
return this.musicModelList.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = context.getLayoutInflater().inflate(R.layout.song_item, null);
}
MusicModel musicModel = (MusicModel) getItem(position);
TextView tvMusicName = (TextView) view.findViewById(R.id.tv_song_name);
tvMusicName.setText(musicModel.getName());
TextView tvArtist = (TextView) view.findViewById(R.id.tv_artist);
tvArtist.setText(musicModel.getArtist());
TextView tvDuration = (TextView) view.findViewById(R.id.tv_duration);
tvDuration.setText(sdf.format(musicModel.getDuration()));
ImageView imgThumbnail = (ImageView) view.findViewById(R.id.img_thumbnail);
imgThumbnail.setImageDrawable(musicModel.getThumbnail());
return view;
}
}
Hope this help.
You need to override getCount() in your custom adapter.
It will return the number of entries in your ListView.
#Override
public int getCount() {
return myArrayList.size();
}

ListView displaying nothing with custom adapter

As the title states, I'm having some troubles getting my custom listview to work properly. The app displays nothing on the list, and gives just a blank white screen. I tested my data with a simple list I already have setup, and that worked just fine. I'm hoping someone can see something I haven't. Thanks.
History.java
public class History {
public String score;
public String gametype;
public int icon;
public History() {
super();
}
public History(String score, String gametype, int icon) {
super();
this.score = score;
this.gametype = gametype;
this.icon = icon;
}
}
HistoryAdapter.java
public class HistoryAdapter extends ArrayAdapter<History> {
Context context;
int layoutResId;
History data[] = null;
public HistoryAdapter(Context context, int layoutResId, History[] data) {
super(context, layoutResId, data);
this.layoutResId = layoutResId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
HistoryHolder holder = null;
if(convertView == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
convertView = inflater.inflate(layoutResId, parent, false);
holder = new HistoryHolder();
holder.imageIcon = (ImageView)convertView.findViewById(R.id.icon);
holder.textTitle = (TextView)convertView.findViewById(R.id.gameType);
holder.textScore = (TextView)convertView.findViewById(R.id.score);
convertView.setTag(holder);
}
else
{
holder = (HistoryHolder)convertView.getTag();
}
History history = data[position];
holder.textScore.setText(history.score);
holder.textTitle.setText(history.gametype);
holder.imageIcon.setImageResource(history.icon);
return convertView;
}
static class HistoryHolder
{
ImageView imageIcon;
TextView textTitle;
TextView textScore;
}
}
Implementation
History[] historyData = new History[games.length()];
for(int i = 0; i < games.length(); i++) {
JSONObject c = games.getJSONObject(i);
JSONObject gameStats = games.getJSONObject(i).getJSONObject(TAG_STATS);
type[i] = c.getString(TAG_TYPE);
champId[i] = c.getString("championId");
cs[i] = gameStats.getString("minionsKilled");
kills[i] = gameStats.getString("championsKilled");
deaths[i] = gameStats.getString("numDeaths");
assists[i] = gameStats.getString("assists");
win[i] = gameStats.getString("win");
if(win[i].equals("true"))
win[i] = "Victory";
else
win[i] = "Defeat";
if(type[i].equals("RANKED_SOLO_5x5"))
type[i] = "Ranked (Solo)";
if(type[i].equals("CAP_5x5"))
type[i] = "TeamBuilder";
if(type[i].equals("NORMAL"))
type[i] = "Unranked";
score[i] = kills[i] +"/" + deaths[i] + "/" + assists[i];
historyData[i] = new History(score[i], champId[i], R.drawable.ic_launcher); // Placeholder image
}
if(historyData == null) {
historyData[0] = new History("No game found", "N/A", R.drawable.ic_launcher);
Log.i("Data", "" + historyData);
}
adapter = new HistoryAdapter(MatchHistoryActivity.this,
R.layout.list_adapter,
historyData);
list.setAdapter(adapter);
listview.xml
<?xml version="1.0" encoding="utf-8"?>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/list"
android:background="#111111">
</ListView>
list_item.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:background="#111111"
android:padding="6dip" >
<ImageView
android:id="#+id/icon"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
android:layout_marginRight="6dip"
android:contentDescription="TODO"
android:src="#drawable/ic_launcher" />
<TextView
android:id="#+id/score"
android:textColor="#C49246"
android:layout_width="fill_parent"
android:layout_height="26dip"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#id/icon"
android:ellipsize="marquee"
android:singleLine="true"
android:text="0/0/0 KDA"
android:textSize="12sp" />
<TextView
android:id="#+id/gameType"
android:textColor="#C49246"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#id/score"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_alignWithParentIfMissing="true"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#id/icon"
android:gravity="center_vertical"
android:textSize="16sp" />
</RelativeLayout>
The code you've included seems fine, so the only point where it can fail is in the loop where you create the historyData array.
For some reason you might not be processing it correctly, for instance, some JSON attributes not being defined sometimes.
You can use a try block and catch a JSONException to see what's wrong, and also add several Log.d() sentences to know where's the culprit.
For instance:
try {
cs[i] = gameStats.getString("minionsKilled");
}
catch (JSONException) { e.printStackTrace(); }
I guess you are using wrong XML
Change
adapter = new HistoryAdapter(MatchHistoryActivity.this,
R.layout.list_adapter,historyData);
to
adapter = new HistoryAdapter(MatchHistoryActivity.this,
R.layout.list_item,historyData);
and make sure that your historyData is not null

Having an issue with a custom listview adapter

As the title states, I'm having some troubles getting my custom listView adapter to work. The app doesn't crash, but it also displays nothing on the list. I tested my data with a simple list I already have setup, and that worked just fine.
History.java
public class History {
public String score;
public String gametype;
public int icon;
public History() {
super();
}
public History(String score, String gametype, int icon) {
super();
this.score = score;
this.gametype = gametype;
this.icon = icon;
}
}
HistoryAdapter.java
public class HistoryAdapter extends ArrayAdapter<History> {
Context context;
int layoutResId;
History data[] = null;
public HistoryAdapter(Context context, int layoutResId, History[] data) {
super(context, layoutResId, data);
this.layoutResId = layoutResId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
HistoryHolder holder = null;
if(convertView == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
convertView = inflater.inflate(layoutResId, parent, false);
holder = new HistoryHolder();
holder.imageIcon = (ImageView)convertView.findViewById(R.id.icon);
holder.textTitle = (TextView)convertView.findViewById(R.id.gameType);
holder.textScore = (TextView)convertView.findViewById(R.id.score);
convertView.setTag(holder);
}
else
{
holder = (HistoryHolder)convertView.getTag();
}
History history = data[position];
holder.textScore.setText(history.score);
holder.textTitle.setText(history.gametype);
holder.imageIcon.setImageResource(history.icon);
return convertView;
}
static class HistoryHolder
{
ImageView imageIcon;
TextView textTitle;
TextView textScore;
}
}
Implementation
for(int i = 0; i < games.length(); i++) {
JSONObject c = games.getJSONObject(i);
JSONObject gameStats = games.getJSONObject(i).getJSONObject(TAG_STATS);
type[i] = c.getString(TAG_TYPE);
champId[i] = c.getString("championId");
cs[i] = gameStats.getString("minionsKilled");
kills[i] = gameStats.getString("championsKilled");
deaths[i] = gameStats.getString("numDeaths");
assists[i] = gameStats.getString("assists");
win[i] = gameStats.getString("win");
if(win[i].equals("true"))
win[i] = "Victory";
else
win[i] = "Defeat";
if(type[i].equals("RANKED_SOLO_5x5"))
type[i] = "Ranked (Solo)";
if(type[i].equals("CAP_5x5"))
type[i] = "TeamBuilder";
if(type[i].equals("NORMAL"))
type[i] = "Unranked";
score[i] = kills[i] +"/" + deaths[i] + "/" + assists[i];
historyData[i] = new History(score[i], champId[i], R.drawable.ic_launcher); // Placeholder image
}
adapter = new HistoryAdapter(MatchHistoryActivity.this,
R.layout.list_adapter,
historyData);
list.setAdapter(adapter);
listview.xml
<?xml version="1.0" encoding="utf-8"?>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/list"
android:background="#111111">
</ListView>
list_item.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:background="#111111"
android:padding="6dip" >
<ImageView
android:id="#+id/icon"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
android:layout_marginRight="6dip"
android:contentDescription="TODO"
android:src="#drawable/ic_launcher" />
<TextView
android:id="#+id/score"
android:textColor="#C49246"
android:layout_width="fill_parent"
android:layout_height="26dip"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#id/icon"
android:ellipsize="marquee"
android:singleLine="true"
android:text="0/0/0 KDA"
android:textSize="12sp" />
<TextView
android:id="#+id/gameType"
android:textColor="#C49246"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#id/score"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_alignWithParentIfMissing="true"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#id/icon"
android:gravity="center_vertical"
android:textSize="16sp" />
</RelativeLayout>
You are creating a History object with this line:
new History(score[i], champId[i], R.drawable.ic_launcher); // Placeholder image
This just calls the constructor and creates an object for the garbage collector to take away again.
You are not actually adding this History object to the historyData array.
Before the loop, you should declare the historyData array as:
History[] historyData = new History[games.length();
And in the loop, you should assign the created object to the array
historyData[i] = new History(score[i], champId[i], R.drawable.ic_launcher); // Placeholder image

Categories

Resources