Checking entries in a database issue with a while loop - android

Integer c=0;
DatabaseHelper dbh1 = new DatabaseHelper(this);
Cursor ca = dbh1.getReadableDatabase().query(DatabaseHelper.TABLE_NAME, null, null, null, null, null, null);
while (ca.moveToNext())
{
String Ans6 = ca.getString(ca.getColumnIndex(DatabaseHelper.VALUE6));
if ( Ans6.equals("Automatic"))
{
c+=1;
}
}
String strI = Integer.toString(c);
Toast toast=Toast.makeText(this, strI, 2000);
toast.show();
I have a SQlite database setup in android. The table has been successfully set up and I am trying to check values from column VALUE6 if it matches Automatic. The cursor has to go through every row and check the value of VALUE6 in that row and return how many rows have Automatic. Is my code right? any ideas? strI returns 0 every time i run the code.

That's a brute force way of doing it. Why not query for that value and then get the count of the rows in the returned cursor?
Cursor ca = dbh1.getReadableDatabase().query(DatabaseHelper.TABLE_NAME, null, DatabaseHelper.VALUE6 + "='AUTOMATIC'", null, null, null, null);
int count = ca.getCount();
Hope this helps!

Related

retrieve particular column between different columns of sqlite databse in android

Here is the code, by this I can retrieve all the columns data from the database. But the problem is that now I want to retrieve only one column, that is my requirement.link1st link 2nd link3rd
word_list = new ArrayList<>();
SQLiteDatabase sd = mydb.getWritableDatabase();
Cursor cursor = sd.query("stickerstable",null, null, null, null, null, null);
if (cursor.moveToFirst()){
do{
word_list.add(new data_items(
cursor.getInt(cursor.getColumnIndex(ID)),
cursor.getString(cursor.getColumnIndex(STICKER_AUTHOR)),
cursor.getString(cursor.getColumnIndex(STICKER_NAME)
)));
}while (cursor.moveToNext());
cursor.close();
sd.close();
}
You can use rawQuery instead of query
Cursor cursor = sd.rawQuery("SELECT YOUR_COLUMN FROM stickerstable",null);
replace YOUR_COLUMN with the name of column you want to retrieve you can even use your Constants like this
Cursor cursor = sd.rawQuery("SELECT " + ID + " FROM stickerstable",null);
or a better way to use String.format
Cursor cursor = sd.rawQuery(String.format("SELECT %s FROM stickerstable", ID),null);
UPDATE
you can use query and specify the column in the second argument
Cursor cursor = sd.query("stickerstable",new String[]{ID}, null, null, null, null, null);
when you pass null means get all columns

CursorIndexOutOfBounds Exception: Index 0 requested, with a size of 0

I tried to read the SQLite database column and store each values in an String array. I did the following but it returned exception cursoroutofbounds. Help me figure out what I'm doing wrong?
public String[] getPlaces(){
SQLiteDatabase db = this.getReadableDatabase();
String [] columns = {"place1"};
c = db.query("rates_table", columns, null, null, null, null, null);
String[] places = new String[c.getColumnCount()];
c.moveToNext();
for(int i=0; i<c.getColumnCount(); i++)
places[i] = c.getString(i);
return places;
}
Here :
String[] places = new String[c.getColumnCount()];
c.getColumnCount() will return count of column in row instead of number of rows in column. use c.getCount() to initialize places Array:
String[] places = new String[c.getCount()];
Or use ArrayList .
I worked out for sometime and found out the solution:
public String[] getPlaces(){
SQLiteDatabase db = this.getReadableDatabase();
String [] columns = {"place1"};
c = db.query("rates_table", columns, null, null, null, null, null);
c.moveToFirst();
ArrayList<String> places = new ArrayList<String>();
while(!c.isAfterLast()) {
places.add(c.getString(c.getColumnIndex("place1")));
c.moveToNext();
}
c.close();
return places.toArray(new String[places.size()]);
}
You need to change your query and further processing at multiple places. Rectify your third parameter of query method to a proper where clause or keep it null. Loop through the cursor properly and add it to your String.
public String[] getPlaces(){
SQLiteDatabase db = this.getReadableDatabase();
String [] columns = {"place1"};
c = db.query("rates_table", columns, null, null, null, null, null);
if (c.getCount() > 0) {
String[] places = new String[c.getCount()];
int i=0;
c.moveToFirst();
do {
places[i] = c.getString(c.getColumnIndex(0)));
} while (c.moveToNext());
return places;
}
c.close();
db.close();
}
First you have an issue with c = db.query("rates_table", columns, "place1", null, null, null, null);
The third parameter will result in no rows being selected.
You could use c = db.query("rates_table", columns, null, null, null, null, null); , which would return all rows.
Or you could use c = db.query("rates_table", columns, "place1 = 'myplace'", null, null, null, null);, in which case only rows that have the value myplace in the column place1 would be shown.
The best practice way is to use the 3rd and 4th parameter in conjunction where you use ? placeholders in the 3rd parm (e.g "place1=?") and corresponding args in the 4th parameter (e.g. new String[]{"myplace"}), so to replicate the previous query you could have c = db.query("rates_table", columns, "place1=?", new String[]{"myplace}, null, null, null);
Using c.moveToNext, will try to move to the next (initially the first) row of the cursor. However, if it cannot move (i.e. there are no rows, as would be the case as described above) it will not fail, rather it returns false (true if the cursor could be moved).
So You need to check this otherwise, in the case of no rows, an attempt to access a row will fail with Cursor out of bounds Index 0 requested, with a size of 0 (i.e. you requested the first (index 0) when the size of the cursors (number of rows) is 0.
There are various ways to check.
However I suspect you will then wonder why your loop only displays 1 column. That would be because you have said in the query to just get 1 column.
If you changed the query's 2nd parameter to null, it would get all columns.
At a guess you want to return an array of all places.
Assuming this then :-
// get Cursor with all rows(3rd parm null) for the place1 column (2nd parm)
c = db.query("rates_table", columns, null, null, null, null, null);
// Create String array according to the number of rows returned.
String[] places = new String[c.getCount()];
// loop through all rows setting the respective places element with the
// value obtained from the Cursor
while (c.moveToNext) {
places[c.getPosition()] = csr.getString(csr.getColumnIndex("place1"));
}
csr.close(); // Should always close a Cursor
return places;

SQLite select query to string

I'm not able to add read data from the following SQLite select query function. I have a table with 3 columns, namely driverID, driversName, driversNo.
It's supposed to return a simple string but alas.
public String readDrivers() {
Cursor cursor = database.query(MySQLiteHelper.PROFILE_TABLE_NAME, necessaryColumns, null, null, null, null, null);
if (cursor != null){
cursor.moveToFirst();
Log.v("TEST", Integer.toString(cursor.getCount()));
Log.v("TEST", cursor.getColumnName(0));
Log.v("TEST", cursor.getColumnName(1));
Log.v("TEST", cursor.getString(0));
Log.v("TEST", cursor.getString(1));
}
String returnString = cursor.getString(0) + cursor.getString(1);
return returnString;
}
Below are the most recent results from LogCat. The last two logs don't show, for some strange reason.
08-04 20:27:35.271: V/TEST(25126): 1
08-04 20:27:35.271: V/TEST(25126): driversName
08-04 20:27:35.271: V/TEST(25126): driversNo
Any help will be greatly appreciated.
The rest of the code is based on this tut http://www.vogella.com/tutorials/AndroidSQLite/article.html
It would be easier if you provided your table structure, but in any case, some info that might help:
Cursor starts from position -1 when not null.
A good way to read the cursor would be
while (cursor.moveToNext()) {
...
}
Also,
String returnString = cursor.getString(1) + cursor.getString(2);
The above code will concatenate column index 1 and column index 2 (please note that indexes start from 0), from first row returned from your query.
Edit:
Then something as the following should work fine.
public String readDrivers() {
Cursor cursor = database.query(MySQLiteHelper.PROFILE_TABLE_NAME, necessaryColumns, null, null, null, null, null);
List<String> list = new ArrayList<String>;
while (cursor.moveToNext()) {
list.add(cursor.getString(1) + cursor.getString(2));
}
return list;
}

ERROR : CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0

Hy Guys, I am Beginner Android Developer. I need your help. i want to insert data into 2 tables of sqlite tblorder, and orderdtl. on orderdtl i have to insert data from multiple item from listview. i try to toast all variable that i want to inserted. their all appears. but when i try to save it. i get those error.
this is my DBDataSource.java
public order createorder(String orderid, String notes, long outletid) {
ContentValues values = new ContentValues();
values.put(DBHelper.ORDER_ID, orderid); // inserting a string
values.put(DBHelper.NOTES, notes); // inserting an int
values.put(DBHelper.OUTLET_ID, outletid); // inserting an int
long insertId = database.insert(DBHelper.TABLE_ORDER, null,
values);
Cursor cursor = database.query(DBHelper.TABLE_ORDER,
allorder, DBHelper.ORDER_ID + " = " + insertId, null,
null, null, null);
cursor.moveToFirst();
order neworder = cursorToorder(cursor);
cursor.close();
return neworder;}
private order cursorToorder(Cursor cursor) {
order order = new order();
order.setorderid(cursor.getString(cursor.getColumnIndex(DBHelper.ORDER_ID)));
order.setorderdate(cursor.getString(cursor.getColumnIndex(DBHelper.ORDER_DATE)));
order.setnotes(cursor.getString(cursor.getColumnIndex(DBHelper.NOTES)));
order.setoutletid(cursor.getLong(cursor.getColumnIndex(DBHelper.OUTLET_ID)));
return order;
}
The error refer to this code
Cursor cursor = database.query(DBHelper.TABLE_ORDER,
allorder, DBHelper.ORDER_ID + " = " + insertId, null,
null, null, null);
And this code
order.setorderid(cursor.getString(cursor.getColumnIndex(DBHelper.ORDER_ID)));
orderid is string, i try to get from yyyyMMddHHmmss.this is the code:
private String orderid(){
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyyMMddHHmmss", Locale.getDefault());
Date date = new Date();
return dateFormat.format(date);
}
I would be very grateful for any help that you give.Thank You.
The query didn't match any rows. Check the result of moveToFirst() to see whether the operation succeeded and only then access cursor data.
Example:
order neworder = null;
if (cursor.moveToFirst()) {
order neworder = cursorToorder(cursor);
}
cursor.close();
return neworder;
The insertId you get from insert() is the sqlite row id for the row. It's likely not the same as ORDER_ID. To make a column an alias for rowid, declare it as INTEGER PRIMARY KEY.
The error I see in logcat is not about _Player_8, but about the unknown column "KEY_Team_Name"
The problem is in your activity, the line prior to the last one:
String EntryA =String.valueOf( db.getentry("Ravirrrr", "KEY_Team_Name"));
It should be:
String EntryA =String.valueOf( db.getentry("Ravirrrr", DatabaseHandler.KEY_Team_Name));
And the DatabaseHandler should have all column names public, as the getentry method requires a column name.
Edit: adding an answer to the question in the comments below.
After calling db.query, you should check if you got something by calling Cursor.isAfterLast(). If true, the select returned an empty result set.
In your example, you WILL get an empty result set as the code creates an entry with "Ravi" as the team name, then asks for a team named "Ravirrrr".

passing parameters via intent to a query

I need to pass a parameter from an EditText and when I click the button, it'll start another activity and get that parameter and pass it to a query. It follows:
final Button ara = (Button) findViewById(R.id.maddebutton);
ara.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String maddeno = madde.getText().toString(); //madde is my EditText
Intent intent = new Intent(Anayasa.this, MaddeBul.class);
intent.putExtra("maddeler", maddeno);
startActivity(intent);
}
});
my second class is as follows:
Intent intent = getIntent();
int maddebul = intent.getIntExtra("maddeler", 0); //I don't want to set a default value but it pushes me
try {
Cursor cursor = FetchRecord(db.query("anayasa", SELECT,
"no = maddebul", null, null, null, null));
ShowRecord(cursor);
} finally {
database.close();
}
my FetchRecord(Cursor c) and ShowRecord(Cursor cursor) functions work fine, since I'm using them in other classes. There is "no" column in my "anayasa" database which holds integer values.
On LogCat, it says "no column such maddebul". It is true, there isn't. It suppose to be:
SELECT * FROM anayasa WHERE no = maddebul; //as sql command
Any help?
You are adding your extra as a String here:
intent.putExtra("maddeler", maddeno);
But when you try to retrieve the extra you are retrieving it as an int:
int maddebul = intent.getIntExtra("maddeler", 0);
Try using this insteald
String maddebul = intent.getStringExtra("maddeler", "");
For reference here are the docs for the getStringExtra() method.
On LogCat, it says "no column such maddebul". It is true, there isn't.
due to in whereClause "no = maddebul", maddebul is not a variable it is string part so change the whereClause to take it's value
Cursor cursor = FetchRecord(db.query("anayasa", SELECT,
"no = maddebul", null, null, null, null));
should be
Cursor cursor = FetchRecord(db.query("anayasa", SELECT,
"no = "+maddebul, null, null, null, null));
There are multiple problems:
You put maddebul as String here so need to get it like this:
String maddebul = intent.getStringExtra("maddeler", "");
Also you are forming your SQL query wrong, maddebul is passed as a String to the db, whereas you actually want to pass the value of that variable. So it could be like this instead:
Cursor cursor = FetchRecord(db.query("anayasa", SELECT,
"no = ?",new String[]{maddebul}, null, null, null));
you are writing maddebul in Double Quotes.
Replace
Cursor cursor = FetchRecord(db.query("anayasa", SELECT,
"no = maddebul", null, null, null, null));
By
Cursor cursor = FetchRecord(db.query("anayasa", SELECT,
"no = "+maddebul, null, null, null, null));
Better use following
Cursor cursor = FetchRecord(db.query("anayasa", SELECT,
"no = ?",new String[]{String.valueOf(maddebul)}, null, null, null));
You are put Extra as String and geting it as Integer - maybe that's the problem?

Categories

Resources