In my SQL database table there are colums _id, int dayofweek, String text ...
I now, do a SQL query on that table to get a cursor to the results.
The results then are shown in a listView:
private void showBlocks()
{
Cursor blocks = ttDB.getBlocks();
startManagingCursor(blocks);
int[] key = new int []{
android.R.id.text1,
android.R.id.text2
};
SimpleCursorAdapter blockAdapter = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_2,
blocks,
new String[] {
"day",
"text"
},
key);
lv1.setAdapter(blockAdapter);
}
How (and where) can I now replace the integer values of dayofweek by the corresponding strings? I thought about joining two tables while querying but then it will not be multilingual any more.
You can try using a ViewBinder via setViewBinder() on your SimpleCursorAdapter.
Or, extend SimpleCursorAdapter, override bindView() and do it yourself.
you can not directly replace values .you have to store first it in list and than you can replace it with ur desired fromat
Related
I am new in java and need help to make my Music Player in android. I need best practice to have a playlist like a queue to handle easily for a simple function like next track, last song of album or shuffle play.
I mean is there any concept in android to handle these stuff easier?
I think you are looking for Cursor. It is an Interface which returns the collection of your query data.
The following methods are available in the Cursor interface which iterate through the Cursor, setting the Cursor pointer to the desired position:
moveToFirst()
moveToLast()
moveToNext()
moveToPrevious()
moveToPosition(position)
For more info about cursor methods visit this but to create a cursor from list of object you can use MatrixCursor like bellow:
String[] columns = new String[] { "_id", "item", "description" };
MatrixCursor matrixCursor = new MatrixCursor(columns );
for (JsonElement mus : musics) {
matrixCursor.addRow(new Object[] { 1, "Item A", "...." });
}
You can find more data from here.
I have a SQLite database that contains multiple tables. For each table, I am trying to represent all the data in an ExpandableListView using a custom CursorTreeAdapter. As far as I understand, the method getChildrenCursor returns a cursor that points to the data I needed to populate my child views. However, I do not have a concrete idea on how to retrieve the children cursor using the groupCursor parameter.
#Override
protected Cursor getChildrenCursor(Cursor groupCursor) {
String[] projection = { "columnNeeded" };
return context.getContentResolver()
.query(CONTENT_URI, projection, null, null, null);
}
the above method will return a cursor that returns all rows containing the column I need. Is this the right way to do this?
In the "columnNeeded" column for each row of the table, it contains a String representation of a jsonArray. I was trying to store an arrayList into each row of the table using JSONArray. Therefore, I am trying to retrieve this arrayList and populate the child views with this arrayList like so:
#Override
protected void bindChildView(View view, Context context, Cursor cursor, boolean isLastChild) {
TextView name = (TextView) view.findViewById(R.id.summary_child_name);
TextView bill = (TextView) view.findViewById(R.id.summary_child_bill);
String arrayListString = cursor
.getString(cursor.getColumnIndex("columnNeeded"));
JSONObject json = new JSONObject();
try {
json = new JSONObject(arrayListString);
} catch (JSONException e) {
Log.e(LOG_TAG, "Unable to retrieve list of items");
}
JSONArray jsonArray = json.optJSONArray(ReceiptContract.JSONARRAY_NAME);
// retrieveArrayList iterates through jsonArray and adds it to items
items = retrieveArrayList(jsonArray);
name.setText(What do I put here?);
bill.setText(What do I put here?);
}
As you can see I have managed to retrieve the entire array list as an ArrayList type object. However, I am stuck on displaying the array list in the child views. Any idea on how I can go about doing this?
Use HashMap to store your data as key value and populate your data into your ExpandableListView using BaseExpandableListAdapter
I'm wanting to compare the strings in an array list taken from my database and join them together..
Here is the code which collects data from my database..
public List<String> getData2List() {
String[] columns = new String[]{ KEY_ROWID, KEY_DATE, KEY_NAME, KEY_PRICE};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, "1", null, null, null, null);
List<String> results = new ArrayList<String>();
int iCM = c.getColumnIndex(KEY_DATE);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
results.add(c.getString(iCM));
}
return results;
}
and here is the code to place them in the list..
Database info = new Database(this);
info.open();
List<String> dates = info.getData2List();
lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, dates));
info.close();
This all works fine but if there are more than one entry which is the same I end up with a list of the same thing (if this makes sense!?).
Example:
if the list came out like {"01/01/13", "02/01/13", "01/01/13", "03/02/13", "01/01/13"}
I'm trying to make the out come like {"01/01/13", "02/01/13", "03/02/13"}
so that all entry of the same value have been compiled into one.
Any help or ideas is much appreciated.
Just use an Set instead of a List.
An HashSet will provide you unique strings, a List instead can contain same occurrence.
Why don't you just use HashSet<String> ?
Example:
List<String> dates = info.getData2List();
Set<String> uniqueDates = new HashSet<String>(dates);
You can use HashSet instead of ArrayList.
because in your case you will have following advantages
joining two set will be more easier useing addAll method
There is no chance to have duplicate values
You need a Set collection class, basically what "Set" does is, storing only unique values, and if you try to set a new value that already exist in the collection it will just ignore, make sure you are overriding equals, and hashCode method as well in case you are trying to store your own object, look at the documentation for more info about how it works..
http://docs.oracle.com/javase/6/docs/api/java/util/Set.html
Regards!
I am new to android and after going through many tutorials I still can't get things.
I have created a database and is now reading this database.
This database and 3 columns All three string type.
Now I want to show this database using ListView.I have this ListView
created with id "listDatabaseItems" in R.layout.viewDatabase
Currently my code is:
Cursor c = sqliteDatabase.query(MY_DATABASE_TABLE, null, null, null, null, null, null);
int firstNameColumn = c.getColumnIndex("name_column");
int protectedColumn = c.getColumnIndex("protected_id_column");
ArrayList<String> results = new ArrayList<String>();
int i = 0;
c.moveToFirst();
do {
i++;
String firstName = c.getString(firstNameColumn);
String protectedID = c.getString(protectedColumn);
results.add(firstName + protectedID); // NEED TO add here
} while (c.moveToNext());
sqliteDatabase.close();
Please tell me what changes I do and how can I show my database in ListView.
Best Regards.
Make a Adapter add your ListArray values to it, and then setAdapter to your listview simple,
After your code, add just two lines,
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, results);
mListView.setAdapter(adapter);
Also, your question sounds basic for android So just look at these links..
SimpleCursorAdapters and ListViews
Android SQLite Database and ContentProvider - Tutorial
Filling the Layout with Data
Since you're using a Cursor in the first place, I'd actually go with a SimpleCursorAdapter. A CursorAdapter allows you to avoid loading the whole data set into memory, making initial load times faster and avoiding huge allocations with large data sets.
To expand on the basic setup in this post (SimpleCursorAdapters and ListViews), You'll also want to set a view binder to customize the way data is bound to the view, ie. concatenate your two strings.
Something like this:
SimpleCursorAdapter.ViewBinder binder = new SimpleCursorAdapter.ViewBinder() {
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
//you're only using one view, so we can ignore columnIndex
TextView text = view.findViewById(R.id.list_item_text);
//the cursor is already in position for this list item
int firstNameColumn = c.getColumnIndex("name_column");
int protectedColumn = c.getColumnIndex("protected_id_column");
String firstName = c.getString(firstNameColumn);
String protectedID = c.getString(protectedColumn);
text.setText(firstName+protectedID);
return true; //we have handled binding the data
}
};
Then when you set up your adapter, you pass it a layout that can be used for each item. The layout should contain a TextView to hold the one text item you want to show. You may be able to use android.R.layout.simple_list_item_1 for this as user370305 suggested, but I'm not sure what the id of its TextView is -- it might be android.R.id.text1.
SimpleCursorAdapter adapter = new SimpleCursorAdapter(
context, //can be your Activity
R.layout.list_item, //xml layout containing textview with id 'list_item_text'
c, //the cursor
new String[] {"name_column"}, //the column to read (we'll do more in the binder)
new int[] {R.id.list_item_text}, //the view to hold the data
0 //no flags
);
adapter.setViewBinder(binder);
Add it to your ListView the same way:
ListView listView = //your ListView reference
listView.setAdapter(adapter);
//or in a ListActivity:
setListAdapter(adapter);
The SQLite database table I'm using is subjected to adding columns whenever I need to. I don't want to hard-code the columns at the risk of updating the database and forgetting to update the hard-coded values. How could I return all the names of the columns in a table? (Preferably in a String[])
Best if you use a SQLiteDatabase instance and use query method
SQLiteDatabase mDataBase;
(some code here...)
mDataBase = getReadableDatabase();
Cursor dbCursor = mDataBase.query(TABLE_NAME, null, null, null, null, null, null);
String[] columnNames = dbCursor.getColumnNames();
columnNames should have the column names
You may not need a list of column names.
It seems that you want the list of column names so that you can build up a comma-separated list of columns to select. If this is the case, then where you would normally place the list of column names in your SELECT query, you could instead use an asterisk:
SELECT * FROM table WHERE ...
Or if the table is aliased:
SELECT t.* FROM table AS t ...
An asterisk means "all columns".
EDIT: If you really do want a list of column names of a table, then you can use the following code:
Cursor c = db.rawQuery("SELECT * FROM table WHERE 0", null);
try {
String[] columnNames = c.columnNames();
} finally {
c.close();
}
Note that you must not modify the returned array of Strings in any way: https://code.google.com/p/android/issues/detail?id=3731
It is also interesting to note that the query method accept null as input for the column parameters. If you input null, all the columns will be returned.
db.query("Table_name",null,COLUMN_ID + "=" + id,null,null,null,null);
Will return all columns of the line that has the specified id.
You can see the method definition here.