I have serveral objects in my DB with three Strings attributes. One of the shows a date information, eg. 1.4.2016, 20.10.2017. I list these objects in a ListView, but before I want to sort them by their dates.
//
//Show all Data on ListView
//
private void displayListView() {
Cursor cursor = datasource.fetchAllData();
// The desired columns to be bound
String[] columns = {
DatabaseHelper.COLUMN_TITLE,
DatabaseHelper.COLUMN_DESCRIPTION,
DatabaseHelper.COLUMN_DEADLINE,
};
// the XML defined views which the data will be bound to
int[] to = new int[] {
R.id.processobject_title,
R.id.processobject_description,
R.id.processobject_deadline,
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(
this, R.layout.listview_viewlayout,
cursor,
columns,
to,
0);
ListView listView = (ListView) findViewById(R.id.listview);
ArrayList <ProcessObject> arrayList = new ArrayList<>();
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
activateAddButton();
OnItemClickListener();
};
I see two oppurtinities: sorting the cursor, or sorting the Array to[]. But I don't know how.
public Cursor fetchAllData(){
Cursor cursor = database.query(DatabaseHelper.TABLE_DATABASE, columns, null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
Solved it:
String orderBy = DatabaseHelper.COLUMN_DEADLINE + " ASC";;
Cursor cursor = database.query(DatabaseHelper.TABLE_DATABASE, columns, null, null, null, null, orderBy);
Related
I have build an app that take data with different attribute, adds them in the database and then shows it through a ListView.
I have done the part where data are added, but I Can't figure out how to fetch it(for now I just want the name) from the database and populate it in the ListView.
Here is the part in the database class.
public Cursor getCursor() {
Cursor c = null;
sqLiteDatabase = this.getReadableDatabase();
String query = "SELECT * FROM tbl_customer";
String where = null;
c = sqLiteDatabase.query("tbl_customer", new String[]{"Name"}, where, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
here is the part of code in activity which I want to show the ListView in.
private void populateListView(){
Cursor cursor = db.getCursor();
String []From = new String[]{"Name"};
int [] to = new int[R.id.textView];
SimpleCursorAdapter adapter;
adapter = new SimpleCursorAdapter(this,R.layout.listview_items,cursor,From,to,0);
ListView listView = (ListView)findViewById(R.id.ShowDataListView);
listView.setAdapter(adapter);
}
Please guide me, where I have gone wrong, and correct me.
you are using R.id.textView as a size of array
int [] to = new int[R.id.textView];
it should be like this
int [] to = new int[]{R.id.textView};
You've to specify the From and To params of the SimpleCursorAdapter.
adapter = new SimpleCursorAdapter(this,R.layout.listview_items,cursor,
new String[] { "Name" },to,0);
As for to, you need to put the id of your textview from R.layout.listview_items. Let's assume the id of your TextView is R.id.text1 then the adapter will look like following,
adapter = new SimpleCursorAdapter(this,R.layout.listview_items,cursor,
new String[] { "Name" },
new int[] { android.R.id.text1 },
0);
Here, have a look at the documentation to grasp it more clearly.
how can i retrieve 2 columns data from database using one cursor....now i am using 2 cursors at a time like
ArrayList<String> sender_array = new ArrayList<String>();
ArrayList<String> body_array = new ArrayList<String>();
messagedb=ListView.this.openOrCreateDatabase("message",0, null);
messagedb.execSQL("CREATE TABLE IF NOT EXISTS tab2(sender INT(13),body varchar)");
Cursor cur1=mydb.rawQuery("select * from tab2", null);
while(cur.moveToNext())
{
String sender1=cur.getString(cur.getColumnIndex("sender"));
sender_array.add(sender1);
}
cur1.close();
Cursor cur2=mydb.rawQuery("select * from tab2", null);
while(cur.moveToNext())
{
String body1=cur.getString(cur.getColumnIndex("body"));
body_array.add(body1);
}
cur2.close();
messagedb.close();
how can i use one cursor for poping out a list view?
Cursor cur=mydb.rawQuery("select sender, body from tab2", null);
while(cur.moveToNext())
{
String sender = cur.getString(0);
String body = cur.getString(1);
}
cur.close();
or this is safer, if you decide to change the columns order later
Cursor cur=mydb.rawQuery("select sender, body from tab2", null);
while(cur.moveToNext())
{
String sender = cur.getString(cur.getColumnIndex("sender"));
String body = cur.getString(cur.getColumnIndex("body"));
}
cur.close();
Use one Cursor as follows:
Cursor cur=mydb.rawQuery("select sender, body from tab2", null);
Update:
You don't need an ArrayList, you can load the Cursor directly to a SimpleCursorAdapter and use this adapter to load the data to the ListView
SimpleCursorAdapter (Context context, int layout, Cursor c, String[] from, int[] to)
then set the adapter to the ListView:
ListView.setAdapter(your_SimpleCursorAdapter)
i want to get the value from the cursor without the SimpleCursorAdapter part.here is the code
public Cursor queueAll(){
String[] columns = new String[]{KEY_ID, KEY_CONTENT1, KEY_CONTENT2,KEY_CONTENT3};
Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns,
null, null, null, null, null);
return cursor;
}
and the activity side code
cursor = mySQLiteAdapter.queueAll();
from = new String[]{SQLiteAdapter.KEY_ID, SQLiteAdapter.KEY_CONTENT1, SQLiteAdapter.KEY_CONTENT2, SQLiteAdapter.KEY_CONTENT3};
int[] to = new int[]{R.id.id, R.id.text1, R.id.text2,R.id.text3};
cursorAdapter =
new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);
listContent.setAdapter(cursorAdapter);
while(!cursor.isAfterLast())
{
String tilt = cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_CONTENT1));
String pkg = cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_CONTENT3));
if(tilt.equals("LEFT"))
{
Log.v("LEFT",pkg);
}
else if(tilt.equals("RIGHT"))
{
Log.v("RIGHT",pkg);
}
cursor.moveToNext();
}
i am getting the pkg value correct.but i want to get the values directly from the cursor while removing SimpleCursorAdapter part the code doesn't work.
any help would be appreciated :)
You can get values without declaring adapters. Adapters are need if you want to show the data in the list widgets. So your can be the following:
cursor = mySQLiteAdapter.queueAll();
if (cursor == null) {
//check if there are errors or query just return null
}
if (cursor.moveToFirst()) {
while(!cursor.isAfterLast())
{
String tilt = cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_CONTENT1));
String pkg = cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_CONTENT3));
if(tilt.equals("LEFT"))
{
Log.v("LEFT",pkg);
}
else if(tilt.equals("RIGHT"))
{
Log.v("RIGHT",pkg);
}
cursor.moveToNext();
}
}
First you must count how many rows are in your table. Then assign that count to variable and it use to create an array. For array size you can use that count variable. Then create a for loop and use that count variable for rounds. After create your query and assign values to your arrays. 100% worked!.
int sqlcount;
Cursor mFetch;
SQLiteDatabase mydb = openOrCreateDatabase("your database name", MODE_PRIVATE, null);
mydb.execSQL("create table if not exists customer(name varchar,email varchar)");
Cursor mCount = mydb.rawQuery("select count(*) from customer", null);
mCount.moveToFirst();
sqlcount = mCount.getInt(0);
mCount.close();
String cname[] = new String[sqlcount];
String cemail[] = new String[sqlcount];
for(int i=0;i<sqlcount;i++) {
mFetch= mydb.rawQuery("select name,email from customer", null);
mFetch.moveToPosition(i);
cname[i] = mFetch.getString(0);
cemail[i] = mFetch.getString(1);
}
mFetch.close();
Toast.makeText(MainActivity.this,String.valueOf(cname[0]),Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity.this,String.valueOf(cemail[1]),Toast.LENGTH_SHORT).show();
How do I bind information from my database to a TextView? The ListView Isnt showing the information from the Cursor. Do I need to use the adapter I have created?
I'm trying to display the results in TextViews withing the List.
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.contactform);
Cursor cursor = getCursor();
SimpleCursorAdapter adapter = new SimpleCursorAdapter(
this, //Context
R.layout.contactform, //xml definintion of each listView item
cursor, //Cursor
new String[] {"FirstName", "LastName", "Phone", "Email"}, //Columns to select From
new int[] {R.id.contact_firstname, R.id.contact_lastname, R.id.contact_phone, R.id.contact_email} //Object to bind to
);
}
private Cursor getCursor()
{
String TABLE_NAME = "exampleContacts";
String[] FROM = {"_id", ""FirstName", "LastName", "Phone", "Email"} ;
dbManager = new DatabaseManager(this);
SQLiteDatabase db = dbManager.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, FROM, "ContactID=?", new String[] {PrContactID}, null, null, null);
startManagingCursor(cursor);
return cursor;
}
It looks like you're pulling back a single record. In that case, you don't need to be using the SimpleCursorAdapter, as that is generally used for assigning multiple records to a ListView. Why not just grab the info you need and manually set them to your TextView(s)?
Also, you shouldn't need to use a manage cursor. Just get the values you need and then close the cursor like so:
TextView textView = (TextView) findViewById(R.id.textView01);
Cursor cursor = db.query("exampleContacts", new String[] {"FirstName", "LastName", "Phone", "Email"}, "ContactID=?", new String[] {PrContactID}, null, null, null);
cursor.moveToFirst();
String text = cursor.getString(0) + " " + cursor.getString(1) + " " + cursor.getString(2) + " " + cursor.getString(3);
textView.setText(text);
cursor.close();
Sorry for any typos... this code is just for example and hasn't been tested.
The reason it wasnt being mapped to the ListView is because setListAdapter(); wasnt being used.
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.contactform);
Cursor cursor = getCursor();
SimpleCursorAdapter adapter = new SimpleCursorAdapter(
this, //Context
R.layout.contactform, //xml definintion of each listView item
cursor, //Cursor
new String[] {"FirstName", "LastName", "Phone", "Email"}, //Columns to select From
new int[] {R.id.contact_firstname, R.id.contact_lastname, R.id.contact_phone, R.id.contact_email} //Object to bind to
);
setListAdapter(adapter);
}
I have a table layout that I want to populate with the result from a database query. I use a select all and the query returns four rows of data.
I use this code to populate the TextViews inside the table rows.
Cursor c = null;
c = dh.getAlternative2();
startManagingCursor(c);
// the desired columns to be bound
String[] columns = new String[] {DataHelper.KEY_ALT};
// the XML defined views which the data will be bound to
int[] to = new int[] { R.id.name_entry};
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this,
R.layout.list_example_entry, c, columns, to);
this.setListAdapter(mAdapter);
I want to be able to separate the four different values of KEY_ALT, and choose where they go. I want them to populate four different TextViews instead of one in my example above.
How can I iterate through the resulting cursor?
Cursor objects returned by database queries are positioned before the first entry, therefore iteration can be simplified to:
while (cursor.moveToNext()) {
// Extract data.
}
Reference from SQLiteDatabase.
You can use below code to go through cursor and store them in string array and after you can set them in four textview
String array[] = new String[cursor.getCount()];
i = 0;
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
array[i] = cursor.getString(0);
i++;
cursor.moveToNext();
}
for (boolean hasItem = cursor.moveToFirst(); hasItem; hasItem = cursor.moveToNext()) {
// use cursor to work with current item
}
Iteration can be done in the following manner:
Cursor cur = sampleDB.rawQuery("SELECT * FROM " + Constants.TABLE_NAME, null);
ArrayList temp = new ArrayList();
if (cur != null) {
if (cur.moveToFirst()) {
do {
temp.add(cur.getString(cur.getColumnIndex("Title"))); // "Title" is the field name(column) of the Table
} while (cur.moveToNext());
}
}
Found a very simple way to iterate over a cursor
for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
// access the curosr
DatabaseUtils.dumpCurrentRowToString(cursor);
final long id = cursor.getLong(cursor.getColumnIndex(BaseColumns._ID));
}
I agree to chiranjib, my code is as follow:
if(cursor != null && cursor.getCount() > 0){
cursor.moveToFirst();
do{
//do logic with cursor.
}while(cursor.moveToNext());
}
public void SQLfunction() {
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String[] sqlSelect = {"column1","column2" ...};
String sqlTable = "TableName";
String selection = "column1= ?"; //optional
String[] selectionArgs = {Value}; //optional
qb.setTables(sqlTable);
final Cursor c = qb.query(db, sqlSelect, selection, selectionArgs, null, null, null);
if(c !=null && c.moveToFirst()){
do {
//do operations
// example : abcField.setText(c.getString(c.getColumnIndex("ColumnName")))
}
while (c.moveToNext());
}
}
NOTE: to use SQLiteQueryBuilder() you need to add
compile 'com.readystatesoftware.sqliteasset:sqliteassethelper:+'
in your grade file