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.
Related
I have a db with table "mytable" having 2 colums "id","sampletext"
I want to query distinct values of sampletext and feed to a Spinner using SimpleCursorAdapter.
here is what is tried
String[] cols=new String[]{"sampletext"};
int[] lbls=new lbls[]{android.R.id.text1};
mycursor=sdb.query(true,"mytable", cols,null,null,null,null,null,null);
sca=new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, mycursor, cols,lbls,0);
sca.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spn.setAdapter(sca);
When i run this i get error at line 4 : id does not exist.
when i changed first line to "id" the spinner got populated with id values.
But i need "sampletext", what am i doing wrong?
Appreciate any suggestions
what am i doing wrong
you didnt read documentation ...
there are two arrays of string with columns: first in used in query, second one in Adapter constructor(you used only one array for both)
first one tells sqlite which columns should be taken to Cursor, second tells Adapter which ones should be showed/mapped to Views in single row...
Next CursorAdapter needs Cursor with column named _id
So now it's pretty obvious that we should do smthin like this:
String[] queryCols=new String[]{"_id", "sampletext"};
String[] adapterCols=new String[]{"sampletext"};
int[] adapterRowViews=new int[]{android.R.id.text1};
mycursor=sdb.query(true,"mytable", queryCols,null,null,null,null,null,null);
sca=new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, mycursor, adapterCols, adapterRowViews,0);
sca.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spn.setAdapter(sca);
Here's an example with raw query. Please note the first ID column returned by the query should be labeled as _id .
MyDatabase.java:
public class MyDatabase extends SQLiteAssetHelper {
...
public Cursor getListNamesForDropDown() {
SQLiteDatabase db = getReadableDatabase();
String sql = "select ID _id, Name from MyTable order by Name ";
Cursor c = db.rawQuery(sql, null);
c.moveToFirst();
return c;
}
MyActivity.java:
#Override
public void onCreate(Bundle savedInstanceState) {
....
Cursor cursorTest = db.getListNamesForDropDown();
android.widget.SimpleCursorAdapter adapter = new android.widget.SimpleCursorAdapter(this,
android.R.layout.simple_spinner_item,
cursorTest,
new String[] {"Name"},
new int[] {android.R.id.text1}, 0);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerTest.setAdapter(adapter);
android.widget.SimpleCursorAdapter adapter = new android.widget.SimpleCursorAdapter(this,
android.R.layout.simple_spinner_item,
cursor,
new String[] { DBOpenHelper.ACCOUNT_BANK },
new int[] { android.R.id.text1 }, 0);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
I have a table called tbl_homework. There are 3 columns called "_id", "hw" and "hwdate".
Now I like to read out "hw" AND "hwdate". So I like it on the same line in this listview.
I have to say that it is working without crash or error. It just don't show the date...
Following picture will tell you what I mean:
Here are the code snippets to tell you how I tried this:
private Button.OnClickListener add_hw = new Button.OnClickListener(){
public void onClick(View arg0) {
mDbHelper.open_database_rw();
String txt_insert_hw = insert_hw.getText().toString();
if(txt_insert_hw.equals("")){
doMessage("Keine Eingabe!");
}else{
String date_picker_message= date_pick.getDayOfMonth() + "/" + (date_pick.getMonth()+1) + "/" + date_pick.getYear();
final String INSERT_HW = "INSERT INTO tbl_homework ('hw', 'hwdate') VALUES ('"+txt_insert_hw+"', '"+date_picker_message+"')";
db.execSQL(INSERT_HW);
insert_hw.setText("");
fillData();
}
}
};
private void fillData() {
// Get all of the notes from the database and create the item list
Cursor c = mDbHelper.fetchAllNotes();
startManagingCursor(c);
String[] from = new String[] { dbHelper.KEY_TITLE, dbHelper.KEY_DATE};
int[] to = new int[] {R.id.txt_notes_row};
// Now create an array adapter and set it to display using our row
SimpleCursorAdapter notes = new SimpleCursorAdapter(this, R.layout.notes_row, c, from, to);
setListAdapter(notes);
}
And in mDbHelper:
public Cursor fetchAllNotes() {
return db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_TITLE, KEY_DATE}, null, null, null, null, null);
}
Soulution of this problem: (Received from Jury)
String[] from = new String[] { dbHelper.KEY_TITLE, dbHelper.KEY_DATE};
int[] to = new int[] {R.id.txt_notes_row, R.id.txt_notes_row2};
I had to add a new TextView. dbHelper.KEY_TITLE AND dbHelper.KEY_DATE coudn't be handle by one TextView. So I had to add a new TextView to handle the second part of my String "from".
I think the problem is that you try to match two columns (from) to only one container (to) here:
String[] from = new String[] { dbHelper.KEY_TITLE, dbHelper.KEY_DATE};
int[] to = new int[] {R.id.txt_notes_row};
You should specify two fields in the list row where you store your values. I.e. your R.id.txt_notes_row should contain two widgets (for instance, R.id.txtview1 and R.id.txtview2) where you can store your values from db.
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/
I'm trying to populate a listview with products. I can do it, but I need them to have custom id's (the ones from the SQLite database). How can I do this? This is my code without the id implementation so far:
ArrayList<String> productNameList = new ArrayList<String>();
ArrayList<String> productIdList = new ArrayList<String>();
Cursor results = myDbHelper.getProducts();
ListView lv = (ListView) findViewById(R.id.productlist);
while (results.moveToNext()){
productNameList.add(results.getString(results.getColumnIndex("name")));
productIdList.add(results.getString(results.getColumnIndex("id")));
}
lv.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , productNameList));
You should use a SimpleCursorAdapter:
String[] columns = new String[] { "_id", "name" };
int[] to = new int[] { android.R.id.text1, android.R.id.text2 };
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, cursor, columns, to);
lv.setAdapter(mAdapter));
"to" and "columns" define a mapping:
"colums" is a list of the database column names you want the SimpleCursorAdapter to read. And "to" is a list of android ids specifying on which widget the values from the cursor are set.
In the latter code this means that the value of "_id" will be displayed in the textfield with the android id "android.R.id.text1" and the value of the column "name" will go into textfield "android.R.id.text2".
I have a database with 5 columns, 1 column which is a TEXT with the name of a drawable that is /res/drawable folder.
private void fillData() {
mCursor = db2.getAllAchievements();
startManagingCursor(mCursor);
String[] from = new String[]{achHelper.ROW_NAME, achHelper.ROW_DESCRIPTION, achHelper.ROW_POINTS, achHelper.ROW_TROPHY};
int[] to = new int[]{R.id.achTitle, R.id.achDescription, R.id.achPoints, R.id.trophy};
SimpleCursorAdapter classes =
new SimpleCursorAdapter(this, R.layout.ach_row, mCursor, from, to);
setListAdapter(classes);
}
R.id.trophy is a ImageView, how can I set the background image based on the data that is being pulled from achHelper.ROW_TROPHY?
the simpleCursorAdapter need Strings, so your StringArray "from" must get String objects from the column achHelper.ROW_TROPHY when you setup your database it has to look like this:
private static final String TABLE_CREATE = "CREATE TABLE " here your other colums
+ ROW_TROPHY + " TEXT NOT NULL);";
db.execSQL(TABLE_CREATE);
So when you make your entry into your Database you have to convert the ID of your TropyImage (whitch is Integer) R.drawable.yourTropyImage to a string:
ContentValues cv = new ContentValues();
cv.put( your other columns, your other input);
cv.put(ROW_TROPHY, Integer.toString(R.drawable.yourTrophyImage));
return db.insert(DATABASE_TABLE, null, cv);
Your String[] from, int[] to and simpleCursorAdapter seem to be correct. You just must have the right DataType and ID in the ROW_TROPY column.