SQLite getCount() returns 0 - java

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;
}

Related

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?!

how to store string data into integer array from sqlite for android

I want to convert the sqlite data into integer array.
public Integer[] getch() {
SQLiteDatabase database = this.getReadableDatabase();
Cursor cursor = database.rawQuery("SELECT sum(sales) FROM sales group by outlet_code order by ordered_date", null);
// String[] array = new String[crs.getCount()];
int columnIndex = 3;
Integer[] in = new Integer[cursor.getCount()];
if (cursor.moveToFirst())
{
for (int i = 0; i < cursor.getCount(); i++)
{
in[i] = cursor.getInt(columnIndex);
cursor.moveToNext();
}
}
cursor.close();
return in;
}
I need result in following format:
int[] income = { 2000,2500,2700,3000,2800,3500,3700,3800, 0,0,0,0};
Integer[] income = controller.getch();
I'm getting the error :
Couldn't read row 0, col 3 from CursorWindow. Make sure the Cursor is
initialized correctly before accessing data from it
Why are you using columnIndex = 3, your sql query will return only 1 column i.e Sum(sales), so you should set your columnIndex value to 0
Try this
public Integer[] getch() {
SQLiteDatabase database = this.getReadableDatabase();
Cursor cursor = database.rawQuery("SELECT sum(sales) FROM sales group by outlet_code order by ordered_date", null);
// String[] array = new String[crs.getCount()];
int columnIndex = 0;
Integer[] in = new Integer[cursor.getCount()];
if (cursor.moveToFirst())
{
for (int i = 0; i < cursor.getCount(); i++)
{
in[i] = cursor.getInt(columnIndex);
cursor.moveToNext();
}
}
cursor.close();
return in;
}
Hope this helps

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)

How to create sequential number but not ROWID in Android SQLite database?

I am working on an app which contains an Android SQLite database. I add and delete rows in this database. When I delete my row, it is based on the ROWID. But I found out, that despite I delete the row, the ROWID remains. So for example if I have 3 rows in my database and delete the 2nd row, my third row will not change to 2 it remains 3. Then if I add a row, it will be 4.
So my question is, how to do that when I delete a row, and add a new one then the number of the added row would equal to the deleted row. So for example if I delete the first row, than the database will show me next to the other rows 1,2,3... and not 2,3,4...
Sorry, maybe it is a little bit complicated, but I hope it makes sense.
Here is my code:
public HotOrNot open() throws SQLException{
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close(){
ourHelper.close();
}
public long createEntry(String name, String hotness) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, name);
cv.put(KEY_HOTNESS, hotness);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
public String getData() {
// TODO Auto-generated method stub
String[] columns = new String[]{ KEY_ROWID, KEY_NAME, KEY_HOTNESS};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
int iName = c.getColumnIndex(KEY_NAME);
int iHotness = c.getColumnIndex(KEY_HOTNESS);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iRow) + " " + c.getString(iName) + " " + c.getString(iHotness) + "\n";
}
return result;
}
public String getName(long l) throws SQLException{
// TODO Auto-generated method stub
String[] columns = new String[]{ KEY_ROWID, KEY_NAME, KEY_HOTNESS};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "=" + l, null, null, null, null);
if(c != null){
c.moveToFirst();
String name = c.getString(1);
return name;
}
return null;
}
public String getHotness(long l) throws SQLException{
// TODO Auto-generated method stub
String[] columns = new String[]{ KEY_ROWID, KEY_NAME, KEY_HOTNESS};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "=" + l, null, null, null, null);
if(c != null){
c.moveToFirst();
String hotness = c.getString(2);
return hotness;
}
return null;
}
public void updateEntry(long lRow, String mName, String mHotness) throws SQLException{
// TODO Auto-generated method stub
ContentValues cvUpdate = new ContentValues();
cvUpdate.put(KEY_NAME, mName);
cvUpdate.put(KEY_HOTNESS, mHotness);
ourDatabase.update(DATABASE_TABLE, cvUpdate, KEY_ROWID + "=" + lRow, null);
}
public void deleteEntry(long lRow1) throws SQLException{
// TODO Auto-generated method stub
ourDatabase.delete(DATABASE_TABLE, KEY_ROWID + "=" + lRow1, null);
}
}
I know that it can't be done using ROWID, because it is unique for each row.
Could you please write the code how to solve this problem, because I am beginner in Android and also in SQLite.
Thanks in advance
SQLite keeps track of the largest ROWID that a table has ever held
using the special SQLITE_SEQUENCE table.
You can update SQLITE_SEQUENCE table-
UPDATE SQLITE_SEQUENCE SET seq = <n> WHERE name = <table_name>
n is the rowid - 1
Similar question.

Cursor doesn't seem to be working in android app

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

Categories

Resources