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.
Related
In Android Studio I'm trying to select specific amount of rows from sqlite database where one row is predetermined based on given id and the rest are picked randomly. The query should be saved in Cursor because I would display selected rows in ListView, which can take info from Cursor simply through SimpleCursorAdapter.
The initial database is created as such:
public void onCreate(SQLiteDatabase database) {
database.execSQL("CREATE TABLE DICTIONARY(_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"english TEXT, " +
"estonian TEXT);");
addWordPair(database, "myriad", "tohutu hulk");
addWordPair(database, "egregious", "jõletu");
addWordPair(database, "erroneous", "väär");
addWordPair(database, "salient", "esile tõusev");
addWordPair(database, "galvanize", "laengut andma");
addWordPair(database, "tenuous", "hõre");
addWordPair(database, "caustic", "söövitav");
}
public void addWordPair(SQLiteDatabase database, String english, String estonian) {
ContentValues wordPair= new ContentValues();
wordPair.put("english", english);
wordPair.put("estonian", estonian);
database.insert("DICTIONARY", null, wordPair);
}
The selected rows would be display in ListView using Cursor:
SimpleCursorAdapter listAdapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
cursor,
selectedLanguage,
new int[] {android.R.id.text1},
0);
ListView listofWordsListView = (ListView) findViewById(R.id.wordsListView);
listofWordsListView.setAdapter(listAdapter);
I get five random english words using:
Cursor cursor = database.query("DICTIONARY Order By RANDOM() LIMIT 5",
new String[] {"english"}, null, null, null,null, null);
I get a single english word with specific id using:
Cursor cursor = database.query("DICTIONARY",
new String[] {"english"},
"_id = ?",
new String[] {Integer.toString(id)},
null, null, null);
Now I need to store both, the specific row and and random rows (specific row preferably in between random rows) in cursor in order to use it in CursorAdapter.
You can use a MergeCursor e.g. :-
Cursor cursor1 = database.query("DICTIONARY Order By RANDOM() LIMIT 5",
new String[] {"english"}, null, null, null,null, null);
Cursor cursor2 = database.query("DICTIONARY",
new String[] {"english"},
"_id = ?",
new String[] {Integer.toString(id)},
null, null, null);
MergeCursor merged = new MergeCursor(new Cursor[]{cursor1,cursor2});
You then treat/handle the MergeCursor (merged in this example) like a standard cursor.
MergeCursor
You can use MergeCursor to join the results of multiple Cursors into one.
In SQL, you can combine queries with a compound query:
SELECT english FROM Dictionary WHERE _id = ?
UNION ALL
SELECT * FROM (SELECT english FROM Dictionary ORDER BY random() LIMIT 5);
(Without the subquery, the ORDER BY/LIMIT would apply also to the first part.)
To put the first row into a random position, reorder again:
SELECT english FROM Dictionary WHERE _id = ?
UNION ALL
SELECT * FROM (SELECT english FROM Dictionary ORDER BY random() LIMIT 5)
ORDER BY random();
To execute a raw SQL query, use rawQuery():
Cursor cursor = database.rawQuery("SELECT .....", new String[]{ ... });
Am using db query to sum the column values by using group by clause. I can get the total amount but i couldn't display the values in simplecursoradapter. Please help me to display the total values. I have posted my code below.
String[] columns = new String[] { KEY_ID, KEY_CATEGORY,"sum("+KEY_AMOUNT+")as" + KEY_AMOUNT,
KEY_COMMENT };
Cursor cursor = db.query(TABLENAME2, columns, null, null, null, null,
null);
return cursor;
To display the values in Listview using Simplecursoradapter
String[] from = new String[] { Dailydialog.KEY_CATEGORY,
Dailydialog.KEY_AMOUNT,Dailydialog.KEY_COMMENT};
int[] to = new int[] { R.id.id2, R.id.id3,R.id.id4};
cursorAdapter1 = new SimpleCursorAdapter(this, R.layout.dailydialogall, cursor1,
from, to);
listview_dialog.setAdapter(cursorAdapter1);
Total values are not listed in Listview.
Instead of "sum("+KEY_AMOUNT+")as" + KEY_AMOUNT use " sum("+KEY_AMOUNT+") as " + KEY_AMOUNT. Notice the spaces? Its always a good idea to print your query in log. Another thing is that you need to specify group by clause as well for sum function otherwise only one row will be returned with total sum of amount of all the rows.
I am entering some values in to my SQLlite database and then retrieving them in a gridview.I am getting a Error "column'_id'" does not exist.but I have not used any _id named column in the database. How can I make it work?? I think theres some problem with SimpleCursor Adapter .
GridView gv = (GridView)findViewById(R.id.gridView1);
try
{
db1 = openOrCreateDatabase("record.db", Context.MODE_PRIVATE,null);
db1.execSQL("CREATE TABLE IF NOT EXISTS stu(ID INTEGER primary Key,NAME VARCHAR foriegn key,age VARCHAR);");
db1.execSQL("INSERT INTO stu VALUES (1,'mona','123');");
Cursor c = db1.rawQuery("SELECT * FROM stu", null);
if(c!= null){
if (c.moveToFirst()) {
do {
String[] cols = new String[]{c.getString(c.getColumnIndex("ID")),c.getString(c.getColumnIndex("NAME"))};
int[] views = new int[] {R.id.textView1,R.id.textView2};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
c, cols, views);
gv.setAdapter(adapter);
}while(c.moveToNext());}
}} catch(Exception e){
Toast.makeText(getBaseContext(),"errord"+ e.getMessage(), Toast.LENGTH_LONG).show();
}
}
The documentation for CursorAdapter (which SimpleCursorAdapter extends) states:
The Cursor must include a column named "_id" or this class will not work.
How can I edit a particular record in a SQLite table given, Database Name, Table Name, int _id ,Column Name and Desired value of record?
EDIT:
My solution was database.update(DataBaseHelper.VFS_DATABASE_TABLE, values, "_id=?", new String[] {id+""});
public int deleteCpShadowEntryById (int id) {
int delRows = mDb.delete(<your_table_name>, "_id" + "=?", new String[] {String.valueOf(id)});
return delRows;
}
But I guess you do not want to delete. You want to update your value. So in this case you should at first select your row, fill the values of this row into a new ContentValues, replace you old value with new and update the row.
Edit: Maybe try this:
ContentValues args = new ContentValues();
args.put(<your_columnName>, newValue);
db.update(<your_table_name>, args, "_id" + "=?", new String[] {String.valueOf(id)});
Should be a simple bit of SQL:
DELETE FROM <table name> WHERE <column name> = <desired value>
SQLiteDatabase has a delete method :
public int delete (String table, String whereClause, String[] whereArgs)
If you have id of the particular record the code would be something like :
String whereArgs[] = new String { id };
db.delete(TABLE_NAME, "_id = ?", whereArgs);
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.