Populating a list view from SQLite Database - android

I'm new to android. What i'm trying to do is to populate a listview from my sqlite database.I know how to do it using arrays. Can somebody help me doing this? I know there is a away to adapt the following code and using it for populating the listview using SQLite but i don't know how to do it.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_item);
final ListView lt = (ListView)findViewById(R.id.ListView01);
List<String> w= new ArrayList<String>();
ArrayAdapter<String> aa;
w.add("waka");
w.add("weka");
w.add("woka");
aa = new ArrayAdapter<String>(this, R.layout.listW, w);
lt.setAdapter(aa);
lt.setTextFilterEnabled(true);
lt.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
final String aux= (String) lt.getItemAtPosition(position);
Intent myIntent = new Intent(infoList.this, tabList.class);
startActivity(myIntent);
}});
}
Thanks

The best way to poputaling a ListView with data is using Content Providers: http://developer.android.com/guide/topics/providers/content-providers.html
Using content providers will you safe headaches regarding open/close operation for the database.

You can use SimpleCursorAdapter.
Image you have a list view (named 'list_item') item with two fields having ids txtOne and txtTwo respectively. Also, you are having a database table with tow fields - field1 and field2.
When you sgolud use the following adapter call.
SimpleCursorAdapter adapter = new SimpleCursorAdapter(
ctx,
R.layout.list_item,
getContentResolver().query(....), // getting cursor for database query here.
new String[] { "field1", "field2" },
new int[] { R.id.txtOne, R.id.txtTwo }
);
This adapter will map a text from field1 to txtOne and from field2 to txtTwo.

Related

Retrieve values from database and launch a new activity when listview item is clicked

I created a listview using an adapter. The list view contains elements retrieved from a SQLite database using a distinct query.
When the listview item is clicked, it should retrieve all items which have that value used to do the distinct query.
My query looks like this:
#Override
public List<Registro> distinctByCol3(){
List aux = new ArrayList();
Cursor cursor = db.query(true,Registro.TABLE_NAME,new String[]{
BaseColumns._ID,
RegistroColumns.Col1,
RegistroColumns.Col2,
RegistroColumns.Col3,
},null,null,RegistroColumnas.Col3,null,null,null);
if (cursor.moveToFirst())
do {
Registro registro = this.parseCursorToR(cursor);
if (registro != null)
aux.add(registro);
}
while (cursor.moveToNext()) ;
if(!cursor.isClosed()){
cursor.close();
}
return aux;
}
The java class:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lista_registros);
final ListView listView = (ListView) findViewById(R.id.lvRegistros);
DataManager servicio = new DataManagerImpl(this);
List<Registro> listRM = service.getRegistroDistinctedByCol3();
final ArrayAdapter<Registro> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listRM);
listView.setAdapter(adapter);
After click in the element, I need to launch a new activity and show all the elements whit COL3, which is the value I used in my query.
How can I achieved my goal?
If some clarification is needed, let me know. Thanks.

How could I change this hardcoded data to data from my database?

I would like to change it by getting the data from the database .
public void initList(){
product = new String[]{"apple","apricot","banana","orange","nuts","pears","pineapple","watermelon"};
listProducts = new ArrayList<>(Arrays.asList(product));
adapter = new ArrayAdapter<String>(this, R.layout.list_item,R.id.txtitem, listProducts);
listView.setAdapter(adapter);
}
For lists that come from the database, you should use a CursorAdapter
public void initList() {
String[] from = new String[] { productColName };
int[] to = new int[] { R.id.txtitem };
Cursor cursor = db.query(.....);
CursorAdapter adapter = new SimpleCursorAdapter(context, R.layout.list_item, cursor, from, to, 0);
listView.setAdapter(adapter);
}
This is an easy way to handle database data for a list item with all TextViews. If you have more complex data, such as for images etc. you should create a CursorAdapter subclass and override newView() and bindView().
You can use SQLite db, which is commonly used in android apps. You can insert and retrieve the data using SQLite queries.
For your example: you can create a table consisting the names of the fruits.
You can query your database to get all the fruits and populate the list (by adding the retrieved results in to the list) and use it as you are using it now to inflate the listView.
You can use the following tutorial to know about how to create a table, insert/update an entry and retrieve data from the table.
SQLite setup and sample queries

Android List Adapter Sort by date

I have a program that retrieves data from a database and displays it in a list adapter, But i want to sort the data by the planned date in Ascending order. Can anyone help
ArrayList<HashMap<String, String>> TimesheetList = controller.getAllworkinstructions();
if(TimesheetList.size()!=0) {
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
Id = (TextView) view.findViewById(R.id.Id);
String valId = Id.getText().toString();
Intent objIndent = new Intent(getApplicationContext(),ViewCuttingtask.class);
objIndent.putExtra("Id", valId);
startActivity(objIndent);
}
});
SimpleAdapter adapter = new SimpleAdapter(Menu.this,TimesheetList, R.layout.list,
new String[] { "Id","weekcomm","jobid","taskid","planneddate","name","Priority"},
new int{R.id.Id,R.id.weekcomm,R.id.jobid,R.id.taskid,R.id.planneddate,R.id.name,R.id.priority});
setListAdapter(adapter);
}
This has nothing to do with adapters.
You should sort your collection depending on your needs then pass it to your adapter (or notify it if you already passed it to a ListView, for instance).
By sort, I mean:
database query time sorting
using Collection.sort(yourCollection, aComparator)
I assume one of these Strings refers to date ArrayList<HashMap<String, String>> TimesheetList Just sort TimesheetList by date and give sorted list to array adapter

Add a "Please Select" option to a Spinner in Android

I have a Spinner which is filled from a query using a SimpleCursorAdapter, this works fine... but now I need to put an option "Please Select" before all the items retrieved from the query, just for usability issues... but I'm not quite sure of how to do so... HELP please...
Here is my code...
private Spinner comboForm;
...
comboForm = (Spinner) findViewById(R.id.comboFormularios);
...
mDbH.abrir();
final Cursor cu = mDbH.consultaFormularios(idU);
if(cu.moveToFirst() == false){
cu.close();
mDbH.cerrar();
}else{
SimpleCursorAdapter adapter2 = new SimpleCursorAdapter(getApplicationContext(),R.layout.spinner,cu,new String[] {"nombre"},new int[] {R.id.textoCombo});
adapter2.setDropDownViewResource(R.layout.simple_spinner_dropdown_item);
comboForm.setAdapter(adapter2);
}
mDbH.cerrar();
...
comboForm.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parentView, View selectedItemView,int position, long id) {
idF = (int) id;
obtenerDatosRutas(idU,idF);
tabla.removeAllViews();
llenarTabla();
}
public void onNothingSelected(AdapterView<?> arg0) {}
});
Where mDbH is an instance of the class I'm using to manipulate the Database... as you can see the Spinner is filled up from Cursor resulting of the query consultaFormularios(idU)
When you create your cursor, one possible solution would be to use a SQL UNION and construct second SELECT that simply contains the label you need (adding hard-coded dummy fields for ordering).
Alternatively, and this is most likely the simplest solution. Instead of using a cursor adapter, use an array adapter and start by populating the array with your default value you want, then stick in all the items from your cursor. Something like,
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("Please select");
final Cursor cu = mDbH.consultaFormularios(idU);
while(cu.moveToNext()) {
arrayList.add(cu.getString(0)); // assuming you want a
//string from the first column
}
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, arrayList);
comboForm.setAdapter(spinnerArrayAdapter);

How can I reset the SQLite query for my Listview after it has been created?

I have a ListView which is populated by a SQLite query in OnCreate using the following code which then sets up an OnItemClickListener.
ListView menuList = (ListView) findViewById(R.id.ListView_Menu);
String sql = "SELECT EXHIBITORS, ('Stand No. ' || STANDNO) AS STANDNO, _ID FROM EXHIBITOR ORDER BY EXHIBITORS";
cursor = myDbHelper.getReadableDatabase().rawQuery(sql, null);
startManagingCursor(cursor);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.menu_item, cursor, FROM, TO);
menuList.setAdapter(adapter);
menuList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View itemClicked, int position, long id) {
However, I want to be able to filter the ListView and then amend the query so that the user can reduce the size of the ListView by say requesting all Exhibitors that start with the letter 'A'. How can I do this, I assume by using the above code again but how do I this and still keep the OnItemClickListener working?
CursorAdapter.changeCursor() will allow you to replace your query with one that filters the Exhibitor names.

Categories

Resources