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
Related
Hi in the below displaying all the images into gridview.gridview images displaying correctly.default gridview will give scroll option,Now Scrolling images it's not scrolling smoothly.
Can any one help me .how to scroll smoothly all the images like normal scrolling.this is my below code any where i did mistake please help me
java
public class GridFragment2 extends Fragment {
private static final String TAG = GridFragment.class.getSimpleName();
public static boolean isSelectedGrid2;
private GridView mGridView;
private ProgressBar mProgressBar;
private GridViewAdapter2 mGridAdapter;
private ArrayList<GridItem> mGridData;
private String FEED_URL = "http://javatechig.com/?json=get_recent_posts&count=45", searchKey;
String vv;
LinearLayout top;
View hr;
String catid;
SharedPreferences imgSh;
SharedPreferences p, got;
public GridFragment2() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_gridview2, container, false);
mGridView = (GridView)rootView.findViewById(R.id.gridView);
mProgressBar = (ProgressBar)rootView.findViewById(R.id.progressBar);
top = (LinearLayout)rootView.findViewById(R.id.top);
hr = rootView.findViewById(R.id.hr);
top.setVisibility(View.GONE);
hr.setVisibility(View.GONE);
imgSh = this.getActivity().getSharedPreferences("data", Context.MODE_APPEND);
p = this.getActivity().getSharedPreferences("gridData", Context.MODE_APPEND);
got = this.getActivity().getSharedPreferences("gotData", Context.MODE_APPEND);
//Initialize with empty data
mGridData = new ArrayList<>();
mGridAdapter = new GridViewAdapter2(rootView.getContext(), R.layout.grid_item_layout2, mGridData);
mGridView.setAdapter(mGridAdapter);
//Grid view click event
mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
//Get item at position
isSelectedGrid2=true;
String catalogueID = p.getString("SelectedCatalogueIdFromGrid1", "");
GridItem item = (GridItem) parent.getItemAtPosition(position);
Intent intent = new Intent(getActivity(), ImageGallery.class);
ImageView imageView = (ImageView) v.findViewById(R.id.grid_item_image);
int[] screenLocation = new int[2];
imageView.getLocationOnScreen(screenLocation);
SharedPreferences prefPosition=getActivity().getSharedPreferences("positionPref", Context.MODE_PRIVATE);
SharedPreferences.Editor positionEditor=prefPosition.edit();
positionEditor.putInt("position", position);
positionEditor.commit();
//Pass the image title and url to DetailsActivity
intent.putExtra("left", screenLocation[0]).
putExtra("top", screenLocation[1]).
putExtra("width", imageView.getWidth()).
putExtra("height", imageView.getHeight()).
putExtra("title", item.getTitle()).
putExtra("image", item.getImage()).
putExtra("catid", catalogueID).putExtra("position",position);
// Log.d("image", (item.getImage()).toString());
//Start details activity
getActivity().finish();
startActivity(intent);
}
});
//Start download
new AsyncHttpTask().execute(FEED_URL);
mProgressBar.setVisibility(View.VISIBLE);
return rootView;
}
//Downloading data asynchronously
public class AsyncHttpTask extends AsyncTask<String, Void, Integer> {
#Override
protected Integer doInBackground(String... params) {
Integer result = 1;
parseResult();
return result;
}
#Override
protected void onPostExecute(Integer result) {
// Download complete. Lets update UI
if (result == 1) {
mGridAdapter.setGridData(mGridData);
} else {
Toast.makeText(getActivity().getBaseContext(), "Failed to fetch data!", Toast.LENGTH_SHORT).show();
}
//Hide progressbar
mProgressBar.setVisibility(View.GONE);
}
}
String streamToString(InputStream stream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
String line;
String result = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
// Close stream
if (null != stream) {
stream.close();
}
return result;
}
private void parseResult() {
catid = p.getString("SelectedCatalogueIdFromGrid1", "");
int clickedPosn = p.getInt("clickedPosition", 0);
int count = p.getInt("numOfImagesInside"+catid+clickedPosn, 0);
Log.d("counterman-id", String.valueOf(count));
GridItem item;
for (int i = 0; i < count; i++) {
item = new GridItem();
item.setTitle("");
// item.setImage("file://" + Environment.getExternalStorageDirectory() + "/" + "thumbImage" + catid + i + ".jpg");
item.setImage("/data/data/com.example.adaptiz.tanishq/"+"thumbImage" + catid + i+".jpg");
// item.setImage(imgSh.getString("thumb" + i, ""));
mGridData.add(item);
}
}
Adapter
public class GridViewAdapter2 extends ArrayAdapter<GridItem> {
//private final ColorMatrixColorFilter grayscaleFilter;
private Context mContext;
private int layoutResourceId;
private ArrayList<GridItem> mGridData = new ArrayList<GridItem>();
public GridViewAdapter2(Context mContext, int layoutResourceId, ArrayList<GridItem> mGridData) {
super(mContext, layoutResourceId, mGridData);
this.layoutResourceId = layoutResourceId;
this.mContext = mContext;
this.mGridData = mGridData;
}
/**
* Updates grid data and refresh grid items.
*
* #param mGridData
*/
public void setGridData(ArrayList<GridItem> mGridData) {
this.mGridData = mGridData;
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder;
if (row == null) {
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
Typeface type_normal = Typeface.createFromAsset(getContext().getAssets(), "HelveticaNeue-Light.otf");
holder = new ViewHolder();
holder.titleTextView = (TextView) row.findViewById(R.id.grid_item_title);
holder.titleTextView.setTypeface(type_normal);
holder.download=(ImageView)row.findViewById(R.id.img);
holder.imageView = (ImageView) row.findViewById(R.id.grid_item_image);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
GridItem item = mGridData.get(position);
holder.titleTextView.setText(Html.fromHtml(item.getTitle()));
File image = new File(item.getImage(), "");
BitmapFactory.Options options = new BitmapFactory.Options();
options.inTempStorage = new byte[16*1024];
options.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(), options);
// bitmap = Bitmap.createScaledBitmap(bitmap, 230, 230, true);
Log.d("the bitmap size", String.valueOf(bitmap.getWidth() + " " + bitmap.getHeight()));
holder.imageView.setImageBitmap(bitmap);
//bitmap=null;
// Picasso.with(mContext).load(item.getImage()).into(holder.imageView);
return row;
}
static class ViewHolder {
TextView titleTextView;
ImageView imageView;
ImageView download;
}
xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/toprel"
>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="30dp"
android:id="#+id/top"
android:orientation="horizontal"
android:layout_alignParentTop="true"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="30dp"
android:id="#+id/searchTitle"
android:layout_centerVertical="true"
android:text="Search"
android:textSize="15sp"
android:gravity="left"
android:layout_toRightOf="#+id/leftTitle"
android:layout_toEndOf="#+id/leftTitle" />
<EditText
android:inputType="text"
android:layout_centerVertical="true"
android:layout_width="200dp"
android:layout_height="30dp"
android:id="#+id/searchBox"
android:background="#drawable/searchbg2x"
android:layout_toRightOf="#+id/searchTitle"
android:layout_toEndOf="#+id/searchTitle"
android:layout_marginLeft="15dp"
android:singleLine="true"
android:imeOptions="actionSearch"
/>
</LinearLayout>
<View
android:layout_marginTop="5dp"
android:layout_width="match_parent"
android:layout_height="1dp"
android:id="#+id/hr"
android:background="#000000"
android:layout_below="#id/top"
/>
<GridView
android:layout_below="#+id/hr"
android:id="#+id/gridView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:columnWidth="200dp"
android:gravity="center"
android:numColumns="4"
android:stretchMode="columnWidth"
android:verticalSpacing="5dp"
android:listSelector="#android:color/transparent"
android:clickable="true"
android:fastScrollEnabled="true"/>
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/progressBar"
android:layout_centerInParent="true"
android:visibility="gone"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="20dp"
android:orientation="horizontal"
android:id="#+id/userlayout"
android:layout_alignParentTop="true"
android:visibility="gone"
android:layout_alignRight="#+id/gridView"
android:layout_alignEnd="#+id/gridView"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:textSize="18sp"
android:id="#+id/userView"
android:text="username"
/>
<ImageView
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_width="20dp"
android:layout_height="10dp"
android:background="#drawable/icon"
/>
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textSize="15sp"
android:layout_gravity="bottom"
android:layout_alignBottom="#+id/gridView"
android:layout_centerHorizontal="true" />
</RelativeLayout>
For that you have to use Image Loader to load image.
Refer below link for that.
http://www.androidhive.info/2012/07/android-loading-image-from-url-http/
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;
}
}
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();
}
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;
}
}
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