Database listview how to relate to the DB record

Basic Tutorials concerning: GUI, Views, Activites, XML, Layouts, Intents, ...

Database listview how to relate to the DB record

Postby Mark Worsnop » Sun Dec 05, 2010 3:48 am

I have figured out how to open the DB and display a couple of fields on a list view. Yippee!

BUT... I need to relate back to the DB record.

For example I have a DB with these fields:
Last Name
First Name
ID

I want to show the first and last name on the list, which isnt a problem, however I need to have the ID somehow. Obviously I dont want to show the ID. So if I click on the list I need to be able to get the ID of the record so I can do whatever.

Can anyone help with this and tell me where I can find code that works so I can try this? I have seen several posts that say try this or that but I havent figured out how to use any of the suggestions in other posts.

Sure do appreciate everyones input on the forum so far... thank you!
Mark Worsnop
Junior Developer
Junior Developer
 
Posts: 24
Joined: Wed Dec 01, 2010 12:34 am

Top

Re: Database listview how to relate to the DB record

Postby blundell » Sun Dec 05, 2010 10:53 am

Ok, this is quite simple if I can explain it correctly.

You ListView display's a list of items, this list can be a list of objects.

Pseudo:
Code: Select all
List listItems = {listObject1, listObject2, listObject3};


So if your using this to instantiate your list, when you have an onItemClickListener, it gives you back the position in the list. This position in the list is the position in your List object. (So if they click the second item down you can retrieve listItems[1] (0 based) giving you listObject2.

Now your ListObject item. If you create this like this:
Code: Select all
public class ListObject {

Long id;
String firstName;
String lastName;

}


You have all three field's stored but only show the one's you want! So when accessing the database you can call, listObject2.getId(); and when showing text on the list item you can call listObject2.getFirstNAme+" "+listObject2.getLastname(); or whatever you want :-)

Hope that explains it for you.

Basically the short answer is, have your list show a list of objects and have a reference to the database ID in this object.
User avatar
blundell
Master Developer
Master Developer
 
Posts: 1610
Joined: Tue Nov 18, 2008 12:58 pm
Location: UK

Re: Database listview how to relate to the DB record

Postby Mark Worsnop » Sun Dec 05, 2010 3:39 pm

Sorry I am a newbie and trying to learn this stuff. thanks for the help!

Below is what I have to take the DB and put it on a list. As you can see I am currently displaying both the ID and the string in the list.

Do I have to make a class (listObjectItem) for every table I want to display on a list and load that class first? What then? An array of the listobjectItem?

How would I change this to work the way you said?

-----

ArrayList<String> results = new ArrayList<String>();
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);


Cursor c = myDataBase.rawQuery("SELECT Description,_id FROM Grp where _id > 1 LIMIT 5", null);

if (c != null ) {
if (c.moveToFirst()) {
do {

String Descr = c.getString(c.getColumnIndex("Description"));
int id = c.getInt(c.getColumnIndex("_id"));
results.add("" + Descr + ",ID: " + id);

}while (c.moveToNext());
}
}

adapter=new ArrayAdapter<String>( this,android.R.layout.simple_list_item_1,results);

setListAdapter(adapter);


getListView().setOnItemLongClickListener(itemDelListener);
Mark Worsnop
Junior Developer
Junior Developer
 
Posts: 24
Joined: Wed Dec 01, 2010 12:34 am

Re: Database listview how to relate to the DB record

Postby blundell » Sun Dec 05, 2010 4:47 pm

Yes so create a new class MyObject or whatever you want to call it.

then in here
Code: Select all



if (c != null ) {
if (c.moveToFirst()) {
do {

MyObject m = new MyObject();
m.setId(c.getColumnIndex("_id"));
m.setDescription(c.getColumnIndex("Description"));
results.add(m); OR results.add(m.toString()); //Then override the toString method in your class

}while (c.moveToNext());
}
}


So results needs to be a List<MyObject>
User avatar
blundell
Master Developer
Master Developer
 
Posts: 1610
Joined: Tue Nov 18, 2008 12:58 pm
Location: UK

Re: Database listview how to relate to the DB record

Postby Mark Worsnop » Sun Dec 05, 2010 6:58 pm

What is the definition then for MyObject class? what would it look like? Is this correct?

Syntax: [ Download ] [ Hide ]
Using javascript Syntax Highlighting
  1. public class MyObj {
  2.  
  3.                 int id;[syntax=""][/syntax]
  4.                 String Description;
  5.                
  6.                 public int getId() {
  7.                         return id;
  8.                 }
  9.                 public void setId(int id) {
  10.                         this.id = id;
  11.                 }
  12.                 public String getDescription() {
  13.                         return Description;
  14.                 }
  15.                 public void setDescription(String description) {
  16.                         Description = description;
  17.                 }
  18.                
  19. }
  20.  
Parsed in 0.003 seconds, using GeSHi 1.0.8.4


The in the sample code you sent, how would I declare the MyObject? Is this correct Doesnt seem to work. Says
Cannot instantiate the type List

Syntax: [ Download ] [ Hide ]
Using javascript Syntax Highlighting
  1. List<MyObject> results = new List<MyObject>();
  2.  
Parsed in 0.001 seconds, using GeSHi 1.0.8.4



And the biggest question is... ok I have the data into the MyObject... then what do I do to attach this to the list?

It still hasnt quite hit me yet, why you can send MyObject to the list that has the 2 fields, but why would the list only show the 1 description field? Is this correct?

adapter=new ArrayAdapter<String>( this,android.R.layout.simple_list_item_1,results);

setListAdapter(adapter);
Last edited by Mark Worsnop on Sun Dec 05, 2010 7:29 pm, edited 1 time in total.
Mark Worsnop
Junior Developer
Junior Developer
 
Posts: 24
Joined: Wed Dec 01, 2010 12:34 am

Re: Database listview how to relate to the DB record

Postby blundell » Sun Dec 05, 2010 7:20 pm

Yes your MyObject would look like this
Code: Select all
public class MyObject {
Long id;
String Description;

public Long getID(){
return id;
}

public void setID(Long id){
this.id = id;
}

// And getter an setter for description
}


Yeah I noticed your using the normal ListView to display your items and this takes a List of Strings so where going to have to do it a little different to keep it simple.

List<MyObject> myResults = new List<MyObject>(); // is where you will store your object
List<String> listResults = new List<String>(); // Is where you will store the stings your list shows

so

myResults.add(m);
listResults.add(m.getDescription());

adapter=new ArrayAdapter<String>( this,android.R.layout.simple_list_item_1,listResults);

So basically the two list's are parralel and item 1 in myResults will always refer to the same object as item 1 in listResults


Later on when you have got this working, you could change your listview to use a custom adapter and then you could play with the ListView a bit more and would only need one List :-)
User avatar
blundell
Master Developer
Master Developer
 
Posts: 1610
Joined: Tue Nov 18, 2008 12:58 pm
Location: UK

Top

Re: Database listview how to relate to the DB record

Postby Mark Worsnop » Sun Dec 05, 2010 7:32 pm

I was adding to the last message when you replied, sorry... Also I got an error see my last post


Should I do the adapter now and not use List?
Mark Worsnop
Junior Developer
Junior Developer
 
Posts: 24
Joined: Wed Dec 01, 2010 12:34 am

Re: Database listview how to relate to the DB record

Postby blundell » Sun Dec 05, 2010 7:55 pm

Ok if your doing this

adapter=new DatabaseAdapter( this, R.layout.listrow, listResults);
setListAdapter(adapter);

You then need the Class DatabaseAdapter and the XML layout listrow.

The xml file is the definition of what each listview item looks like. So for now we'll just have a TextView (ie a string)
Code: Select all
<LinearLayout...

<TextView
  android:id="@+id/myTextView"
....
  />
/>


And the DatabaseAdapter.java:
Code: Select all
public class DatabaseAdapter extends ArrayAdapter<MyObject> {
       
        private Context mContext;
        private ArrayList<MyObject> mItems;
        private int mXmlId;
               
        public DatabaseAdapter(Context context, int textViewResourceId, ArrayList<MyObject> items) {
                super(context, textViewResourceId, items);
                this.mContext = context;
                this.mItems = items;
                this.mXmlId = textViewResourceId;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
                View v = convertView;
                if (v == null) {
                        LayoutInflater vi = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                        v = vi.inflate(mXmlId, null);
                }
                MyObject mo = mItems.get(position);
                if (mo  != null) {
                        TextView text = (TextView) v.findViewById(R.id.myTextView);
                        if (text != null) {
                                if(mo .getDescription() != null){
                                        text .setText(mo .getDescription());
                                }
                        }               
                }
                return v;
        }
}
User avatar
blundell
Master Developer
Master Developer
 
Posts: 1610
Joined: Tue Nov 18, 2008 12:58 pm
Location: UK

Re: Database listview how to relate to the DB record

Postby Mark Worsnop » Sun Dec 05, 2010 8:09 pm

I thought I almost had this figured out until the last post :(
thanks for your patience!

The last post using the databaseadapter is that the alternate to using the list?

I wasnt able to make the list work becuase of this:
List<MyObject> results = new List<MyObject>();
This give an error. "Cannot instantiate the type List"


In you example directly above is the listresults a string?

Is there any code or maybe you have to shows how to do this that works if I just drop it in?
Mark Worsnop
Junior Developer
Junior Developer
 
Posts: 24
Joined: Wed Dec 01, 2010 12:34 am

Re: Database listview how to relate to the DB record

Postby blundell » Sun Dec 05, 2010 8:17 pm

Sorry ArrayList<MyObject> results = new ArrayList<MyObject>();

You need this list to pass it into the Adapter, the Adapter basically takes the ArrayList and convert's it into a view for the Android ListView to use hence name 'adapter' :-)
User avatar
blundell
Master Developer
Master Developer
 
Posts: 1610
Joined: Tue Nov 18, 2008 12:58 pm
Location: UK

Re: Database listview how to relate to the DB record

Postby blundell » Sun Dec 05, 2010 8:34 pm

Here maybe this makes it a bit clearer :-)

ImageLoader.rar
Custom ListView with references
(37.74 KiB) Downloaded 89 times
User avatar
blundell
Master Developer
Master Developer
 
Posts: 1610
Joined: Tue Nov 18, 2008 12:58 pm
Location: UK

Re: Database listview how to relate to the DB record

Postby Mark Worsnop » Sun Dec 05, 2010 8:49 pm

I have two errors that I cant run without fixing. There is probably some changes needed in the readdata() functions too. Could you please tell me what the 2 errors mean, and also what do i need to change on readdata()

Here are all the parts of what I think I am supposed to be doing:

text.xml

<?xml version="1.0" encoding="utf-8"?>


<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:cacheColorHint="#00000000"

android:id="@android:id/list" >

</ListView>

mylist.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">

<TextView
android:id="@+id/myTextView"

/>


</LinearLayout>


DataBaseAdapter class

package com.mvw;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;

import android.database.Cursor;

import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

ERROR HERE:
Constructor call must be the first statement in a constructorline 32 Java Problem

public class DataBaseAdapter extends ArrayAdapter<MyObj> {

private Context mContext;
private ArrayList<MyObj> mItems;
private int mXmlId;


ERROR HERE
Implicit super constructor ArrayAdapter<MyObj>() is undefined for default constructor. Must define an explicit constructor

public void DatabaseAdapter(Context context, int textViewResourceId, ArrayList<MyObj> items) {
super(context, textViewResourceId, items);
this.mContext = context;
this.mItems = items;
this.mXmlId = textViewResourceId;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(mXmlId, null);
}
MyObj mo = mItems.get(position);
if (mo != null) {
TextView text = (TextView) v.findViewById(R.id.myTextView);
if (text != null) {
if(mo .getDescription() != null){
text .setText(mo .getDescription());
}
}
}
return v;
}
}


And finally the TEST class

package com.mvw;


import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import com.mvw.DataBaseHelper;


import android.app.AlertDialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;



public class test extends ListActivity {
private static String DB_PATH = "/data/data/com.mvw/databases/";

private static String DB_NAME = "Food.sqlite";

private SQLiteDatabase myDataBase;

ArrayList<MyObj> results = new ArrayList<MyObj>();

ArrayAdapter<MyObj> adapter;


DataBaseHelper db = new DataBaseHelper(null);


//public ArrayList<String> ReadData2() {
public ArrayList<MyObj> ReadData2() {

ArrayList<MyObj> results = new ArrayList<MyObj>();

String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);


Cursor c = myDataBase.rawQuery("SELECT Description,_id FROM Grp where _id > 1 LIMIT 5", null);

if (c != null ) {
if (c.moveToFirst()) {
do {

String Descr = c.getString(c.getColumnIndex("Description"));
int id = c.getInt(c.getColumnIndex("_id"));


MyObj m = new MyObj();

m.setId(id);

m.setDescription(Descr);

results.add(m);
//OR results.add(m.toString()); //Then override the toString method in your class

//results.add("" + Descr + ",ID: " + id);

}while (c.moveToNext());
}
}

return results;

}


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);


results = db.ReadData2();


adapter=new ArrayAdapter<MyObj>( this,android.R.layout.simple_list_item_1,results);

setListAdapter(adapter);


}
}
Mark Worsnop
Junior Developer
Junior Developer
 
Posts: 24
Joined: Wed Dec 01, 2010 12:34 am

Re: Database listview how to relate to the DB record

Postby blundell » Sun Dec 05, 2010 8:56 pm

Please post your code in code tags [ code ] :-) [/ code ]

Check the example project I attached, both error's look like the same problem. Also you missed out the layout params of the textview width an height.

Also press ctrl+shift+O in each of your class files, it will clear up the import your dont need or use :-)
User avatar
blundell
Master Developer
Master Developer
 
Posts: 1610
Joined: Tue Nov 18, 2008 12:58 pm
Location: UK

Re: Database listview how to relate to the DB record

Postby Mark Worsnop » Sun Dec 05, 2010 9:03 pm

I looked in the example you sent but still do not understand what these 2 errors mean.
Mark Worsnop
Junior Developer
Junior Developer
 
Posts: 24
Joined: Wed Dec 01, 2010 12:34 am

Re: Database listview how to relate to the DB record

Postby Mark Worsnop » Sun Dec 05, 2010 9:04 pm

The other thing is I dont know where to call the DatabaseAdapter
Mark Worsnop
Junior Developer
Junior Developer
 
Posts: 24
Joined: Wed Dec 01, 2010 12:34 am

Top
Next

Return to Novice Tutorials

Who is online

Users browsing this forum: No registered users and 13 guests