I'm new in android. I'm facing a problem creating a listview using data from sqlite database.
I found this code below to create a listview from contact data
public class Test extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get a cursor with all people
Cursor c = getContentResolver().query(Contacts.CONTENT_URI,CONTACT_PROJECTION, null, null, null);
startManagingCursor(c);
ListAdapter adapter = new SimpleCursorAdapter(this,
// Use a template that displays a text view
android.R.layout.simple_list_item_1,
// Give the cursor to the list adatper
c,
// Map the NAME column in the people database to...
new String[] {Contacts.DISPLAY_NAME},
// The "text1" view defined in the XML template
new int[] {android.R.id.text1});
setListAdapter(adapter);
}
private static final String[] CONTACT_PROJECTION = new String[] {
Contacts._ID,
Contacts.DISPLAY_NAME
};
}
Now I use this code to pull data from database
SQLiteDatabase myDB= null;
String TableName = "myTable";
myDB = this.openOrCreateDatabase("DatabaseName", MODE_PRIVATE, null);
// Get a cursor with all people
Cursor c = myDB.rawQuery("SELECT * FROM " + TableName , null);
Now How can I combine these two codes so I can show data pulled from a database in this list.
Thanks in advance.
If you want to list the data from both sources (contact and DB), I think only option you have is construct an array with return values from both sources.
List finalList = new ArrayList();
Cursor c = getContentResolver().query(Contacts.CONTENT_URI,CONTACT_PROJECTION, null, null, null);
startManagingCursor(c);
c.moveToFirst();
Iterate this cursor and populate the String value to finalList
SQLiteDatabase myDB= null;
String TableName = "myTable";
myDB = this.openOrCreateDatabase("DatabaseName", MODE_PRIVATE, null);
// Get a cursor with all people
Cursor c2 = myDB.rawQuery("SELECT * FROM " + TableName , null);
startManagingCursor(c2);
c2.moveToFirst();
Iterate c2 cursor and add values to finalList.
Convert finalList to array by Iterating finalList
String[] ipArray = new String[finalList.size()];
loop through list and populate the values to ipArray.
I don't have IDE handy, so I have typed the flow.
If suppose you already have data in your cursor, you can follow code in the following tutorial
http://chetanandroidarora.wordpress.com/2011/12/18/customcursoradapter/
Related
I am filling my ListView with data which I am getting from the database I created. I want to get the name of the item in ListView which is being long clicked.
I have tried using following method:
- parent.getItemAtPosition(position).toString();
- myListView.getItemAtPosition(position).toString();
- myListView.getSeletedItem(position).toString();
These three statements work well but as I am filling up the LisView by getting data from my database so I am getting the following value returned:
09-20 13:01:22.370: I/System.out(5351): android.database.sqlite.SQLiteCursor#426925b0
whereas the Item's name, which I am clicking, is 'Home'..
Please help me. How can I convert android.database.sqlite.SQLiteCursor#426925b0 into Home?
MY ADAPTER:
mCursor = mDB.fetchData();
String[] columns = new String[] { AreaDatabase.KEY_AREA };
int[] to = new int[] { R.id.tvArea };
mAdapter = new SimpleCursorAdapter(this, R.layout.lvarea, mCursor,
columns, to);
lvArea.setAdapter(mAdapter);
fetchData() function:
public Cursor fetchAreaData() {
Cursor mCursor = ourDatabase.query(AREA_TABLE_NAME, new String[] {
KEY_ROWID, KEY_AREA }, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
Cursor has method getString(int columnIndex). You can use that to get String value from Cursor from specified column index.
> Cursor currentCur = myListView.getItemAtPosition(position);
> String name = currentCur.getString(1); //It will return KEY_AREA (column index 1) value from Cursor
do like this :
parent.getItemAtPosition(position).toString();
I have a ListView in my Class which will display a list of every category in the database table. In that list view I have three TextViews, ROWID CategoryName and CategoryCount respectively as so:
private void populateCategoryList() {
DatabaseHandler db = new DatabaseHandler(this);
TextView tvCategoryItem = (TextView) findViewById(R.id.tvCategoryItem);
TextView tvCatID = (TextView) findViewById(R.id.tvCatID);
TextView tvCatCount = (TextView) findViewById(R.id.tvCatCount);
Cursor cursor = db.getCategories();
// Allow activity to manage lifetime of the cursor.
// DEPRECATED! Runs on the UI thread, OK for small/short queries.
// startManagingCursor(cursor); //TODO Turned off because on back from contact details made a closed cursor error
// Setup mapping from cursor to view fields:
String[] fromFieldNames = new String[] { db.KEY_ROWID, db.KEY_CATEGORY };
int[] toViewIDs = new int[] { R.id.tvCatID, R.id.tvCategoryItem };
SimpleCursorAdapter myCursorAdapter = new SimpleCursorAdapter(this, // Context
R.layout.item_categorylist, // Row layout template
cursor, // cursor (set of DB records to map)
fromFieldNames, // DB Column names
toViewIDs // View IDs to put information in
);
/****** COUNT CODE ******/
// tvCatCount = (db.countCategory(category));
// Set the adapter for the list view
lvCategories = (ListView) findViewById(R.id.lvCategories);
lvCategories.setAdapter(myCursorAdapter);
db.close();
You can see in the toFields above that I do not yet have a field set for the count. I will use tvCatCount for this. The question is, how and where do I insert the count code. In this case the count? I think that the countCategory will need to be a for loop where it should get the id of the current category entry for that row, call the db.countCategory and tehn set the value in the TextView to the returned result?
Here is the db.countCategory code:
public int countCategory(category){
SQLiteDatabase db = this.getWritableDatabase();
String[] categoryColumns = new String[] { KEY_ROWID, KEY_CATEGORY };
Cursor c = db.query(CATEGORY_TABLE, null, null, null, KEY_CATEGORY + "=" + category, null, null);
int result = c.getCount();
c.close();
Log.i("DATABASE", "Category Count for id " + id + "is " + result);
return result;
}
which should count every entry in the table equal to the value of "id". This code already works elsewhere, so I am not too worried about it, but to count for each row in a listview, that is a different animal.
To show the count of expenses for each category, you would need a table with these columns:
_id | CategoryName | Count
To compute this, you have to join the categories table to the expenses table, and use GROUP BY to get one output row for each distinct category value:
SELECT Category.rowid AS _id,
Category.Name,
COUNT(*) AS NumberOfExpenses
FROM Category
JOIN Expenses ON Category.rowid = Expenses.CategoryID
GROUP BY Category.rowid
02-23 20:16:17.499: E/AndroidRuntime(25817): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.makkosarka/com.example.makkosarka.Table.Table}:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.makkosarka/
com.example.makkosarka.Table.Liga1}: java.lang.IllegalArgumentException: column '_id' does not exist
and here are the methods that are trying to select records from this table and than display
in listview
private void populateListFromDB(){
Cursor cursor = myDB.getAllRows("1");
startManagingCursor(cursor);
String[] columnFromTable = new String[]
{DBadapter.KEY_HOSTID, DBadapter.GUESTID, DBadapter.KEY_HSCORE , DBadapter.KEY_GSCORE };
int[] toLayoutFild = new int[] {R.id.txtview_name, R.id.txtview_gameno, R.id.txtview_won, R.id.txtview_lost, };
SimpleCursorAdapter myCursorAdapter = new SimpleCursorAdapter(this, R.layout.rowlayout,
cursor, columnFromTable, toLayoutFild);
ListView mylistview = (ListView) findViewById(R.id.listview_table);
mylistview.setAdapter(myCursorAdapter);
}
This is in the Adapter class and i'm not even selecting the "_id"(KEY_ROWID) column
public static final String[] ALL_COLUMNS = new String[] {KEY_HOSTID, KEY_GUESTID,
KEY_HSCORE, KEY_GSCORE};
public Cursor getAllRows(String league) {
Cursor c = db.query(true, DUELS_TABLE, ALL_COLUMNS,
null, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
What does that error mean is it possible that the table is not created at all?
I have two tables and I`m using the same method to select records for the other one it works perfectly but for this it shows this error listed on the top of this question
This is in the Adapter class and i'm not even selecting the "_id"(KEY_ROWID) column
CursorAdapter and its subclasses require that the Cursor have a column named _id. Use your own if you have one, or else switch to rawQuery() so you can include ROWID AS _id in your list of columns to return.
I am inserting data into SQLite database using ArrayList>. I want to retrieve only unique values into a listview using simple adapter. I am using the same key to insert the values. how can i get only different values into the listview?
Here's my code..
Databasehandler.java
public void insertAnimal(HashMap<String, String> queryValues) {
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("animalName", queryValues.get("animalName"));
database.insert("animals", null, values);
database.close();
}
public ArrayList<HashMap<String, String>> getAllAnimals() {
ArrayList<HashMap<String, String>> wordList;
wordList = new ArrayList<HashMap<String, String>>();
String selectQuery = "SELECT * FROM animals";
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
map.put("animalId", cursor.getString(0));
map.put("animalName", cursor.getString(1));
wordList.add(map);
} while (cursor.moveToNext());
}
return wordList;
}
And here's my MainActivity.java
DBController controller = new DBController(this);
ArrayList<HashMap<String, String>> animalList = controller.getAllAnimals();
if(animalList.size()!=0) {
ListView lv = getListView();
ListAdapter adapter = new SimpleAdapter( MainActivity.this,animalList, R.layout.view_animal_entry, new String[] { "animalId","animalName"}, new int[] {R.id.animalId, R.id.animalName});
setListAdapter(adapter);
Use the DISTINCT keyword to eliminate duplicate rows from a results set:
SELECT DISTINCT * FROM animals
Note that this will only remove rows that are duplicate in terms of all columns. So if you have the same animal name under different ids, you'll still get both rows. For example if your table contains:
animalId animalName
1 Lion
1 Lion
2 Lion
3 Tiger
3 Tiger
The results would be:
animalId animalName
1 Lion
2 Lion
3 Tiger
An alternative would be to group by the animal name:
SELECT * FROM animals
GROUP BY animalName
The result would (most likely) be:
animalId animalName
2 Lion
3 Tiger
Note that here, you now have unique names. However in the case of a name that was grouped (Lion in this example) the animalId you get for it will be from one of the rows from the set that was grouped. The exact one you get is not defined.
If you want to get the records with different animalIDs then you would do something like this
public Cursor getUniqueValues() {
Cursor cursor = database.query(SQLiteHelper.TABLE_NAME,
allColumns, SQLiteHelper.ANIMAL_ID + " like \'Whatever\'", null, null, null, null ,null);
return cursor;
}
I wanna create an array of cities that are stored in the database
Cities Table
CREATE TABLE cities (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT);
Querying for City List
// City List
public Cursor cityList() throws SQLException {
return db.query(TABLE_CITIES, new String[] {ID, KEY_NAME}, null, null, null, null, null, null);
}
Trying to Get the content into the Array
Cursor cities = db.cityList();
startManagingCursor(cities);
String[] city_list = new String[] { DBAdapter.KEY_NAME };
Spinner cityList = (Spinner)this.findViewById(R.id.citySpiner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, city_list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
cityList.setAdapter(adapter);
Am not able to populate the Spinner.. with the database content.
Try SimpleCursorAdapter
String[] from = new String[] { DBAdapter.KEY_NAME };
int[] to = new int[] {android.R.id.text1};
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(context, android.R.layout.simple_spinner_dropdown_item , cursor, from, to);
cityList.setAdapter(cursorAdapter);
Edit:
from means the column(s) from the Cursor which will be used to display as text array in Spinner.
to means the id(s) of the view which will hold the value of that column.
It is very interesting that the view at index N will hold the text from column at N.