Cursor doesn't seem to be working in android app - java

My cursor do not seem to be working. Can somebody please help me?
Actually the for loop here is not working. The log is not being shown.
This is my code:
public String getAFact(int rowNumber)
{
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("select mfacts from mfacts where osl_number=" + rowNumber + ";", null);
for(c.moveToFirst();!c.isAfterLast();c.moveToNext()) {
rowData = c.getString(c.getColumnIndex(KEY_NAME));
Log.i("log_tag", "cursor isn't f**ked up..."+rowData);
}
c.close();
db.close();
return rowData;
}
}
But anyway the following code is working fine and is showing the number of records correctly!
public int countRowsInDb()
{
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("select * from mfacts",null);
Log.i("Number of Records"," :: "+c.getCount());
db.close();
int c_getCount = c.getCount();
c.close();
return c_getCount;
}

I think your SQL statement is off. It looks like you are trying to get the whole row of data, try
"select * from mfacts where osl_number=" + rowNumber + ";"
as your query.

U can try for this..
if (cursor.moveToFirst())
{
for (int i = 0; i < cursor.getCount(); i++)
{
//Your logic goes here//
cursor.moveToNext();
//
}
}
cursor.close();
db.close();

Related

SQL: Can't get count(*) to work - why so?

I'm trying to query a database for the count of entries that match the given ID, but I can't come up with a working solution.
There are two of each type of account that correspond to the userID of 1, for some reason the first method outputs "1" and the second "0". I can show the mainactivity and the database shchema if needed as well.
public int numberOfDebitAccounts(int userID){
int numOf_accs = 0;
String query = "select count(*) from debitAccount where userID = '" +userID+"'";
openDatabase();
Cursor cursor = db.rawQuery(query,null);
if(cursor.moveToFirst()) {
numOf_accs = cursor.getInt(0);
System.out.println("Number of debit accs: " + numOf_accs);
}
cursor.close();
closeDatabase();
return numOf_accs;
}
public int numberOfCreditAccounts(int userID){
int numOf_accs = 0;
String query = "select count(accountID) from creditAccount where userID = '" +userID+"'";
openDatabase();
Cursor cursor = db.rawQuery(query,null);
if(cursor.moveToFirst()) {
numOf_accs = cursor.getInt(0);
System.out.println("number of credit accounts: " + numOf_accs);
}
closeDatabase();
return numOf_accs;
}

SQLite getCount() returns 0

I am trying to make search history through SQLite in Android Studio.
When I try to get information from SQLite DB using getCount(),
it keeps returning 0.
I have checked if there are any data in DB by terminal.
However it showed results that there are data.
Please help me.
public String[][] getResult(){
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM AlYak_History", null);
Log.d("getCount", valueOf(cursor.getCount()));
String[][] result = new String[cursor.getCount()][];
cursor.moveToFirst();
while(cursor.moveToNext()){
for(int i = 0 ; i < 12 ; i ++){
result[cursor.getPosition()][i] = cursor.getString(i+1);
}
}
cursor.close();
db.close();
return result;
}
Are you sure you connect to the DB? Your constructor should be like this:
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
It should be String.valueOf() not valueOf
This one work for me
public int getResultCount() {
String countQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int cnt = cursor.getCount();
cursor.close();
return cnt;
}

ContentValues does not insert values into table

I have this:
public void addNewNote(Note n) {
ContentValues values = new ContentValues();
values.put(COLUMN_TITLE, n.getNote_title());
values.put(COLUMN_TEXT, n.getNote_text());
values.put(COLUMN_FK, n.getNote_ForeignKey()); //this column is integer type
values.put(COLUMN_PT, String.valueOf(n.getNote_PersonType())); //this column is char type
SQLiteDatabase db = this.getWritableDatabase();
db.insert("tbl_Notes",null, values);
}
as my add method, as I traced it, the record is added successfully. but when I try to get my note with below code, findNote always returns null and cnt is always 0.
public Note findNote(int note_id){
String query = "select * from tbl_Notes"; // where " + COLUMN_ID + " = " + note_id;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
int cnt = cursor.getCount();
Note N = new Note();
if (cursor.moveToFirst()) {
cursor.moveToFirst();
N.setNote_title(cursor.getString(1)); //title column
N.setNote_text(cursor.getString(2)); //text body column
N.setNote_ForeignKey(Integer.parseInt(cursor.getString(3))); //foreign key column
N.setNote_PersonType(cursor.getString(4).charAt(0)); //person type column
cursor.close();
}else {
N = null;
}
return N;
}
and here is my onClick which fires addNewNote:
Note myNote = new Note(
txt_Title.getText().toString(),
foreignKey,
personType,
txt_Body.getText().toString()
);
tbl_notes.addNewNote(myNote);
what am I doing wrong?!

SQLite database query returns only one row

Below is the code I'm using to grab all results stored in an SQLite table. The problem I am having is that it is only returning a single row when I know there are 21 rows in the DB.
public HashMap<String, String> fetchResults(String TABLE_NAME, String sql) {
HashMap<String, String> table = new HashMap<String, String>();
if(sql == null)
sql = "";
String selectQuery = "SELECT * FROM " + TABLE_NAME + " " + sql;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
String[] columns = null;
switch(TABLE_NAME ){
case "projects":
columns = dbTables.projectsColumns;
break;
}
// Move to first row
cursor.moveToFirst();
if (cursor.getCount() > 0) {
int n=1;
for(int i=0; i<columns.length; i++){
table.put(columns[i], cursor.getString(n));
n++;
}
}
//move to the next row
cursor.moveToNext();
cursor.close();
db.close();
// return user
Log.d(TAG, "Fetching " + TABLE_NAME + " from Sqlite: " + table.toString());
return table;
}
The db call is made within a fragment and look like this.
HashMap<String, String> projects = db.fetchResults(dbTables.TABLE_PROJECTS, null);
for (String key : projects.keySet()) {
if(key == "projectname"){
System.out.println("Key: " + key + ", Value: " + projects.get(key));
menuList.add(projects.get(key));
}
}
You are only retrieving one single row there:
// Move to first row
cursor.moveToFirst();
if (cursor.getCount() > 0) {
int n=1;
for(int i=0; i<columns.length; i++){
table.put(columns[i], cursor.getString(n));
n++;
}
}
You have to iterate the cursor to get all results:
// Move to first row
cursor.moveToFirst();
if (cursor.getCount() > 0) {
while(cursor.moveToNext()) {
for (int i = 0; i < columns.length; i++) {
table.put(columns[i], cursor.getString(i));
}
}
}
But your table would list all the column values of every row. If you want to have a table with row-entries, define a class for storing the column values.
I am unsure on what the cursor.movetonext() method is because I have never used it, but I would just been using a method like this:
public static ResultSet createRS(String Query,String Server) {
// Create a variable for the connection string.
String connectionUrl = "jdbc:sqlserver://"+Server+"\\SQLExpress;databaseName=Schedule;" +
"integratedSecurity=true;";
// Declare the JDBC objects.
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
// Establish the connection.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(connectionUrl);
// Create and execute an SQL statement that returns a
// set of data and then display it.
String SQL = Query;
stmt = con.createStatement();
rs = stmt.executeQuery(SQL);
}
// Handle any errors that may have occurred.
catch (Exception e) {
e.printStackTrace();
}
return rs;
}
With the result set you can just do this:
try {
while (rs.next()) {
current=Double.parseDouble(rs.getString(currentColumn));
}
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
Thanks to all who answered. I have found a function that works for perfectly.
public Cursor getAllRows(String TABLE_NAME, String sql){
String selectQuery = "SELECT * FROM " + TABLE_NAME + " " + sql;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if(cursor != null){
cursor.moveToFirst();
}
return cursor;
}

retrieve multiple rows form android sqlite

I am going to fetch some rows with specific tag in android Sqlite.
The problems are
I got 15 with cursor.getCount(); but 13 rows retrieved.
the 13 rows just repeat last row data
here is my code
public ArrayList<HashMap<String, String>> getTodo(String tag) {
ArrayList<HashMap<String,String>> arList = new ArrayList<HashMap<String,String>>();
HashMap<String, String> todo = new HashMap<String, String>();
String selectQuery = "SELECT * FROM " + TABLE_NAME + " WHERE "
+ COLUMN_TAG + " = ?";
String[] args={tag};
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, args);
// Move to first row
cursor.moveToFirst();
System.out.println(cursor.getCount());
if (cursor.getCount() > 0) {
do {
todo.put(COLUMN_ID, cursor.getString(cursor.getColumnIndex(COLUMN_ID)));
todo.put(COLUMN_FROM, cursor.getString(cursor.getColumnIndex(COLUMN_FROM)));
todo.put(COLUMN_TO, cursor.getString(cursor.getColumnIndex(COLUMN_TO)));
todo.put(COLUMN_TITLE, cursor.getString(cursor.getColumnIndex(COLUMN_TITLE)));
todo.put(COLUMN_TAG, cursor.getString(cursor.getColumnIndex(COLUMN_TAG)));
arList.add(todo);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
// return todo
return arList;
}
Please help. Thanks
You are using the same todo object for all rows, so you end up with lots of references to the same object.
Create a new one for each row in the loop:
Cursor cursor = db.rawQuery(selectQuery, args);
try {
while (cursor.moveToNext()) {
HashMap<String, String> todo = new HashMap<String, String>();
todo.put(...);
...
arList.add(todo);
}
finally {
cursor.close();
}
It's better to make the todo's you want to acquire into objects
public class Todo {
public String id, from, to, title, tag;
//setters and getters (not necessary)
}
public ArrayList<MyData> getTodo(String tag) {
ArrayList<MyData> arList = new ArrayList<MyData>();
String selectQuery = "SELECT * FROM " + TABLE_NAME + " WHERE "
+ COLUMN_TAG + " = ?";
String[] args={tag};
try {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, args);
// Move to first row
if (!cursor.moveToFirst())
return arList;
do {
Todo todo = new Todo();
todo.id = cursor.getString(cursor.getColumnIndex(COLUMN_ID));
todo.from = cursor.getString(cursor.getColumnIndex(COLUMN_FROM));
todo.to = cursor.getString(cursor.getColumnIndex(COLUMN_TO));
todo.title = cursor.getString(cursor.getColumnIndex(COLUMN_TITLE))
todo.tag = cursor.getString(cursor.getColumnIndex(COLUMN_TAG));
arList.add(todo);
} while(cursor.moveToNext());
cursor.close();
db.close();
return arList;
}
finally {
cursor.close();
db.close();
}
}
You keep putting new strings to an already created hashmap, but you keep using the same keys, and therefore, many entries get replaced. The Todo object keeps your code readable. You should also check if the cursor can jump to the first entry (which makes a getCount call unnecessary)

Categories

Resources