ListView - Custom Adapter - Database - android

Android 2.3.3
I have a table in database with two columns. I wish to retrieve this data and show them in a ListView having two textviews(first column in first textview and second column in second textview) and repeat this till for all the rows in the database. I have read a few examples on(custom adapter and listview) how to do, but the more I read, the more I get confused.
Can someone give me a head start on how to do this? I can use a dynamic listview, but I wish to do it using the static one.
Here is the Layout of the row in the listview:
<?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"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:paddingBottom="5dp"
android:paddingTop="5dp" >
<TextView
android:id="#+id/txtView_History_Expression"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="0.50"
android:text="Expression"
android:textColor="#FFFFFF"
/>
<TextView
android:id="#+id/txtView_History_Result"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="0.50"
android:text="Result"
android:textColor="#316DA2" />
</LinearLayout>
Here is the XML with ListView:
<?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/txtView_History_Header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="HISTORY"
android:gravity="center"
android:textSize="24dp"
android:textColor="#316DA2"
android:paddingTop="10dp"
/>
<ListView
android:id="#+id/lvHistory"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
I am retrieving the data from database and storing it in a Cursor. I want to read data from Cursor and give those values to the textviews in the listview.

I have a table in database with two columns. I wish to retrieve this
data and show them in a ListView having two textviews(first column in
first textview and second column in second textview) and repeat this
till for all the rows in the database. I have read a few examples
on(custom adapter and listview) how to do, but the more I read, the
more I get confused.
Hello. This algorithm is not too tricky. You need to these steps:
Create some method for getting rows from db. You can return either
List<TableDataType> or directly Cursor.
Create subclass of some ListAdapter to get better control over it.
Set ListAdapter to ListView.
Example:
Method for getting data from db:
public List<DataType> getAll() {
List<DataType> objects = new ArrayList<DataType>();
DataType child = null;
Cursor c = null;
try {
String query = "select * from TableName";
c = db.rawQuery(query, null);
if (c.moveToFirst()) {
child = new DataType();
child.setId(c.getInt(c.getColumnIndex("id")));
child.setName(c.getString(c.getColumnIndex("name")));
objects.add(child);
}
return objects;
}
finally {
if (c != null) {
c.close();
}
if (db != null) {
db.close();
}
}
}
Then you can create own Adapter extending from BaseAdapter and set data to TextViews in getView() method and create RowHolder that will be arbitrary Object that holds childs(widgets) of each row
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
// inflate convertView and add row to RowHolder
// set RowHolder as tag of row .. convertView.setTag(rowHolder);
}
else {
// just recycle views so get existing RowHolder
rowHolder = (RowHolder) convertView.getTag();
}
// set data to widget(s)
rowHolder.getFirstTextView().setText(dataSource.get(position).getId());
...
}
RowHolder can looks like
public class RowHolder {
private View row;
private TextView idColumn;
public RowHolder(View v) {
this.row = v;
}
public TextView getIdColumn() {
if (idColumn == null) {
idColumn = (TextView) row.findViewById(R.id.idColumnId);
}
return idColumn;
}
}
And finally set Adapter to ListView and work is done.
Note:
DataType is own defined Object. It presents Table in your db where properties of Object are identical with columns in Table.
There is other approach and return from db Cursor and a usage of SimpleCursorAdapter or CursorAdapter. Here are nice examples:
Android Listview Example using CursorAdapter and SQLite
database
SimpleCursorAdapters and
ListViews

you should follow this flow
step 1 -> get data from data base and Fill the List with getter Setter
Step 2 -> Create BaseAdapter Class and give that list in this class[Here you need to see BaseAdpter bind methods]
Stap 3 -> Bind BaseAdapter object with Your ListView

All you can do is take a look at Bind the List view from Database with Cursor Adapter.
Also check the ListView Example using Cursor Adapter with SQLiteDatabase.
I hope this will guide you.
Thanks.

Related

Android - SQLite Database retrieving of values then output as looped Checkboxes based on the amount of IDs in Database [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Mock Up of the App I'm trying to make.
SELECTION:
New to Android but I'm trying to retrieve the values from my SQLite Database and make a continuous loop of checkboxes based on the amount of IDs stored. The checkboxes will just output the subject name. If possible it should output subject name and units. Can you help me?
//get all subjects
public List < Subject > getAllSubjects() {
List < Subject > subjectList = new ArrayList < Subject > ();
//select all query
String selectQuery = " SELECT * FROM " + TABLE_SUBJECTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
//loop through all rows and add it to list
if (cursor.moveToFirst()) {
do {
Subject subject = new Subject();
subject.setID(Integer.parseInt(cursor.getString(0)));
subject.setSubName(cursor.getString(1));
subject.setUnits(cursor.getString(2));
//ADD CONTACT TO LIST
subjectList.add(subject);
} while (cursor.moveToNext());
}
return subjectList;
}
Need a syntax or code example on how I can retrieve the subjectList values into MainActivity and output them as looped Checkboxes and/or ListViews.
First refer this link : Learn SQLITE.
With the help of above tutorial Create two tables named Subjects & Teachers, The structure of tables will be like this:
Subject : ID integer PRIMARY KEY AUTOINCREAMENT, NAME text, UNITS text.
Teachers : ID integer PRIMARY KEY AUTOINCREAMENT, NAME text, Subjects text.
For add class Subject.
There will be two edittexts 1st will have Sub name and second will have number of Units. Take that two values in separate string on button click and store the in Subjects table. Now your subject table will contain a record like:
Id Name Units
1 Subject-1 4
Like this go on entering Subjects.
For add teachers and assignments
You will be having one edittext in which name of the teacher will be entered. One selection button, On the click of that button You can show the list of subject from our Subjects Table.
on click of Ok in dialog you can get selected subjects.
Submit button click, Save the teachers data in table Teachers.Store only id's of subject comma separated. After that refer a particular by its id only.
Now the teachers table will be having data like :
Id Name Subjects
1 daniel 1,2
For the list of Teachers
Show the list from our Teachers table.
EDIT 2: For Setting the list to listView
Refer this link : How to set list in ListView+CheckBoxes
I am summarizing the concept here:
Step : 1
You need to create a list_item.xml layout which will contain a TextView And a Check box only Horizontally placed :
<?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"
android:padding="6dip" >
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:focusable="false"
android:focusableInTouchMode="false"
android:text="CheckBox" />
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/checkBox1"
android:layout_alignBottom="#+id/checkBox1"
android:layout_toRightOf="#+id/checkBox1"
android:text="TextView" />
</LinearLayout>
Step : 2
You need to create an adapter which will be taking care of your list which will be set to the listView.
public class MyCustomAdapter extends ArrayAdapter<Subject> {
private ArrayList<Subject> subList;
public MyCustomAdapter(Context context, int textViewResourceId,
ArrayList<Subject> subList) {
super(context, textViewResourceId, subList);
this.subList = new ArrayList<Subject>();
this.subList.addAll(subList);
}
private class ViewHolder {
TextView name;
CheckBox chk_box;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.chk_box = (CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Subject subject = subList.get(position);
holder.name.setText(subject.getSubName() + " - " + subject.getUnits());
return convertView;
}
}
Step - 3
Set this adapter to you ListView in MainActivty:
Create another xml activity_main.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<ListView
android:id="#+id/mylist"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
MainActivty.java
public class MainActivity extends Activity {
ListView mylist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mylist = (ListView)findViewById(R.id.mylist);
mylist.setAdapter(new MyCustomAdapter(MainActivty.this,subjectList,R.layout.list_item));
}
}

How to prevent ListView with two columns from drawing to the size of ArrayList passed (prevent populating empty items)?

I have a custom ListView Adaper that has two columns. It accepts an ArrayList and populate its content in two columns.
My adapter class is like this
public class myAdapter extends ArrayAdapter<String []> {
private final Activity activity;
private final ArrayList<String []> myArray;
public myAdapter(Activity activity,ArrayList<String[]> arraylist){
super(activity,R.layout.customListview,arraylist);
this.activity = activity;
this.myArray = arraylist;
}
#Override
public View getView(final int position,View view, ViewGroup parent){
LayoutInflater inflater = activity.getLayoutInflater();
View rowView = inflater.inflate(R.layout.customListview, null, true);
if (position < (myArray.size()/2)){
textview1.setText(myArray.get(position*2)[0]);
textview2.setText(myArray.get((position*2)+1)[0]);
}
else {
LinearLayout listRow = (LinearLayout)rowView.findViewById(R.id.listRow);
listRow.setVisibility(View.GONE);
textvew1.setVisibility(View.GONE);
textvew2.setVisibility(View.GONE);
}
return rowView;
}
My listview is displaying contents properly. But there is a blank space below my listview. I think it is populating null elements with list item for the size of the array passed. Since I am displaying the contents of my array in two columns, I need the size of listview to be only the half of my array. Any suggestions?
Thanks in advance.This happens if i pass array with 2 elements
Here is the customListview.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:id="#+id/listRow"
android:orientation="horizontal"
android:weightSum="1">
<TextView
android:layout_weight="0.5"
android:layout_width="0sp"
android:layout_height="match_parent"
android:textAlignment="center"
android:id="#+id/text1"
android:layout_marginRight="10dp"/>
<TextView
android:layout_weight="0.5"
android:layout_width="0sp"
android:layout_height="match_parent"
android:textAlignment="center"
android:id="#+id/text2"
android:layout_marginLeft="10dp"/>
</LinearLayout>
just override getCount() inside your adapter and set the list length
#Override
public int getCount() {
return myArray.size() / 2;
}
As #nbaroz mentioned in his answer you should override getCount() and return a custom value based on the content inside of myArray. Further more, it seems that since you only want your ListView to contain two rows you should only return 2 from getCount(). This way it will always only have two cells.
Based on what I understand from your description, you are trying to create a layout similar to the Play store; where you have several rows and in each row you have several individual columns. This can be done with only one data structure (ArrayList or LinkedList) to make the design easier. You would do this by having the data structure length be the amount of rows (this is better than hard-coding a value) you want to display. The items inside of the data structure would be of a custom object type that contains the data necessary for populating the columns inside of each row.
Example Custom ListView item object:
public class MyCustomRowObject {
public Column column1;
public Column column2;
public Column column2;
public Column getColumn1() {
return column1;
}
public Column getColumn2() {
return column2;
}
public Column getColumn3() {
return column3;
}
Inside of getView(...) you would get a reference of MyCustomRowObject and create your custom list item that contains the individual views for the columns of the row. Once the list item is inflated, use the data from MyCustomRowObject reference to populate the views data fields and return the list item. Viola!
Also note
This will incur a lot of overhead inflating all of these views so you definitely will want to using the view recycling pattern if you have any content that scroll of screen. Personally, I would use the recycling pattern always even if I don't have a lot of list data because it makes it future proof.

View data from SQLite database using ListView on Android

I am quite new to Android development. I managed to get data saved to SQLite database. Now, what I want is to view these data when I call viewData(). I have viewData() which shows data as a Toast as I made it as a sample. Now I need these data to show on a new activity using a ListView, but the number of data to show is depending on how many data is in the database at the moment, If user saved 10 items then I want all the 10 items to shown up. How can I do it?
I hope my question is clear.
Thanks in advance.
you could use ListView
declare it in your layout
<LinearLayout 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"
android:orientation="vertical">
<ListView
android:id="#+id/list"
android:layout_height="wrap_content"
android:layout_width="match_parent">
</ListView>
</LinearLayout>
in yor activity declare a globar var:
ListView listView;
and onCreate
listView = (ListView) findViewById(R.id.list);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
// Assign adapter to ListView
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id){
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
String itemValue = (String) listView.getItemAtPosition(position);
}
});
datos can be an array that you can populate with data that you extract from your data base and that's the most simple way to show it. if you want to customizise your listView you can create a custom adapter, or in other way the newest element that replace listView is ReciclerView. I hope tihs help you
You can use a SimpleCursorAdapter:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListView answerList=(ListView)findViewById(R.id.answerList);
Cursor mCursor = getData();
startManagingCursor(mCursor);
// now create a new list adapter bound to the cursor.
// SimpleListAdapter is designed for binding to a Cursor.
ListAdapter adapter = new SimpleCursorAdapter(this, // Context.
android.R.layout.two_line_list_item,
mCursor, // Pass in the cursor to bind to.
// Array of cursor columns to bind to.
new String[] {"_id", "answer"};
// Parallel array of which template objects to bind to those
// columns.
new int[] { android.R.id.text1,android.R.id.text2 });
// Bind to our new adapter.
answerList.setAdapter(adapter);
}
private Cursor getData() {
String sq = "Select _id, answer from foo";
Cursor c = db.rawQuery(sql);
return c;
}
I will try to give an in-depth answer to this.
Whenever you want to fetch and display a list of data from the database, you can use a ListView, GridView, Spinner, etc for it.
You can use a CursorAdapter which can make the job of querying and displaying data much more simple and easy.
Here is a basic visual representation of it,
Step 1
Firstly, you need to create a database. As mentioned in your question, it is clear that you know how to create a database and put some data into it. So I am not going into the depths of it.
Step 2
We need to define the layout to be used for the individual items in the ListView and save it as res/layout/item_todo.xml This is just a sample layout, you can design any kind of layout you want to.
<?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" >
<TextView
android:id="#+id/tvBody"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Study cursors"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/tvPriority"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="3"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
Step 3
Now we need to define an adapter. Here we are using a CursorAdapter which converts a Cursor (that you provide) into Views (defined by your layout).
There are two methods, newView and bindView which we need to override. The newView is responsible for inflating newViews for the first time and the bindView is responsible for binding the data to the Views.
public class TodoCursorAdapter extends CursorAdapter {
public TodoCursorAdapter(Context context, Cursor cursor) {
super(context, cursor, 0);
}
// The newView method is used to inflate a new view and return it,
// you don't bind any data to the view at this point.
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.item_todo, parent, false);
}
// The bindView method is used to bind all data to a given view
// such as setting the text on a TextView.
#Override
public void bindView(View view, Context context, Cursor cursor) {
// Find fields to populate in inflated template
TextView tvBody = (TextView) view.findViewById(R.id.tvBody);
TextView tvPriority = (TextView) view.findViewById(R.id.tvPriority);
// Extract properties from cursor
String body = cursor.getString(cursor.getColumnIndexOrThrow("body"));
int priority = cursor.getInt(cursor.getColumnIndexOrThrow("priority"));
// Populate fields with extracted properties
tvBody.setText(body);
tvPriority.setText(String.valueOf(priority));
}
}
Step 4
Now as you can clearly see, that the constructor needs a Context and a Cursor. Now we need to query the database and retrieve the data into a Cursor and pass it to the adapter.
// TodoDatabaseHandler is a SQLiteOpenHelper class connecting to SQLite
TodoDatabaseHandler handler = new TodoDatabaseHandler(this);
// Get access to the underlying writeable database
SQLiteDatabase db = handler.getWritableDatabase();
// Query for items from the database and get a cursor back
Cursor todoCursor = db.rawQuery("SELECT * FROM todo_items", null);
Step 5
This is the last step where we need to instantiate the adapter and attach the ListView with the adapter to populate the data.
// Find ListView to populate
ListView lvItems = (ListView) findViewById(R.id.lvItems);
// Setup cursor adapter using cursor from last step
TodoCursorAdapter todoAdapter = new TodoCursorAdapter(this, todoCursor);
// Attach cursor adapter to the ListView
lvItems.setAdapter(todoAdapter);

Retrieve array from SQLite in listview with more than a colum (ANDROID)

So I want to create a listview that consists of more than a column. I already succeed called the database, but the layouting still not work. I think this is because the all my data are put in one array and its difficult to make them in three columns. anyone can find solution for me?
My program result is like this in listview:
John Doe 12 Argentina
Marilyn Rose 32 Russia
Annabella 19 United States
However what I want is more like this:
John Doe 12 Argentina
Marilyn Rose 32 Russia
Annabella 19 United States
From what I read, we will need 2 XMLs. One for listview, and another is for layouting (give space between text). And One .JAVA called adapter to connect my MainActivity.java and layouting XML.
add:
I already tried using two XMLs. one XML, lets call it main.XML is for calling ListView. And grid.XML, is where i put android:layout_alignParentLeft="true" (to create spaces).
I used MyAdapter.JAVA to convertview in grid.XML. and in MainActivity.JAVA i called MyAdapter. However my code in MainActivity became error when its connected it MyAdapter.
this was my code that gave error java.lang.RuntimeException. So I had to delete it.. more information about it, please check two last code...
MainActivity.java (error)
public static ArrayList<String> arraydealer = new ArrayList<String>();
MyAdapter bohwat = new MyAdapter(MainActivity.this, arraydealer);
lvcustom.setAdapter(bohwat);
And here is the code that is working well. It uses class MainActivity, AstraDB, and MySetGet, and main.XML. Other class thats not working is MyAdapter and grid.xml
This is how I called my database:
public class MainActivity extends Activity
{
public static ArrayList<String> arraydealer = new ArrayList<String>();
AstraDB astrahandler = new AstraDB(this);
Spinner spDealer;
ListView lvcustom;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lvcustom = (ListView)findViewById(R.id.custom_lv);
ShowListView();
}
private void ShowListView()
{
astrahandler.getAllDealer();
ArrayAdapter<String> adapt = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, arraydealer);
lvcustom.setAdapter(adapt);
}
}
This code of ArrayList in Activity and String name in AstraDB are very important to connect my MainActivity with the database but it seems this create trouble in layouting. because they are contained in ONE array
And this is function to get all data in my DB. its on AstraDB.java:
public List<MySetGet> getAllDealer()
{
List<MySetGet> info = new ArrayList<MySetGet>();
db = DBHelper.getReadableDatabase();
// Select All Query
String selectQuery = "SELECT * FROM Dealer";
cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
MySetGet lets = new MySetGet();
lets.setDealerID(Integer.parseInt(cursor.getString(0)));
lets.setDealerName(cursor.getString(1));
lets.setDealerOwner(cursor.getString(2));
lets.setDealerWil(cursor.getString(3));
String name = cursor.getInt(0) +
"\u00A0 "+ cursor.getString(1)+
"\u00A0 "+ cursor.getString(2)+
"\u00A0 "+ cursor.getString(3);
MainActivity.arraydealer.add(name);
//add
info.add(lets);
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
//return contentdealer;
return info;
}
The MySetGet in getAllDealer() connects with MySetGet.java where I put setter and getter so the data can become object. which is more like this:
public int getDealerID(){ return DealerID;}
public void setDealerID(int DealerID) { this.DealerID = DealerID; }
Code to connect other XML with Java but still gave error:
grid_dealer.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:layout_height="wrap_content"
android:layout_width="50dp"
android:id="#+id/col1"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text=""/>
<TextView
android:layout_height="wrap_content"
android:layout_width="100dp"
android:id="#+id/col2"
android:layout_toRightOf="#id/col1"
android:layout_centerVertical="true"
android:text=""/>
important code in MyAdapter.java:
public class MyAdapter extends BaseAdapter
{
Context context;
ArrayList<MySetGet> dealerlist;
public MyAdapter(Context context, ArrayList<MySetGet>list)
{
this.context = context;
dealerlist = list;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
MySetGet yay = dealerlist.get(position);
//this is to customize the layout of the listview
if(convertView == null)
{
LayoutInflater inflater = null;
inflater = (LayoutInflater)context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.grid_dealer, null);
}
TextView tvID = (TextView)convertView.findViewById(R.id.col1);
tvID.setText(yay.getDealerID());
TextView tvName = (TextView)convertView.findViewById(R.id.col2);
tvName.setText(yay.getDealerName());
TextView tvOwner = (TextView)convertView.findViewById(R.id.col3);
tvOwner.setText(yay.getDealerOwner());
return convertView;
}
}
Please help me. I am very new to this. Is there a way to modify my code without changing too much on how I called my database? The class and XML below works fine in showing database, but didnt create a neat layout space between columns
Working class : AstraDB, MainActivity, MySetGet
Working XML : main.xml
Im sorry, if the post becomes longer. I want to clarify several things so that there is no misunderstanding.
you can use android:layout_weight="" for better arrangement of views
Using SimpleCursorAdapter is the ideal solution in your case. Please checkout a tutorial here that will take you through the steps in achieving what you want.
In simple_list_item_1 layout if you arrange items relative to each other you will get the result what you are getting now. If you want proper formatting, relate the elements to left, center and right using android:layout_alignParentLeft="true", android:centerHorizontal="true" and android:layout_alignParentRight="true" respectively

Android: get the i-th TextView inside a ListView

I'm try to write a little application and the releated unit tests.
I have a ListView binded to a SimpleCursorAdapter reading data from an SQL table.
The Activity#onCreate() method is:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dbHelper = new DatabaseHelper(this);
SQLiteDatabase dbRead = dbHelper.getReadableDatabase();
String[] columns={BaseColumns._ID, ENTRY_VALUE};
cursor = dbRead.query(ENTRIES_TABLENAME, columns, null, null, null, null, null);
String[] from = {"value"};
int[] to = {R.id.value};
adapter = new SimpleCursorAdapter(this, R.layout.list_entry, cursor, from, to);
setListAdapter(adapter);
}
My test inside the unit-test is:
#UiThreadTest
public void testTheElementInsideTheDBisDisplayedInTheList() {
String entryValue = "clipboard entry 1";
DatabaseHelper dbHelper = new DatabaseHelper(cmActivity);
Cursor beforeCursor = selectAllEntries(dbHelper);
// The table, at the begining of the test, is empty, I control that
assertEquals(0, beforeCursor.getCount());
// I insert the new value in the table
insertEntry(dbHelper, entryValue);
// and I control that is really inside the table now
Cursor afterCursor = selectAllEntries(dbHelper);
assertEquals(1, afterCursor.getCount());
// This method calls the method "requery()" on the cursor associate
// to the listView's adapter to update the list view
cmActivity.updateList();
// I control that the listView is updated
assertEquals(1, entryList.getCount());
// Now I try to retrive the only child inside the list view
// to extract the text inside it and to compare this text with
// the value inserted into the DB table.
TextView entryView = (TextView) entryList.getChildAt(0);
String viewText = entryView.getText().toString();
assertEquals(entryValue, viewText);
}
My problem is in the third-last row:
TextView entryView = (TextView) entryList.getChildAt(0);
I sude getChildAt() to get the first TextView child of the ListView. But this method returns null, so the test gets a NullPointerException.
Maybe getChildAt() is not the right method to get the View child from a ListView, so which is the correct one?
I see from the documenation that the method works with GroupView, I didn't use them, do I need to configure a default GroupView and put all the entry inside it? In this way, will getChildAt(0) work? Is this the correct way to setup a ListView?
thank you, bye
Andrea
As asked by Vivek, I post here the 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">
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView android:id="#android:id/empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Empty set"
/>
</LinearLayout>
As you can see is very very basic. Also le list entry is very simple:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/value"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="16sp" >
</TextView>
I doubt if the list is populated when you call getChildAt() method. So call getChildCount() method and see if the list is populated. And post back the output here.
Edit:
Now I understand the problem. ListView.getCount() method returns the number of items populated in the list. And ListView.getChildCount() Method or ListView.getChildAt() Method will return 0 here because these methods will return a value only when the view is visible to the user. You can use getChildAt() method only after the textviews are generated. i.e If you use the method in OnItemClick method of the listview, or any listview listener implementation, you will get the desired output. What is the need to get the reference to the textviews here in this method anyways?

Categories

Resources