How to read out two columns from table and multiplize them? - android

How can I realize that in Android Java ?
So I mean how can I read out mark and weight, multiplize them and add the next row with the same system?:
That is what I have now for list those marks in a ListView:
private void fillData() {
Bundle extras = getIntent().getExtras();
String txt_sub_id = extras.getString("IDFach");
int test = Integer.parseInt(txt_sub_id);
Cursor mCursor = db.rawQuery("SELECT _id, subid, name, mark, gewicht, datum FROM tbl_marks WHERE subid = '"+test+"';", null);
startManagingCursor(mCursor);
if (mCursor != null && mCursor.moveToFirst()) {
int intName = mCursor.getColumnIndexOrThrow("subid");
do {
teststring = mCursor.getString(intName);
String[] from = new String[] { dbHelper.KEY_NAME_MARKS, dbHelper.KEY_MARK_MARKS, dbHelper.KEY_GEWICHT_MARKS, dbHelper.KEY_DATUM_MARKS};
int[] to = new int[] {R.id.txt_marks_row, R.id.txt_note, R.id.txt_gewicht, R.id.txt_datum};
SimpleCursorAdapter notes = new SimpleCursorAdapter(this, R.layout.show_marks, mCursor, from, to);
setListAdapter(notes);
} while (mCursor.moveToNext());
}
}
This looks like that:
What I like to have:
Thanks in advance!

You need to do something like below inside do/while loop. Here 4 is index of column name in your query.
int mark=mCursor.getInt(4);
int wght=mCursor.getInt(5);

Related

Android Simple Cursor adapter and Cursor

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.

updating sqlite database to sort integers from highest value down

How would i go about this, i have COLUMN_ID, COLUMN_NAME and COLUMN_INTE
COLUMN_INTE holds long integers and I want it to be displayed on a List view, which it currently does just not descending from highest to lowest
You need to write your query against your table with an ORDER BY clause that dictates a descending order with the DESC keyword. Something like this should work:
string query = "SELECT COLUMN_ID, COLUMN_NAME, COLUMN_INTE FROM MY_TABLE ORDER BY COLUMN_INTE DESC";
Cursor c = db.rawQuery(query, null);
String[] columns = new String[] { "COLUMN_ID", "COLUMN_NAME"};
int[] to = new int[] {android.R.id.text1, android.R.id.text2};
try {
dataAdapter = new SimpleCursorAdapter(
this, android.R.layout.simple_list_item_2, c, columns, to, 0
);
ListView lv = (ListView) findViewById(R.id.MY_LISTVIEW);
lv.setAdapter(dataAdapter);
} catch (Exception ex) {
ex.printStackTrace();
}
You can also use comparator to do sorting . Like an example -
class MySalaryComp implements Comparator{
#Override
public int compare(Empl e1, Empl e2) {
if(e1.getSalary() < e2.getSalary()){
return 1;
} else {
return -1;
}
}
}
You have two options: Use an SQL command that sorts for you or you can get the entire list and sort it yourself.
SQL command sorting:
// Create an object to store rows from the table
tableRowObject = new tableRowObject();
String query = "select * from STATISTICS order by COLUMN_INTE";
Cursor cursor = db.rawQuery(query, null);
if(cursor.getCount()<1) // COLUMN_INTE Not Found
{
cursor.close();
}
else
{
while(cursor.moveToNext())
{
// Get COLUMN_ID, COLUMN_NAME, COLUMN_INTE
int columnID = cursor.getInt(cursor.getColumnIndex("COLUMN_ID"));
String columnName = cursor.getString(cursor.getColumnIndex("COLUMN_NAME"));
int columnInte = cursor.getInt(cursor.getColumnIndex("COLUMN_INTE"));
// Add the variables to a new object
tableRowObject.add(columnID, columnName, columnInte);
}
cursor.close();
}
Sort yourself:
// Create an object to store rows from the table
tableRowObject = new tableRowObject();
String query = "select * from STATISTICS";
Cursor cursor = db.rawQuery(query, null);
if(cursor.getCount()<1) // COLUMN_INTE Not Found
{
cursor.close();
}
else
{
while(cursor.moveToNext())
{
// Get COLUMN_ID, COLUMN_NAME, COLUMN_INTE
int columnID = cursor.getInt(cursor.getColumnIndex("COLUMN_ID"));
String columnName = cursor.getString(cursor.getColumnIndex("COLUMN_NAME"));
int columnInte = cursor.getInt(cursor.getColumnIndex("COLUMN_INTE"));
// Add the variables to a new object
tableRowObject.add(columnID, columnName, columnInte);
}
cursor.close();
}
// Sort the object

Reapeated columns using setFilterQueryProvider

I have a listview with a problem. I want to implement the classic search with the edittext, i am using the addTextChangedListener with TextWatcher(). The Listview gets the elements from a database so I use cursor and simplecursoradapter so i have to use the setFilterQueryProvider. The problem appears when I write something in the edittext, if I write the name of a product it changes all the names of the elements in the list.So i dont know what to do. Appreciate the help.
here is my java code with the listview:
public class Lista_general extends ListActivity {
SimpleCursorAdapter adapter;
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lista_general);
list = getListView();
EditText edit =(EditText)findViewById(R.id.edit);
// open database
AdminSQLiteOpenHelper dbhelper = new AdminSQLiteOpenHelper(
getBaseContext());
SQLiteDatabase db = dbhelper.getReadableDatabase();
// array for SimpleCursorAdapter
String columns[] = new String[] { "PRODUCTO._id",
"nombre","category","CATEGORIAS._id","categoryid" };
String orderBy = "category";
// query database
Cursor c = db.query("PRODUCTO, CATEGORIAS WHERE CATEGORIAS._id = categoryid ",
columns,null,null, null, null, orderBy);
c.moveToFirst();
// array for SimpleCursorAdapter
String from[] = new String[] { "nombre", "category", };
//String from[] = new String[] { "nombre", "categoria", };
int to[] = new int[] { R.id.name, R.id.cate, };
// Adapter
adapter = new SimpleCursorAdapter(getBaseContext(),
R.layout.productos, c, from, to,
SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
setListAdapter(adapter);
list.setTextFilterEnabled(true);
//Listener edit text
edit.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
adapter.getFilter().filter(s.toString());
}
});
adapter.setFilterQueryProvider(new FilterQueryProvider() {
#Override
public Cursor runQuery(CharSequence constraint) {
// TODO Auto-generated method stub
AdminSQLiteOpenHelper dbhelper = new AdminSQLiteOpenHelper(
getBaseContext());
SQLiteDatabase db = dbhelper.getReadableDatabase();
Cursor mCursor = null;
if (constraint == null || constraint.length () == 0) {
mCursor = db.query("PRODUCTO, CATEGORIAS", new String[] {
"PRODUCTO._id", "nombre","CATEGORIAS._id","category"},
null, null, null, null, null);
}
else {
mCursor = db.query(true,"PRODUCTO, CATEGORIAS", new String[]
{"PRODUCTO._id", "nombre", "category","CATEGORIAS._id"},
"nombre" + " like '%" + constraint + "%'", null,
null, null, null, null);
}
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
});
}
Here is a visual of my error:
first my normal list:
http://i40.tinypic.com/2111k0p.png
after I wrote:
http://i44.tinypic.com/23j04kg.png
It looks like the queries generated in the FilterQueryProvider are not joining the tables properly, so that you end up with every possible combination of PRODUCTO and CATEGORIAS (which are then filtered by PRODUCTO.nombre to give the impression that all the names have changed).
There's also a potential security risk with inserting constraint directly into the query, this opens the door to SQL injection attacks. I'm not sure how serious this is in the context of Android apps, but in for example a PHP web application this would allow anyone to execute any SQL they wished by entering a carefully crafted constraint.
From the answers to this question it looks like a rawQuery() call is needed in order to use SQL JOIN so I would change your queries as follows...
For querying with no filter (i.e. in onCreate(); and in runQuery() where there is no constraint):
cursor = db.rawQuery("SELECT PRODUCTO._id, nombre, category, CATEGORIAS._id FROM PRODUCTO INNER JOIN CATEGORIAS ON PRODUCTO.categoryid = CATEGORIAS._id", null);
For querying with a filter:
String[] params = { constraint.toString() };
cursor = db.rawQuery("SELECT PRODUCTO._id, nombre, category, CATEGORIAS._id FROM PRODUCTO INNER JOIN CATEGORIAS ON PRODUCTO.categoryid = CATEGORIAS._id WHERE nombre LIKE ('%' || ? || '%')", params);

Android SQLite get data from database to an array

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();

Iterate through rows from Sqlite-query

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

Categories

Resources