Actually I have created a custom ListView. I want to add items to this custom ListView dynamically. But in my case, the first item is inserted without any problem but when I try to insert the second item it gives an error. If anyone knows how to solve this, please suggest it to me.
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="#+id/relativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<ListView
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:id="#+id/historyFrmLstView2"
android:layout_alignParentLeft="true"
android:layout_below="#+id/historyFrmLstView1"
android:layout_marginTop="20dip"
android:layout_marginBottom="10dip">
</ListView>
</RelativeLayout>
ListView.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="#+id/relativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="5dip"
android:background="#00000000">
<TextView
android:textSize="18dp"
android:layout_height="wrap_content"
android:textColor="#000000"
android:background="#drawable/history_scroll_title_label_bg"
android:layout_width="wrap_content"
android:id="#+id/txtHistoryDisplay"
android:layout_below="#+id/txtViewHeading"
android:layout_marginTop="0dip"
android:layout_marginLeft="2dip">
</TextView>
</RelativeLayout>
main.java
public void displayHistory()
{
String strDisplay[] = {" "};
historyFrmLstView2 = (ListView) findViewById(R.id.historyFrmLstView2);
int iHistCount = CycleManager.getSingletonObject().getHistoryCount();
int i;
SimpleDateFormat sdFormatter = new SimpleDateFormat("dd-MMMM-yyyy");
for (i=0; i<iHistCount; i++)
{
strDisplay[i] = "";
Date dtHist = CycleManager.getSingletonObject().getHistoryDate(iHistCount);
strDisplay[i]=sdFormatter.format(dtHist.getTime());
aHistFrmAdpter2 = new HistoryFrmCustomAdapter2(this,strDisplay);
historyFrmLstView2.setAdapter(aHistFrmAdpter2);
}
}
custom Adapter.java
public class HistoryFrmCustomAdapter2 extends BaseAdapter
{
public String heading1[];
public Activity context;
public LayoutInflater inflater;
public HistoryFrmCustomAdapter2(Activity context,String[] heading1)
{
super();
this.context = context;
this.heading1=heading1;
this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount()
{
return heading1.length;
}
public Object getItem(int position)
{
return null;
}
public long getItemId(int position)
{
return 0;
}
public static class ViewHolder
{
TextView txtHistoryDisplay;
}
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder;
if(convertView==null)
{
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.histryfrm_listview2, null);
holder.txtHistoryDisplay =(TextView) convertView.findViewById(R.id.txtHistoryDisplay);
convertView.setTag(holder);
}
else
holder=(ViewHolder)convertView.getTag();
holder.txtHistoryDisplay.setText(heading1[position]);
return convertView;
}
}
Hi i think that may be used below code..
public void displayHistory()
{
String strDisplay[] = {" "};
historyFrmLstView2 = (ListView) findViewById(R.id.historyFrmLstView2);
int iHistCount = CycleManager.getSingletonObject().getHistoryCount();
int i;
SimpleDateFormat sdFormatter = new SimpleDateFormat("dd-MMMM-yyyy");
for (i=0; i<iHistCount; i++)
{
strDisplay[i] = "";
Date dtHist = CycleManager.getSingletonObject().getHistoryDate(iHistCount);
strDisplay[i]=sdFormatter.format(dtHist.getTime());
}
aHistFrmAdpter2 = new HistoryFrmCustomAdapter2(this,strDisplay);
historyFrmLstView2.setAdapter(aHistFrmAdpter2);
}
there will be only one element in your string array strDisplay[iHistCount]. since you r putting value at the last position each time. replace iHistCount with i.
Related
I'm new in android..
I would like to create the different views in Listview using Custom Adapter.
Please suggest me how I can do this.
In first row there will be a single Item and in second row there will be two item and so on..
Please Check the attached screen..
Thanks in advance
Define a custom layout of how you want the list row like this
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="#dimen/headerHeightCustRow"
android:background="#FFFFFF"
tools:ignore="HardcodedText" >
<TextView
android:id="#+id/txtName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dip"
android:layout_marginLeft="#dimen/viewSpace1"
android:text="Varun Mad"
android:textSize="#dimen/logout_textSize"
android:textStyle="bold"
android:textColor="#color/orange_normal" />
<TextView
android:id="#+id/txtCustId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginLeft="#dimen/viewSpace3"
android:layout_marginTop="#dimen/viewSpace3"
android:layout_marginRight="#dimen/viewSpace3"
android:text="10549"
android:layout_centerVertical="true"
android:textColor="#color/orange_normal"
android:textSize="15sp" />
<TextView
android:id="#+id/txtPhone"
android:layout_below="#id/txtName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/viewSpace1"
android:text="(886)677-8855"
android:textColor="#color/orange_normal"
android:textSize="#dimen/vsText" />
<TextView
android:id="#+id/txtEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/viewSpace1"
android:text="ggg#gmail.com"
android:textSize="#dimen/vsText"
android:layout_below="#id/txtPhone"
android:textColor="#color/orange_normal" />
<View
android:layout_width="fill_parent"
android:layout_height="0.5dip"
android:layout_alignParentBottom="true"
android:background="#color/greyDark" />
here is the adapter class
public class SearchCustomerAdapter extends BaseAdapter {
Context ctx;
LayoutInflater lInflater;
ArrayList<SearchCustomerItem> objects;
public SearchCustomerAdapter(Context context, ArrayList<SearchCustomerItem> products) {
ctx = context;
objects = products;
lInflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return objects.size();
}
#Override
public Object getItem(int position) {
return objects.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = lInflater.inflate(R.layout.search_cust_row, parent, false);
}
SearchCustomerItem p = getProduct(position);
((TextView) view.findViewById(R.id.txtName)).setText(p.customerName);
if (p.customerEmail.compareTo("anyType{}") == 0) {
((TextView) view.findViewById(R.id.txtEmail)).setText("");
} else {
((TextView) view.findViewById(R.id.txtEmail)).setText(p.customerEmail);
}
((TextView) view.findViewById(R.id.txtPhone)).setText(p.customerPhone);
((TextView) view.findViewById(R.id.txtCustId)).setText(p.customerId);
return view;
}
SearchCustomerItem getProduct(int position) {
return ((SearchCustomerItem) getItem(position));
}
#SuppressWarnings("unused")
ArrayList<SearchCustomerItem> getBox() {
ArrayList<SearchCustomerItem> box = new ArrayList<SearchCustomerItem>();
for (SearchCustomerItem p : objects) {
// if (p.box)
// box.add(p);
}
return box;
}
}
and the ITem Class
public class SearchCustomerItem {
public String customerName;
public String customerPhone;
public String customerEmail;
public String customerId;
public SearchCustomerItem(String _cName, String _cPhone, String _cEmail, String _cCustId) {
customerName = _cName;
customerPhone = _cPhone;
customerEmail = _cEmail;
customerId = _cCustId;
}
}
you can initialize the adapter,
add the items in Arraylist and show in the list by using
SearchCustomerAdapter boxAdapter;
ArrayList<SearchCustomerItem> products = new ArrayList<SearchCustomerItem>();
to add items in arraylist
products.add(new SearchCustomerItem("CustomerName","PhoneNo","Cust_EmailId","Cust_Id"));
//Add as many items you want
than
boxAdapter = new SearchCustomerAdapter(SearchActivity.this, products);
list.setAdapter(boxAdapter);
This link might help you. link
You should do it step by step.
Extend Base Adapter class by you Custom Adapter class
Override getView and other related methods
set the adapter to list view adapter.
I have a list view which displays only one record always, I've traced my program and find that there are 3 records in my arrayList which I'm passing to the listView adapter. After tracing into getView of list view I find that It executes more that 3 times with position of 0!
I have no idea what's the problem, please help me if you can.
activity_news.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/background"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".News" >
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ListView
android:id="#+id/lvNews"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp" />
</ScrollView>
</RelativeLayout>
this is row template for listView: news_row.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="wrap_content"
android:background="#drawable/message_row_style"
android:layout_gravity="right"
android:gravity="right"
android:orientation="vertical" >
<LinearLayout
android:layout_marginTop="50dp"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:orientation="horizontal">
<TextView
android:id="#+id/txtTitle"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#color/dark_purple"
android:layout_gravity="right"
android:gravity="right"
android:background="#color/red"
/>
<TextView
android:id="#+id/txtDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/dark_purple"
android:layout_gravity="right"
android:background="#color/blue"
android:gravity="right" />
</LinearLayout>
</LinearLayout>
newsAdapter.java:
public class NewsAdapter extends BaseAdapter{
private Context context;
private ArrayList<News> list;
private Activity activity;
public NewsAdapter(Context c,Activity activity,ArrayList<News> l) {
Log.d("Ehsan", "News Adapter Constructor");
context = c;
list = l;
this.activity = activity;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int i) {
return list.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.news_row, parent,false);
TextView title = (TextView) row.findViewById(R.id.txtTitle);
TextView date = (TextView) row.findViewById(R.id.txtDate);
News temp = list.get(position);
title.setText(temp.getTitle());
date.setText(temp.getsDate());
title.setTag(temp.getid());
title.setOnClickListener(onClickListener);
return row;
}
private OnClickListener onClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
String date = null,title = null,description = null;
int id=1;
Intent i = null;
News news = new News(activity);
news.load(id);
date = news.getsDate()+" - ";
title = news.getTitle();
description = news.getDescription();
i = new Intent(activity,ShowInfo.class);
i.putExtra("date", date);
i.putExtra("title", title);
i.putExtra("description", description);
activity.startActivity(i);
activity.finish();
}
};
}
Do following changes in your getView
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
ViewHolder holder=new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.news_row, parent,false);
TextView title = (TextView) row.findViewById(R.id.txtTitle);
TextView date = (TextView) row.findViewById(R.id.txtDate);
convertView.setTag(holder);
}
ViewHolder hold=(ViewHolder)convertView.getTag();
News temp = list.get(position);
hold.title.setText(temp.getTitle());
hold.date.setText(temp.getsDate());
title.setOnClickListener(onClickListener);
return row;
}
add this class in your adapter file
static class ViewHolder
{
TextView title;
TextView date;
}
You should call super in the constructor of your adapter change your adapter as following:
public class NewsAdapter extends ArrayAdapter<News>{
private Context context;
private ArrayList<News> list;
private Activity activity;
public NewsAdapter(Context c,Activity activity,ArrayList<News> l) {
super(c,-1,l);//<-- **pass your item list to super**
Log.d("Ehsan", "News Adapter Constructor");
context = c;
list = l;
this.activity = activity;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int i) {
return list.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.news_row, parent,false);
TextView title = (TextView) row.findViewById(R.id.txtTitle);
TextView date = (TextView) row.findViewById(R.id.txtDate);
News temp = list.get(position);
title.setText(temp.getTitle());
date.setText(temp.getsDate());
title.setTag(temp.getid());
title.setOnClickListener(onClickListener);
return row;
}
private OnClickListener onClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
String date = null,title = null,description = null;
int id=1;
Intent i = null;
News news = new News(activity);
news.load(id);
date = news.getsDate()+" - ";
title = news.getTitle();
description = news.getDescription();
i = new Intent(activity,ShowInfo.class);
i.putExtra("date", date);
i.putExtra("title", title);
i.putExtra("description", description);
activity.startActivity(i);
activity.finish();
}
};
}
I am new to Android development. I have created a custom object in java. How do I render it to screen? I look around and is really confused about the whole Android rendering process.
My object is not a list. It is a tree. I also read about Adapter, Layout and View, but don't understand it. Here is my code:
public class GeoArea {
public String id;
public String name;
public String searchLocation;
public static String searchTerm;
public List<GeoArea> subGeoAreas;
public GeoArea parentGeoArea;
public GeoArea(String id) {
this.id = id;
name = id;
searchLocation = "";
subGeoAreas = new LinkedList<GeoArea>();
}
#Override
public String toString() {
return name;
}
public int size(){
int result = 0;
for(GeoArea curGeoArea:subGeoAreas){
result += curGeoArea.size();
}
return result + 1;
}
}
And here is the Layout I have:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".Activity_GeoAreas" >
<TextView
android:id="#+id/textMain"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Choose Suburb"
android:textAppearance="?android:attr/textAppearanceLarge" />
<LinearLayout
android:id=""#+id/geoAreasLayout""
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textMain"
android:orientation="vertical" >
</LinearLayout>
</RelativeLayout>
So the idea is to render the main GeoArea into geoAreasLayout, and since it is a tree, each subGeoArea will get rendered in turn.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_geo_areas);
GeoArea.searchTerm = "Bar & Grill";
GeoArea torontoArea = new GeoArea("cityOfToronto");
torontoArea.name = "City of Toronto";
torontoArea.searchLocation = "Toronto, ON";
GeoArea testGeoArea = null;
testGeoArea = new GeoArea("DownTownCore");
testGeoArea.name = "Down Town Core";
testGeoArea.searchLocation = "Downtown Core, Toronto, ON";
testGeoArea.parentGeoArea = torontoArea;
torontoArea.subGeoAreas.add(testGeoArea);
testGeoArea = new GeoArea("AlexandraPark");
testGeoArea.name = "Alexandra Park";
testGeoArea.searchLocation = "Alexandra Park, Toronto, ON";
testGeoArea.parentGeoArea = torontoArea;
torontoArea.subGeoAreas.add(testGeoArea);
// what's next?
}
}
I try to write an Adapter, but I am not even sure what it's for or how to use it:
public class GeoAreaAdapter extends BaseAdapter implements Filterable{
private Context _context;
private int resource;
private GeoArea _myGeoArea;
public GeoAreaAdapter(Context context, int resource, GeoArea myGeoArea) {
_context = context;
_myGeoArea = myGeoArea;
}
public int getCount() {
return _myGeoArea.size();
}
public Object getItem(int position) {
return _myGeoArea;
}
public long getItemId(int position) {
return _myGeoArea.id.hashCode();
}
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout GeoAreaView;
if (convertView == null) {
GeoAreaView = new LinearLayout(_context);
LayoutInflater li = LayoutInflater.from(_context);
convertView = li.inflate(R.layout.layout_geo_area, null);
}
else {
GeoAreaView = (LinearLayout) convertView;
}
TextView name = (TextView) GeoAreaView.findViewById(R.id.txtGeoAreaName);
name.setText(_myGeoArea.name);
return convertView;
}
static class ViewHolder {
TextView name;
RelativeLayout childContainer;
}
#Override
public Filter getFilter() {
return null;
}
}
Firstly your class must be extends from one of Views or ViewGroups classes to render and use it in LinearLayout.like this:
public class GeoArea extends View{
According to this issue after that you can use it in xml Layout file like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<com.example.YourClassName
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/mapview"
></com.example.YourClassName>
</LinearLayout>
as you see you must use package name to render your new object in xml layout file.
I'm using listview to show the messages from the database..when i add a message it
takes all the string and showing on the listview..here is my xml file and java..
I need to get the message in a singline per rows with '...'. I researched for this question and i found,type
android:singleLine="true" in textview,but i don't know what they mean 'in textview'.becauz i'm using listview.please help.
<?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="#drawable/wave" >
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_below="#+id/SearchMessageExit"
android:focusableInTouchMode="true"
>
</ListView>
</LinearLayout>
message.java
public void detailsOfMessage(){
try{
Database_message info = new Database_message(this);
String data = info.getData();
info.close();
if(data.equals(""))
{
Toast.makeText(getApplicationContext(), "Empty Message", Toast.LENGTH_LONG).show();
}
StringTokenizer token = new StringTokenizer(data,"\t");
int rows = token.countTokens();
classes = new String[rows];
int i=0;
while (token.hasMoreTokens())
{
classes[i]=token.nextToken();
i++;
}
listView = (ListView) findViewById(R.id.list);
listView.setOnItemClickListener(this);
listView.setOnLongClickListener(this);
inAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,0);
listView.setAdapter(inAdapter);
for (int r = 0; r < classes.length; r++) {
inAdapter.add(classes[r]);
}
}catch(Exception e){
Toast.makeText(getApplicationContext(), "Empty Message", Toast.LENGTH_LONG).show();
}
}
you are using default layout android.R.layout.simple_list_item_1 for listview item. instead create one layout with textview with single line enable. and pass it to listview. and use custom array adapter for listview.
Do like this:
create list itemview XML
listview_item_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp">
<TextView android:id="#+id/txtTitle"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:textStyle="bold"
android:textSize="22dp"
android:textColor="#000000"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp" />
</LinearLayout>
One class like
Weather.java
public class Weather {
public String title;
public Weather(){
super();
}
public Weather(String title) {
super();
this.title = title;
}
}
and then create array adapter class
public class WeatherAdapter extends ArrayAdapter<Weather>{
Context context;
int layoutResourceId;
Weather data[] = null;
public WeatherAdapter(Context context, int layoutResourceId, Weather[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
WeatherHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new WeatherHolder();
holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle);
row.setTag(holder);
}
else
{
holder = (WeatherHolder)row.getTag();
}
Weather weather = data[position];
holder.txtTitle.setText(weather.title);
return row;
}
static class WeatherHolder
{
TextView txtTitle;
}
}
And use like this in your activity:
Weather weather_data[] = new Weather[]
{
new Weather("Cloudy"),
new Weather("Showers"),
new Weather("Snow"),
new Weather("Storm"),
new Weather("Sunny")
};
WeatherAdapter adapter = new WeatherAdapter(this,
R.layout.listview_item_row, weather_data);
listView1.setAdapter(adapter);
Hope it Helps!!!
You need to implement a custom adapter for your ListView.
Along with that you should also implement, a custom_row.xml file for each row of your List View.
For Example:
1. Custom Adapter:
public class CustomAdapterListView extends BaseAdapter
{
private Activity activity;
private static LayoutInflater inflater=null;
private YOUR_DATA_TYPE data;
public CategoryDetailsCustomGridviewAdapter(Activity a, ArrayList<YOUR_DATA_TYPE> d)
{
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount()
{
// TODO Auto-generated method stub
return data.size();
}
#Override
public Object getItem(int position)
{
// TODO Auto-generated method stub
return 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
View vi=convertView;
if(convertView==null)
{
vi = inflater.inflate(R.layout.YOUR_LISTVIEW_ROW_XML_FILE, null);
}
//Fetching the Data from ArrayList for each row.
TextView custom_row_tv = vi.findViewById(R.id.YOUR_TEXT_VIEW_ID)
YOUR_DATA_TYPE dataToBePopulated = new YOUR_DATA_TYPE;
custom_row_tv.setText(YOUR_DATA_TYPE.ToString());
dataToBePopulated = data.get(position);
return vi;
}
}
2. YOUR_LISTVIEW_ROW_XML_FILE.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" >
<TextView
android:id="#+id/YOUR_TEXT_VIEW_ID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true" >
</TextView>
</RelativeLayout>
3. Setting up Your Custom Adapter:
Public Class YourClass extends Activity
{
onCreate(....)
{
setContentView(R.Layout.YOUR_LAYOUT_FILE);
ArrayList<YOUR_DATA_TYPE> data = new ArrayList<YOUR_DATA_TYPE>();
data.add(...) //Fetch your Data from Data source into this ArrayList.
ListView yourListView = (ListView)findViewById(R,id.YOUR_LISTVIEW_ID);
CustomAdapterListView adapter = new CustomAdapterListView (YourClass.this, data);
yourListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
//YOUR OTHER FUNCTIONALITY......
}
//YOUR OTHER METHODS.....
....
....
}
This way you can simply implement a custom ListView with the Attribute of Single line attached to your TextView embedded within your ListView.
I hope this solves your problem.
Hi this is the code I'm looking at:
https://github.com/findup/Android_Sample_TodoApp/blob/master/src/jp/co/example/testapp/MainActivity.java
Around line 127, it chooses to use a database connection to fetch content from the database.
Instead of fetching data from the database, I'd like to use an ArrayList to hold the data. Could anyone help me figure out what I need to do? Thanks!
Not a one-for-one example based on your code, but this is will populate a list from a database table without a simple cursor:
public class MyListAdapter extends ListActivity {
List<ContactGroup> groups = new ArrayList<ContactGroup>();
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.groups = getGrpList();
ContactGroupAdapter cAdapter = new ContactGroupAdapter(this);
setListAdapter(cAdapter);
}
private List<ContactGroup> getGrpList(){
List<ContactGroup> grps = new ArrayList<ContactGroup>();
ContentResolver cr = getContentResolver();
Cursor groupCur = cr.query(Groups.CONTENT_URI, new String [] {Groups._ID, Groups.NAME}, null, null, Groups.NAME + " ASC");
if (groupCur.getCount() > 0) {
while (groupCur.moveToNext()) {
ContactGroup newGroup = new ContactGroup();
newGroup.Name = groupCur.getString(groupCur.getColumnIndex(Groups.NAME));
newGroup.Id = groupCur.getString(groupCur.getColumnIndex(Groups._ID));
grps.add(newGroup);
}
}
return grps;
}
public class ContactGroupAdapter extends BaseAdapter{
public ContactGroupAdapter(Context c) {
mContext = c;
}
public int getCount() {
return groups.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
LayoutInflater vi = LayoutInflater.from(this.mContext);
convertView = vi.inflate(R.layout.two_line_list_item, null);
holder = new ViewHolder();
convertView.setTag(holder);
}
else {
//Get view holder back
holder = (ViewHolder) convertView.getTag();
}
ContactGroup cg = groups.get(position);
if (cg != null) {
//Name
holder.toptext = (TextView) convertView.findViewById(R.id.text1);
holder.toptext.setText(cg.Name);
//ID
holder.bottomtext = (TextView) convertView.findViewById(R.id.text2);
holder.bottomtext.setText(cg.Id);
}
return convertView;
}
private Context mContext;
}
public static class ViewHolder {
TextView toptext;
TextView bottomtext;
}
public class ContactGroup{
public String Id;
public String Name;
}
}
Then there are XML files ...
two_line_list_item.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">
<TextView android:id="#+id/text1" android:textStyle="bold"
android:layout_width="fill_parent" android:layout_height="wrap_content" />
<TextView android:id="#+id/text2" android:textStyle="bold"
android:layout_width="fill_parent" android:layout_height="wrap_content" />
</LinearLayout>
and main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:paddingLeft="8dp"
android:paddingRight="8dp">
<ListView android:id="#+id/android:list" android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<TextView android:id="#id/android:empty" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:text="No Groups" />
</LinearLayout>