ListView with ImageView and TextView doesn't show anything - android

I'm populating a ListView which contains an ImageView and a TextView. It doesn't crash, but doesn't show anything either. I see a lot of tutorials but appear to show the same code as I am using.
This is the row.xml
<?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"
android:background="#drawable/fondo_fila_click"
android:orientation="horizontal"
android:padding="5dip" >
<LinearLayout android:id="#+id/thumbnail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="3dip"
android:layout_alignParentLeft="true"
android:background="#drawable/borde_foto"
android:layout_marginRight="5dip">
<ImageView
android:id="#+id/imagen_marca"
android:layout_width="50dip"
android:layout_height="50dip"/>
</LinearLayout>
<TextView
android:id="#+id/nombre"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/thumbnail"
android:layout_toRightOf="#+id/thumbnail"
android:textColor="#040404"
android:typeface="sans"
android:textSize="15dip"
android:textStyle="bold"/>
</RelativeLayout>
And the code:
public class SATActivity extends SherlockListActivity {
private IconListViewAdapter adaptador;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList m_fabricante = new ArrayList();
this.adaptador = new IconListViewAdapter(this, R.layout.fila, m_fabricante);
setListAdapter(this.adaptador);
iniciaFabricantes();
}
#SuppressWarnings("unchecked")
private void iniciaFabricantes() {
ArrayList m_fabricante = new ArrayList();
try {
Fabricante acer = new Fabricante();
acer.setNombre("Acer");
acer.setFoto(R.drawable.acer);
Fabricante apple = new Fabricante();
apple.setNombre("Apple");
apple.setFoto(R.drawable.apple);
m_fabricante.add(acer);
m_fabricante.add(apple);
} catch (Exception e) {
}
adaptador.notifyDataSetChanged();
}
public class IconListViewAdapter extends ArrayAdapter<Fabricante> {
private ArrayList<Fabricante> items;
public IconListViewAdapter(Context context, int textViewResourceId, ArrayList<Fabricante> items) {
super(context, textViewResourceId, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.row, null);
}
Fabricante o = items.get(position);
if (o != null) {
//poblamos la lista de elementos
TextView tt = (TextView) v.findViewById(R.id.nombre);
ImageView im = (ImageView) v.findViewById(R.id.imagen_marca);
if (im!= null) {
im.setImageResource(o.getFoto());
}
if (tt != null) {
tt.setText(o.getNombre());
}
}
return v;
}
}
}
Does anyone know why it doesn't show the text or the images?
Thanks

Try changing your adapter class to below one:
public class IconListViewAdapter extends ArrayAdapter<Fabricante> {
private ArrayList<Fabricante> items;
LayoutInflater mInflater;
public IconListViewAdapter(Context context, int textViewResourceId, ArrayList<Fabricante> items) {
super(context, textViewResourceId, items);
this.items = items;
mInflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row, null);
holder = new ViewHolder();
holder.mTextView=(TextView)convertView.findViewById(R.id.nombre);
holder.mImageView=(ImageView)convertView.findViewById(R.id.imagen_marca);
convertView.setTag(holder);
}
else
holder=(ViewHolder)convertView.getTag();
Fabricante o = items.get(position);
if (o != null) {
//poblamos la lista de elementos
holder.mImageView.setImageResource(o.getFoto());
holder.mTextView.setText(o.getNombre());
}
return convertView;
}
static class ViewHolder
{
TextView mTextView;
ImageView mImageView;
}
}

In your getView method, make the following change:
if (im!= null) {
Drawable d = context.getResources().getDrawable(o.getFoto());
d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());//must require
if(d!=null)
im.setImageDrawable(d);
else
Log.w("listview", "drawable is not available");
}
Hopefully then it should work.

Try adding a ViewHolder as well as calling your findViewById in your if statement where you inflate the view. http://www.vogella.de/articles/AndroidListView/article.html#overview should help with your custom adapter.

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.

Android: Custom ArrayAdapter not working, getView() not getting called

I am using CustomArrayAdapter with ListView. But, even after setting setAdapter it is not working. Following are my code snippets:
PastOrders.java Fragment displaying listView
public class PastOrders extends Fragment {
private View view;
private ListView pastOrdersList;
private Context context;
private ArrayList<Order> orders;
public PastOrders() {
}
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
view = inflater.inflate(R.layout.fragment_pastorders, container, false);
context = getActivity();
pastOrdersList = (ListView) view.findViewById(R.id.pastOrdersList);
ParseQuery<ParseObject> query = ParseQuery.getQuery("Order");
query.whereEqualTo("user_id", Vars.currentUser);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if(e != null) {
Log.e("TAG", e.getLocalizedMessage());
} else {
ArrayList<Order> orders = new ArrayList<Order>();
Log.i("TAG", objects.toString());
for (ParseObject object: objects) {
Order temp = new Order();
temp.orderId = object.getObjectId();
temp.date = object.getCreatedAt();
temp.status = object.getString("status");
Log.i("TAG", "orderID: "+ object.getObjectId() + " temp orderID"+ temp.orderId);
orders.add(temp);
Vars.pastOrders.add(object);
}
Log.i("TAG", "after for loop past orders: "+ orders.toString());
PastOrdersAdapter pastOrdersAdapter = new PastOrdersAdapter(getActivity(), R.layout.past_orders_row, orders);
pastOrdersList.setAdapter(pastOrdersAdapter);
}
}
});
return view;
}
#Override
public void onResume() {
super.onResume();
}
}
PastOrdersAdapter.java Custom Adapter
public class PastOrdersAdapter extends ArrayAdapter<Order> {
private Context context;
private ViewHolder holder;
//private ArrayList<Order> orders;
public PastOrdersAdapter(Context context, int resource, List<Order> orders) {
super(context, resource);
// this.orders = orders;
Log.i("TAG", "POA adapter called");
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Log.i("TAG", "getView from POA");
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
if (convertView == null) {
convertView = inflater
.inflate(R.layout.past_orders_row, parent, false);
holder = new ViewHolder();
holder.orderId = (TextView) convertView.findViewById(R.id.orderId);
holder.date = (TextView) convertView.findViewById(R.id.date);
holder.status = (TextView) convertView.findViewById(R.id.status);
holder.details = (ImageView) convertView.findViewById(R.id.details);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
ParseObject order = Vars.pastOrders.get(position);
Log.i("TAG", "order id in adapter: "+ order.getObjectId());
if(order != null) {
holder.orderId.setText(order.getObjectId());
holder.date.setText(getFormattedDate(order.getCreatedAt()));
holder.status.setText(order.getString("status"));
if(order.getString("status").equals("Delivered")) {
holder.status.setTextColor(Color.GREEN);
} else if(order.getString("status").equals("Cancelled")) {
holder.status.setTextColor(Color.RED);
} else {
holder.status.setTextColor(Color.YELLOW);
}
}
return convertView;
}
static class ViewHolder {
TextView orderId;
TextView date;
TextView status;
ImageView details;
}
}
Order.java
public class Order {
public String orderId;
public Date date;
public String status;
}
fragment_pastorders.xml Layout File for Fragment showing ListView
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:id="#+id/pastOrdersList"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
</RelativeLayout>
past_orders_row.xml Layout file for each row of listview
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="150dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="150dp"
android:orientation="vertical"
android:id="#+id/LinearLayout01">
<TextView
android:id="#+id/orderId"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/date"
android:textStyle="italic"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/status"/>
</LinearLayout>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_action_next_item"
android:layout_toRightOf="#id/LinearLayout01"
android:layout_centerVertical="true"
android:id="#+id/details"/>
</RelativeLayout>
I have tried printing getCount() as well and it is non-zero. I have tried everything. Kindly help
Thanks,
Arpit
In the constructor of your custom adapter, your forgot to pass your orders parameter to the parent constructor. So your adapter does not know what to display.
You are passing empty list orders to you adapter. And then in adapter you are using different list: Vars.pastOrders.
So your adapter has empty list.
Replace this:
PastOrdersAdapter pastOrdersAdapter =
new PastOrdersAdapter(getActivity(), R.layout.past_orders_row, orders);
with this:
PastOrdersAdapter pastOrdersAdapter =
new PastOrdersAdapter(getActivity(), R.layout.past_orders_row, Vars.pastOrders);

How to add an icon to a listview in a fragment

I made a listview in a fragment. Now I need to add a simple icon to the listview items. The icon must be the same on every item. This will be a simple arrow (imageview).
Is this possible with the listview I made? And if yes, how do I do it?
So like this format:
My text here --space--space-- >
The code for the fragment:
public class BiblioFragment extends Fragment {
final String[] items = new String[] { "Astma en alcohol", "Astma en huisdieren", "Astma en lichaamsgewicht",
"Astma en ouder worden", "Astmamedicatie", "Bekende mensen met astma", "Longfunctieonderzoek", "Reizen en vakantie",
"Sociaal leven", "Weetjes over astma", "Enzovoort", "Enzovoort", "Enzovoort" };
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_biblio, container, false);
ListView list = (ListView)view.findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Log.v("TAG", "CLICKED row number: " + arg2);
Intent myIntent = new Intent(getActivity(), BiblioDetail.class);
myIntent.putExtra("welkerij", arg2);
startActivity(myIntent);
}
});
return view;
}
}
My XML for that fragment:
<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="#ffffff">
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
</ListView>
</LinearLayout>
In onCreateView
ListView list = (ListView)view.findViewById(R.id.listView1);
CustomAdapter cus = new CustomAdapter(getActivity(),items);
list.setAdapter(cus);
Use a custom adapter
public class CustomAdapter extends BaseAdapter {
String items[];
LayoutInflater mInflater;
public CustomAdapter(Context context, String[] items) {
mInflater = LayoutInflater.from(context);
this.items = items;
}
#Override
public int getCount() {
return items.length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView ==null)
{
convertView = mInflater.inflate(R.layout.list_item,parent,false);
holder = new ViewHolder();
holder.tv = (TextView) convertView.findViewById(R.id.textView1);
holder.iv = (ImageView) convertView.findViewById(R.id.imageView1);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.tv.setText(items[position])
// use holder.iv to set whatever image you want according to the position
return convertView;
}
static class ViewHolder
{
ImageView iv;
TextView tv;
}
}
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="42dp"
android:layout_marginTop="32dp"
android:src="#drawable/ic_launcher" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/imageView1"
android:layout_marginLeft="64dp"
android:layout_marginTop="14dp"
android:layout_toRightOf="#+id/imageView1"
android:text="TextView" />
</RelativeLayout>
Snap
Edit:
If you feel this is over kill you can use a compound textview with image on the left and text on the right.
In the above I have used list_item.xml which is a custom layout. I inflate that layout in getView of custom adapter. I set the text to textview. I have set the default launcher icon to imageview. You can change it though.
I have also used a ViewHolder
http://developer.android.com/training/improving-layouts/smooth-scrolling.html
Also check
How ListView's recycling mechanism works
Create ListAdapter
public class ListAdapter extends ArrayAdapter<Item> {
public ListAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
// TODO Auto-generated constructor stub
}
private List<Item> items;
public ListAdapter(Context context, int resource, List<Item> items) {
super(context, resource, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.itemlistrow, null);
}
Item p = items.get(position);
if (p != null) {
ImageView ICon = ( ImageView) v.findViewById(R.id.description);
}
}
return v;
}
In your Activity
ListView yourListView = (ListView) findViewById(R.id.itemListView);
// get data from the table by the ListAdapter
ListAdapter customAdapter = new ListAdapter(this, R.layout.itemlistrow, List<yourItem>);
yourListView .setAdapter(customAdapter);

Populate list in ListFragment through custom ArrayAdapter - my data doesn't show but are present in the adapter

I am new in android app dev and I am trying to create a ListFragment consisting of a TextView and a ListView. I want to try and populate the ListView with data from a custom class and thus created a custom ArrayAdapter. My app runs but doesn't show anything in the list and I can't figure out why not. I have logged the data and it is present in the holder and the text seems to be set but something is wrong.
row_layout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:padding="6dip" >
<LinearLayout
android:orientation="vertical"
android:layout_width="0dip"
android:layout_weight="1"
android:layout_height="fill_parent">
<TextView
android:id="#+id/TextViewStation"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:gravity="center_vertical"
android:text="My Application" />
<TextView
android:id="#+id/TextViewType"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:singleLine="true"
android:ellipsize="marquee"
android:text="Simple application that shows how to use RelativeLayout" />
</LinearLayout>
</RelativeLayout>
list_layout.xml
<?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="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/android:empty"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="No items to display." />
<ListView
android:id="#+id/android:list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
SimpleArrayAdapter.java
public class SimpleArrayAdapter extends ArrayAdapter<Warning> {
private final Context context;
private final List<Warning> objects;
public SimpleArrayAdapter(Context context, int resource,
List<Warning> objects) {
super(context, resource);
this.context = context;
this.objects = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = new ViewHolder();
if (row == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.row_layout, parent, false);
holder.v1 = (TextView) row.findViewById(R.id.TextViewStation);
holder.v2 = (TextView) row.findViewById(R.id.TextViewType);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
final Warning warning = objects.get(position);
if (warning != null) {
holder.v1.setText(warning.getStation());
holder.v2.setText(warning.getType());
// Log.d("Adapter", "holder.v1.getText(): " + holder.v1.getText());
}
return row;
}
public static class ViewHolder {
TextView v1; // view1
TextView v2; // view2
}
#Override
public int getCount() {
return objects.size();
}
#Override
public Warning getItem(int position) {
// TODO Auto-generated method stub
return objects.get(position);
}
}
List_View.java - the ListFragment
public class List_View extends ListFragment {
List<Warning> items = new ArrayList<Warning>();
Gson gson = new Gson();
private SimpleArrayAdapter adapter;
private ListView mListView;
// #Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ---- Get data!
JsonElement je = new JsonParser().parse(result);
JsonObject jo = je.getAsJsonObject();
JsonArray ja = jo.getAsJsonArray("warnings");
for (int i = 0; i < ja.size(); i++) {
Warning war = new Warning();
war = gson.fromJson(ja.get(i).getAsJsonObject(), Warning.class);
items.add(war);
}
// ----
}
// #Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater
.inflate(R.layout.list_layout, container, false);
// RESTManager manager = new RESTManager();
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.d("Adapter", "items.size(): "+ items.size());
adapter = new SimpleArrayAdapter(getActivity(), R.layout.row_layout,
items);
setListAdapter(adapter);
}
}
In SimpleArrayAdapter, me logging the result from holder.v1.getText() returns correct value but still nothing is showing in the ListView in the app.
Try this :
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
TextView station, type ;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.row_layout, parent, false);
station = (TextView) row.findViewById(R.id.TextViewStation);
type = (TextView) row.findViewById(R.id.TextViewType);
}
Warning warning = objects.get(position);
if (warning != null) {
station.setText(warning.getStation());
type.setText(warning.getType());
// Log.d("Adapter", "holder.v1.getText(): " + holder.v1.getText());
}
return row;
}
I found the problem. Stupidly for some reason I had android:layout_width="0dip" for the textviews........ changed to android:layout_width="fill_parent" and boom, there is my data!

Adding items to data source doesn't appear in ListView

I am adding items to my data source and would like it to appear in my ListView. For some reason nothing is appearing:
Adapter:
private class STCompanyAdapter extends ArrayAdapter<STCompany> {
private ArrayList<STCompany> items;
public STCompanyAdapter(Context context, int textViewResourceId,
ArrayList<STCompany> items) {
super(context, textViewResourceId, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.addstocksrow, null);
}
STCompany q = items.get(position);
if (q != null) {
TextView symbolText = (TextView) v.findViewById(R.id.toptext);
TextView nameText = (TextView) v.findViewById(R.id.bottomtext);
if (nameText != null) {
nameText.setText(q.getSymbol());
}
if (symbolText != null) {
symbolText.setText(q.getName());
}
}
return v;
}
}
Adding items in onCreate:
listView = (ListView) findViewById(R.id.symbolsListView);
this.companiesAdapter = new STCompanyAdapter(this, R.layout.addstocksrow, companies);
listView.setAdapter(this.companiesAdapter);
STCompany myCompany = new STCompany();
myCompany.setName("La La");
myCompany.setSymbol("BP");
companiesAdapter.add(myCompany);
companiesAdapter.notifyDataSetChanged();
Here is my layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android" android:id="#+id/LinearLayout">
<EditText android:id="#+id/addStocksEditText" android:text="Search company or stock" android:layout_width="200dp" android:layout_height="50dp"></EditText><Button android:layout_height="wrap_content" android:text="Search" android:id="#+id/searchButton" android:layout_width="fill_parent"></Button><ListView android:id="#+id/symbolsListView" android:layout_width="fill_parent" android:layout_height="fill_parent"></ListView>
</LinearLayout>
try companies.add(myCompany) instead of companiesAdapter.add(myCompany).
Problem was my layout. listview wasn't appearing. Code is ok.

Categories

Resources