I have created a custom list view adapter and items for the list view is stored at String.xml. When I run the app I only shows a blank activity.
Please help me to fix this issue.
This is my custom adapter java class.
public class UserAdapter extends ArrayAdapter<User> {
public UserAdapter(Context context, ArrayList<User> users, String[] number) {
super(context, 0, users);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
User user = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.listview_singlerow, parent, false);
}
TextView tvName = (TextView) convertView.findViewById(R.id.org_name);
TextView tvNum = (TextView) convertView.findViewById(R.id.cn_num);
// Populate the data into the template view using the data object
tvName.setText(user.company_name);
tvNum.setText(user.contact_num);
return convertView;
}}
List View model class.
public class User {
public String company_name;
public Integer contact_num;
public User(String company_name, Integer contact_num) {
this.company_name = company_name;
this.contact_num = contact_num;
}}
Main Activity class where I attach adapter to the view.
public class activity_one extends Activity {
String[] number;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity1);
number = getResources().getStringArray(R.array.dummy_data);
ArrayList<User> arrayOfUsers = new ArrayList<User>();
UserAdapter adapter = new UserAdapter(this, arrayOfUsers,number);
ListView listView = (ListView) findViewById(R.id.listView2);
listView.setAdapter(adapter);
}}
Since i am not 100% sure on what you want to do, ill show you a piece of my code and you can deduce from that what you need.
My DrawerListAdapter is an custom ListView adapter, and every item on that list consists of 3 objects - a String name, String imageurl, String description.
public class DrawerListAdapter extends ArrayAdapter<String> {
private final static int settingsCount = 4; // can ignore this
private Activity context;
// Next 3 lines: All data required for this adapter
private static ArrayList<String> itemname = null;
private static ArrayList<String> imgid;
private static ArrayList<String> itemDescription;
public DrawerListAdapter(Activity context, ArrayList<String> itemname, ArrayList<String> itemDescription, ArrayList<String> imgid) {
// R.layout.drawer_list_item is a layout that represents ONE item
// (not 100% sure, but i think the super class inflates this view itemname.size() times)
super(context, R.layout.drawer_list_item, itemname);
this.context=context;
// saving the required data
DrawerListAdapter.itemDescription = itemDescription;
DrawerListAdapter.itemname=itemname;
DrawerListAdapter.imgid=imgid;
}
#Override
public View getView(int position,View view,ViewGroup parent) {
LayoutInflater inflater=context.getLayoutInflater();
View rowView=inflater.inflate(R.layout.drawer_list_item, null,true);
// the views that are present in R.layout.drawer_list_item
TextView txtTitle = (TextView) rowView.findViewById(R.id.tvName);
ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
TextView extratxt = (TextView) rowView.findViewById(R.id.tvDescription);
txtTitle.setText(itemname.get(position));
extratxt.setText(itemDescription.get(position));
// setting the image here of the list item here
if (position < settingsCount) {
imageView.setImageResource(Integer.parseInt(imgid.get(position)));
} else {
Glide.with(context).load(imgid.get(position)).into(imageView);
}
return rowView;
};
// need to override the getCount. this function just returns the amount of items in your list
#Override
public int getCount(){
if (itemname != null)
return itemname.size();
return 0;
}
This is initialized by:
private void init() {
mDrawerList = (ListView) findViewById(R.id.left_drawer);
if (adapter == null) {
ArrayList<String> itemname = new ArrayList<String>();
itemname.add("item1");
itemname.add("item2");
itemname.add("item3");
itemname.add("item4");
ArrayList<String> imgid = new ArrayList<String>();
imgid.add(R.drawable.pic1 + "");
imgid.add(R.drawable.pic2 + "");
imgid.add(R.drawable.pic4 + "");
imgid.add(R.drawable.pic3 + "");
ArrayList<String> itemDescription = new ArrayList<String>();
itemDescription.add("desc1");
itemDescription.add("desc2");
itemDescription.add("desc3");
itemDescription.add("desc4");
adapter=new DrawerListAdapter(this, itemname, itemDescription, imgid);
setOnItemClickListener(); // sets onClick for each item on the list
}
mDrawerList.setAdapter(adapter);
}
and the drawer_list_item.xml just in case you are intrested:
<?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="horizontal" >
<ImageView
android:id="#+id/icon"
android:layout_width="60dp"
android:layout_height="60dp"
android:padding="5dp" />
<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/tvName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:padding="2dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#429bd9" />
<TextView
android:id="#+id/tvDescription"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:maxLines="2"
android:textColor="#79e5a4" />
</LinearLayout>
Related
The code is based by tinder tutorial:
public class arrayadapter extends ArrayAdapter<cards>
{
Context context;
public arrayadapter(Context context, int resource_id, List<cards> items)
{
super(context,resource_id,items);
}
public View getview(int position, View convertview, ViewGroup parent)
{
cards card_item = getItem(position);
if (convertview == null)
{
convertview = LayoutInflater.from(getContext()).inflate(R.layout.item,parent,false);
}
TextView user_name =(TextView) convertview.findViewById(R.id.user_name);
ImageView user_image =(ImageView) convertview.findViewById(R.id.image);
user_name.setText(card_item.getUser_name());
user_image.setImageResource(R.mipmap.ic_launcher); // change in the future with user pic
return convertview;
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="40sp"
android:paddingRight="40sp"
android:paddingTop="20sp"
android:paddingBottom="20sp"
android:outlineProvider="bounds"
android:clipToPadding="false"
>
<androidx.cardview.widget.CardView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
app:cardCornerRadius="6dp"
android:elevation="2dp"
android:id="#+id/card_view"
>
<FrameLayout
android:layout_gravity="center"
android:layout_width="250dp"
android:layout_height="170dp"
>
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/image">
</ImageView>
<TextView
android:id="#+id/user_name"
android:textSize="40sp"
android:textColor="#android:color/black"
android:gravity="center"
tools:text="hello"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
This are the swipe, arrayadapter classes and item xml. The data of the users are not important right now.
public class swipe_cards extends AppCompatActivity {
private cards cards_data[] ;
private arrayadapter arrayadapter;
private int i;
ListView listView;
List<cards>rowitems;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_swipe_cards);
Bundle extras = getIntent().getExtras();
rowitems = new ArrayList<cards>();
//arrayadapter = new arrayadapter (this,R.layout.item,rowitems);
//context,YourCustomLayoutID,TextViewIDinYourLayout,ListData
arrayadapter = new arrayadapter(this,R.layout.item,rowitems);
// ArrayAdapter arrayAdapter = new ArrayAdapter(MainActivity.this,
// R.layout.layout_item_autocomplete, R.id.tvCustom, getResources().getStringArray(R.array.sweets));
SwipeFlingAdapterView flingContainer =(SwipeFlingAdapterView)findViewById(R.id.frame);
flingContainer.setAdapter(arrayadapter);
flingContainer.setFlingListener(new SwipeFlingAdapterView.onFlingListener() {
#Override
public void removeFirstObjectInAdapter() {
// this is the simplest way to delete an object from the Adapter (/AdapterView)
Log.d("LIST", "removed object!");
rowitems.remove(0);
arrayadapter.notifyDataSetChanged();
}
#Override
public void onLeftCardExit(Object dataObject) {
//Do something on the left!
//You also have access to the original object.
//If you want to use it just cast it (String) dataObject
Toast.makeText(swipe_cards.this, "Left!",Toast.LENGTH_SHORT).show();
}
#Override
public void onRightCardExit(Object dataObject) {
Toast.makeText(swipe_cards.this, "Right!",Toast.LENGTH_SHORT).show();
}
#Override
public void onAdapterAboutToEmpty(int itemsInAdapter) {
// Ask for more data here
//rowitems.add("XML ".concat(String.valueOf(i)));
arrayadapter.notifyDataSetChanged();
Log.d("LIST", "notified");
i++;
}
#Override
public void onScroll(float scrollProgressPercent) {
}
});
// Optionally add an OnItemClickListener
flingContainer.setOnItemClickListener(new SwipeFlingAdapterView.OnItemClickListener() {
#Override
public void onItemClicked(int itemPosition, Object dataObject) {
Toast.makeText(swipe_cards.this, "Clicked!",Toast.LENGTH_SHORT).show();
}
});
if (extras != null)
{
ArrayList<String> users= extras.getStringArrayList("potential_users");
for (int counter = 0; counter < users.size(); counter++) {
String user = users.get(counter);
//String[] user_details= user.split(":");
String[] user_details = user.split(",");
String [] name_parmetrs= user_details[0].split(":");
String user_name= name_parmetrs[1];
cards card = new cards("222",user_name);
rowitems.add(card);
arrayadapter.notifyDataSetChanged();
}
}
}
You are creating an array adapter with the contructor where u are just giving 3 parameters- context, layout Id and the row-Items.
So for your constructor with only 3 parameters R.layout.item must be the id of a XML layout file containing only a TextView(the TextView can't be wrapped by another layout, like a LinearLayout, RelativeLayout etc!), something like this:
But in your case, you are using a complex layout So in that case you need to pass both layout id and Textview id in the constructor.
In case u need you don't have textViewId you can pass textViewId as 0.
like this
public arrayadapter(Context context, int resource_id, List<cards> items)
{
super(context,resource_id,0,items);
}
If u have a textview ResourceId you can pass the resourceid in place of 0
public arrayadapter(Context context, int resource_id,int textViewId, List<cards> items)
{
super(context,resource_id,textViewId,items);
}
I want to add Text and Images to a TextView with a ArrayApapter.
If this ist the definition of the ArrayAdapter
new ArrayAdapter<View>(getContext(),R.id.element_manual_list, viewsOfPage);
I could use for element_manual_list a TextView or a ImageView but I want both. How can I implement this? Or is there any more easy way to write a userManual Text with images into a Scrollable View?
Something that is HTML styleable perhaps?
You need to create your own adapter class:
public class MyAdapter extends ArrayAdapter<User> {
public MyAdapter(Context context, ArrayList<User> users) {
super(context, 0, users);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
User user = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_user, parent, false);
}
// Lookup view for data population
TextView tvName = (TextView) convertView.findViewById(R.id.tvName);
ImageView ivPhoto = (ImageView) convertView.findViewById(R.id.ivPhoto);
// Populate the data into the template view using the data object
tvName.setText(user.name);
ivPhoto.setImageResource(user.photo);
// Return the completed view to render on screen
return convertView;
}
}
Then XML for your row:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="#+id/ivPhoto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#android:drawable/sym_def_app_icon" />
<TextView
android:id="#+id/tvName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name" />
Then your custom for example User class:
public class User {
public String name;
public int photo;
public User(String name, int photo) {
this.name = name;
this.photo = photo;
}
}
In your main clas put this:
// Construct the data source
ArrayList<User> arrayOfUsers = new ArrayList<User>();
// Create the adapter to convert the array to views
MyAdapter adapter = new MyAdapter(this, arrayOfUsers);
// Attach the adapter to a ListView
ListView listView = (ListView) findViewById(R.id.lvItems);
listView.setAdapter(adapter);
// Add item to adapter
User newUser = new User("Nathan", R.drawable.logo);
adapter.add(newUser);
I need help to make listview adapter. Below is code please make the adapter both value name with roomid.
JSONArray rooms = jsonObject.getJSONArray("rooms");
for (int i = 0; i < rooms.length(); i++) {
JSONObject room = rooms.getJSONObject(i);
String name = room.optString("room");
String roomid = room.optString("roomid");
final RoomModel sched = new RoomModel();
sched.setName(name);
sched.setroomId(roomid);
CustomListViewValuesArr.add(sched);}
listView = (ListView) findViewById(R.id.ChatlistView);
RoomModel.java
public class RoomModel {
private String name, id, roomid;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getroomId() {
return roomid;
}
public void setroomId(String roomid) {
this.roomid = roomid;
}
}
try the following Adapter......
public class MyAdapter extends BaseAdapter {
Context con;
ArrayList<your type> mlist;
RoomModel sched;
public MyAdapter(Context con,ArrayList<your type> mlist )
{
this.con=con;
this.mlist=mlist;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mlist.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return mlist[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
sched=mlist.get(position);
LayoutInflater inflater=(LayoutInflater)con.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView=inflater.inflate(R.layout.your_layout,parent,false);
TextView tv1=(TextView)convertView.findViewById(R.id.your_textview);
tv1.setText(sched.getId());
TextView tv2=(TextView)convertView.findViewById(R.id.your_textview);
tv2.setText(sched.getName());
TextView tv3=(TextView)convertView.findViewById(R.id.your_textview);
tv3.setText(sched.getroomId());
return convertView;
}
}
and change the following code.
JSONArray rooms = jsonObject.getJSONArray("rooms");
for (int i = 0; i < rooms.length(); i++) {
JSONObject room = rooms.getJSONObject(i);
String name = room.optString("room");
String roomid = room.optString("roomid");
final RoomModel sched = new RoomModel();
sched.setName(name);
sched.setroomId(roomid);
CustomListViewValuesArr.add(sched);}
listView = (ListView) findViewById(R.id.ChatlistView);
MyAdapter adapter=new MyAdapter(this,CustomListViewValuesArr);
listView.setAdapter(adapter);
OK as requested by Sandeep, I will give you simple hint but I can't give you full codes that you can directly copy and paste. Just follow instructions
Create an XML file for single item of the list which may have certain elements as you need, for example It's single_item.xml which has 3 TextView
<?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">
<TextView
android:id="#+id/tvId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Sample Id"
android:textColor="#0414f4"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="10sp" />
<TextView
android:id="#+id/tvTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
android:text="Sample Title"
android:textColor="#000"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="20dp"
android:textStyle="bold" />
<TextView
android:id="#+id/tvBody"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Sample body"
android:textSize="16sp"/>
</LinearLayout>
and after getting the reference of listView from main layout set the adapter like this, And here modelList is an ArrayList.
mAdapter = new CustomAdapter(MainActivity.this, R.layout.single_item, modelList);
mAdapter.notifyDataSetChanged();
mListView.setAdapter(mAdapter);
Then the class CustomAdapter looks like this
public class CustomAdapter extends ArrayAdapter<Model> {
ArrayList<Model> modelList;
Context context;
public CustomAdapter(Context context, int resource, ArrayList<Model> objects) {
super(context, resource, objects);
this.modelList = objects;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.single_item,parent,false);
}
// Lookup view for data population
TextView tvId = (TextView) convertView.findViewById(R.id.tvId);
TextView tvTitle = (TextView) convertView.findViewById(R.id.tvTitle);
TextView tvBody = (TextView) convertView.findViewById(R.id.tvBody);
// Populate the data into the template view using the data object
tvId.setText(String.valueOf(model.getId()));
tvTitle.setText(model.getroomId());
tvBody.setText(model.getName());
// Return the completed view to render on screen
return convertView;
}
}
NOTE : I have commented and made it simple as possible to help you. Hope this may help. You can comment if any problem raised.
Here's the code with the problem:
//declarations:
private ArrayAdapter<String> listAdapter;
private ArrayAdapter<String> listAdapter2;
String [] nomi=null;
String[] famiglia=null;
private ListView mainListView;
// other code bla bla bla...
mainListView = (ListView) findViewById(R.id.listView);
// other code bla bla bla...
nomi = new String[res.size()];
for (int i = 0; i < res.size(); i++) {
nomi[i] = res.get(i).getNomignolo();
}
famiglia= new String[res.size()];
for(int i=0; i<res.size();i++){
famiglia[i] = res.get(i).getFamiglia();
}
ArrayList<String> listaNomi = new ArrayList<String>();
listaNomi.addAll(Arrays.asList(nomi));
ArrayList<String> listaFamiglie = new ArrayList<String>();
listaFamiglie.addAll(Arrays.asList(famiglia));
listAdapter = new ArrayAdapter<String>(HomeActivity.this, R.layout.row, R.id.button3, listaNomi);
listAdapter2 = new ArrayAdapter<String>(HomeActivity.this, R.layout.row, R.id.button6, listaFamiglie);
mainListView.setAdapter(listAdapter);
mainListView.setAdapter(listAdapter2);
It works, but only in part, because when i start the app i can find only the result of the second setAdapter method. How can i achieve also the result of all the setAdapter methods? Thanks.
try to add objects of second list in first on
nomi = new String[res.size()];
for (int i = 0; i < res.size(); i++) {
nomi[i] = res.get(i).getNomignolo() + " " +res.get(i).getFamiglia();
}
//list of object with name and family
create adapter
listAdapter = new ArrayAdapter<String>(HomeActivity.this, R.layout.row, R.id.button3, listaNomi);
mainListView.setAdapter(listAdapter);
you cannot set multiple adapter for one listview.
How to create custom array adapter:
public class CustomAdapter extends ArrayAdapter<Person>{
private final Activity context;
private ArrayList<Person> Items;
public CustomAdapter (Activity context, int layout,ArrayList<Person> persons) {
super(context, layout, carriers);
// TODO Auto-generated constructor stub
this.context = context;
this.Items = persons;
}
static class ViewHolder {
public Button name;
public Button family;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
// Recycle existing view if passed as parameter
// This will save memory and time on Android
// This only works if the base layout for all classes are the same
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = context.getLayoutInflater();
rowView = inflater.inflate(R.layout.item, null, true);
holder = new ViewHolder();
holder.name= (TextView) rowView.findViewById(R.id.name);
holder.family= (TextView) rowView.findViewById(R.id.family);
rowView.setTag(holder);
} else {
holder = (ViewHolder) rowView.getTag();
}
holder.name.setText(Items.get(position).getName());
holder.family.setText(Items.get(position).getFamily());
return rowView;
}
}
and create PErson Object:
public class PErson{ public String name; public String family;
public Person();
public String getName(){ return name;}
public String getFamily(){return family;}
}
and this is item xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="wkjdhk"
android:textColor="#color/green"
android:textSize="12sp" />
<Button
android:id="#+id/family"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="wkjdhk"
android:textColor="#color/green"
android:textSize="12sp" />
</RelativeLayout>
this is how to call from activity:
adapter = new MyCustomAdapter(CarrierSummaryActivity.this,nomi,R.layout.item);
mainListView.setAdapter(adapter);
Can you please do like this way ?
First List:
ArrayList<String> a = new ArrayList<String>();
a.add("a");
a.add("b");
a.add("c");
Second List:
ArrayList<String> b = new ArrayList<String>();
b.add("d");
b.add("e");
b.add("f");
Add a to b:
b.addAll(a);
Merge both list:
ArrayList<String> union = new ArrayList<String>(a);
union.addAll(b);
Set Adapter on ListView:
listAdapter = new ArrayAdapter<String>(HomeActivity.this, R.layout.row, R.id.button3, union);
mainListView.setAdapter(listAdapter);
Hope this will help you.
This is not possible, whenever you are setting second adapter to listview, your first adapters data get replaced with second.
LISTVIEW CAN DISPLAY SINGLE ADAPTER DATA AT SINGLE TIME.
If you want to display data from multiple sources to ListView then first merge all all data and then use single adapter. Do something like below
dataList1 (From source A)
datalist2 (From source B)
datalist3 = dataList1 + dataList2;
setDapter(dataList3)
You should implement your custom adapter so it can draw the list just like you want.
class MyAdapter extends BaseAdapter
{
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//Here you can return a View with any data in any way
}
}
Hope this helps.
I'm using a paginator with a few Fragments.
I want to show a message when there are no entries in the list (Fragment).
I tried to use Textview with android:id="#id/android:empty but it doesn't work.
Custom list layout code:
<?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="wrap_content"
android:padding="#dimen/padding_medium" >
<TextView
android:id="#+id/label_value"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="#dimen/padding_medium"
android:text="#string/label_value"
android:textColor="#android:color/white"
android:textSize="18sp" />
<TextView
android:id="#+id/label_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="#dimen/padding_medium"
android:text="#string/title_time"
android:textColor="#android:color/white"
android:textSize="16sp" />
</RelativeLayout>
List adapter class:
public class JournalAdapter extends ArrayAdapter<String> {
private final Context context;
private final List<String> values;
private final List<String> dates;
public JournalAdapter(Context context, List<String> values,
List<String> dates) {
super(context, R.layout.layout_journal_list, values);
this.context = context;
this.values = values;
this.dates = dates;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.layout_journal_list, parent, false);
TextView value = (TextView) rowView.findViewById(R.id.label_glucose);
TextView date = (TextView) rowView.findViewById(R.id.label_date);
value.setText(values.get(position));
date.setText(dates.get(position));
return rowView;
}
}
List parsing method:
private void initListView() {
values = dataSource.getAllValues();
List<String> values = new ArrayList<String>();
List<String> dates = new ArrayList<String>();
for (Value value : values) {
values.add(Double.toString(value.getValue()));
dates.add(secondsToDate(value.getDate()));
}
setListAdapter(new JournalAdapter(context, values, dates));
listView = getListView();
listView.setEmptyView(noItems("NO ITEMS"));
listView.setOnItemClickListener(this);
}
noItems method:
private TextView noItems(String text) {
TextView emptyView = new TextView(context);
emptyView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
emptyView.setText(text);
emptyView.setTextColor(Color.WHITE);
emptyView.setTextSize(20);
emptyView.setVisibility(View.GONE);
emptyView.setGravity(Gravity.CENTER_VERTICAL
| Gravity.CENTER_HORIZONTAL);
return emptyView;
}
This worked for me (got the solution from this question asked by William Remacle). What you might have missed is adding the created TextView to the ListView layout parent (second line of code from the bottom of the noItems method below):
In my ListFragment I used the following method to get a view for the empty view:
private TextView noItems(String text) {
TextView emptyView = new TextView(getActivity());
//Make sure you import android.widget.LinearLayout.LayoutParams;
emptyView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
//Instead of passing resource id here I passed resolved color
//That is, getResources().getColor((R.color.gray_dark))
emptyView.setTextColor(getResources().getColor(R.color.gray_dark));
emptyView.setText(text);
emptyView.setTextSize(12);
emptyView.setVisibility(View.GONE);
emptyView.setGravity(Gravity.CENTER_VERTICAL
| Gravity.CENTER_HORIZONTAL);
//Add the view to the list view. This might be what you are missing
((ViewGroup) getListView().getParent()).addView(emptyView);
return emptyView;
}
Then in the onStart() method of the the ListFragment set the the empty view:
#Override
public void onStart() {
super.onStart();
getListView().setEmptyView(
noItems(getResources().getString(R.string.widget_empty)));
}
android:id="#android:id/empty"
and not
android:id="#id/android:empty"