Access the data from database and put them into String[] - android

I built a table in the database, and now I want to access the all of the values in a certain column. Finally, I want to put the data into byte[].
Part of my code:
db.execSQL("create table thing(id integer primary key" +
" autoincrement, name varchar(20))");
List<Integer> all = new ArrayList<Integer>();
String sql = " SELECT id from " + DB_NAME;
Cursor result = this.db.rawQuery(sql, null);
for (result.moveToFirst(); result.isAfterLast(); result.moveToNext()) {
all.add(result.getInt(0));
}
String[] fstr = (String[]) all.toArray();
for (String bstr : fstr) {
byte[] bbs = bstr.getBytes();
}

Use this code
String[] fstr = new String[result.getCount()] ;
do {
int posi = result.getPosition();
fstr[posi] =result.getString(0);
}while (result.moveToNext());

try this
Cursor c=this.db.rawQuery(sql, null);
if(c.getCount()>0)
{
for(c.moveToFirst();!c.isAfterLast();c.moveToNext())
{
String str=c.getInt(0));// or c.getString();
}
}
else
{
Log.d(" Null value in cursor ", " null ");
}
c.close();
dbhelper.close();

Related

rawQuery() exact match

I am using the following method to query my SQLite database with LIKE statement.
public List<Bean> getWords(String englishWord) {
if(englishWord.equals(""))
return new ArrayList<Bean>();
String sql = "SELECT * FROM " + TABLE_NAME +
" WHERE " + ENGLISH + " LIKE ? ORDER BY LENGTH(" + ENGLISH + ") LIMIT 100";
SQLiteDatabase db = initializer.getReadableDatabase();
Cursor cursor = null;
try {
cursor = db.rawQuery(sql, new String[]{"%" + englishWord.trim() + "%"});
List<Bean> wordList = new ArrayList<Bean>();
while(cursor.moveToNext()) {
String english = cursor.getString(1);
String mal = cursor.getString(2);
wordList.add(new Bean(english, bangla));
}
return wordList;
} catch (SQLiteException exception) {
exception.printStackTrace();
return null;
} finally {
if (cursor != null)
cursor.close();
}
}
I would like to change the above code for that it will query for exact match. I tried to modify the code as below but I do not how to get the mal string.
public void getoneWords(String englishWord) {
String sql = "SELECT * FROM " + TABLE_NAME +
" WHERE " + ENGLISH + " =?";
SQLiteDatabase db = initializer.getReadableDatabase();
Cursor cursor = null;
try {
cursor = db.rawQuery(sql, new String[]{englishWord});
while(cursor.moveToNext()) {
String english = cursor.getString(1);
String mal = cursor.getString(2);
}
} finally {
if (cursor != null)
cursor.close();
}
}
Method getoneWords for what. You should return mal and english in this function.
return new Bean(english, mal);
If you need first word, just cursor.moveToFirst and delete while loop:
String english = cursor.getString(1);
String mal = cursor.getString(2);
return new Bean(english, mal);
I finally solved this problem myself.
public String getoneWords(String englishWord) {
String sql = "SELECT * FROM " + TABLE_NAME +
" WHERE " + ENGLISH + " =?";
SQLiteDatabase db = initializer.getReadableDatabase();
Cursor cursor = null;
String meaning = "";
try {
cursor = db.rawQuery(sql, new String[] {englishWord});
if(cursor.getCount() > 0) {
cursor.moveToFirst();
meaning = cursor.getString(2);
}
return meaning;
}finally {
cursor.close();
}
}
In your getoneWords() you are not returning the queried values.
As you have two return values you would either need to wrap them in a Pair or create a "holder" Object (e.g. class Words(String english, String mal)) for the return values.
If your Query returns multiple matches you would need to return a list of those Objects. Otherwise, your above Code would just return the last match.
So you need to alter your function to return the queried
public Pair<String,String> getoneWords(String englishWord) {
Pair<String,String> result = null;
...
if(cursor.moveToNext()) {
String english = cursor.getString(1);
String mal = cursor.getString(2);
result = new Pair<String,String>(english, mal);
}
...
return result;
}

SQLite select query returning null when it shouldn't

I'm getting a null pointer exception on the following line of code
attendanceList = dbHelper.getAttendance(surName, name);
both surName and name are not null, have size() > 0 and attendanceList is of type ArrayList and here is the getAttendance function:
public ArrayList<Attendance> getAttendance(String surName, String name)
{
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<Attendance> attendanceList = new ArrayList<>();
Cursor cursor = db.rawQuery("SELECT * FROM " + ATTENDANCE_TABLE + " WHERE " + COLUMN_SURNAME + " =? AND "
+ COLUMN_NAME + " =?", new String[] {surName, name});
if(cursor .moveToFirst())
{
while(!cursor.isAfterLast())
{
Attendance attendance = new Attendance();
attendance.setDate(cursor.getString(cursor.getColumnIndex(COLUMN_DATE)));
attendance.setName(cursor.getString(cursor.getColumnIndex(COLUMN_NAME)));
attendance.setSurName(cursor.getString(cursor.getColumnIndex(COLUMN_SURNAME)));
attendance.setState(cursor.getString(cursor.getColumnIndex(COLUMN_STATE)));
attendance.setTerm(cursor.getInt(cursor.getColumnIndex(COLUMN_TERM)));
attendance.setSubject(cursor.getString(cursor.getColumnIndex(COLUMN_SUBJECT_NAME)));
attendanceList.add(attendance);
cursor.moveToNext();
}
cursor.close();
db.close();
return attendanceList;
}
else
{
cursor.close();
db.close();
return null;
}
}
There is no syntax error in the above function, and I know it shouldn't return null because I see the content of the ATTENDANCE_TABLE using DB Browser for SQLite. Can someone point what is wrong with my code? I feel like I wrote 1 + 1 = 2 and getting an error..
Try this... SQLiteDbHelper is my DataBase Class where my table is defined. Table_Name is string in which my table name is stored
cursor = db.rawQuery("SELECT * FROM "+SQLiteDBHelper.TABLE_NAME+" WHERE "+SQLiteDBHelper.COLUMN_SURNAME+"=? AND "+SQLiteDBHelper.COLUMN_NAME+"=?",new String[] {surName,name});
if (cursor != null) {
if(cursor.getCount() > 0) {
cursor.moveToFirst();
//Retrieving User SurName and Name
String s_name = cursor.getString(cursor.getColumnIndex(SQLiteDBHelper.COLUMN_SURNAME));
String _name= cursor.getString(cursor.getColumnIndex(SQLiteDBHelper.COLUMN_NAME));
Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();
I am pretty sure that it not surName or name that causes NullpointerException, but dbHelper is.
So please check if you are initialising your dbHelper after this line
attendanceList = dbHelper.getAttendance(surName, name);
If so, then move it above and your crash will be fixed.
Hope it helps.

Exception Invalid Limit Clauses - Android

I am trying to put json object in sqlite database
private void addList(String info){
try {
JSONObject reader=new JSONObject(info);
String COMMAND = reader.getString("COMMAND");
String PARAMS = reader.getString("PARAMS");
int id = vpictures.InsertList(COMMAND,info);
} catch (Exception e){
if (DEBUG_FLAG)Log.d("Log1 ", "adding Exception :"+ e.getMessage());
}
return;
}
The json object info looks like this
{
"COMMAND":"ADD_NEW",
"PARAMS":{
"deviceID":"1234",
"custID":"41701",
"description":"Ddd",
"colTranType":"ABS",
}
}
This is my sqlite table
private static final String TABLE_CREATE = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER, DEVICEID TEXT, LTIME INTEGER, LATITUDE REAL,"+
"LONGITUDE REAL, THEPICTURE BLOB, SENT INTEGER, NOTES TEXT, COMMAND TEXT, PARAMS TEXT);";
I am trying to insert COMMAND and PARAMS.
And my sqlite code looks like this
public int InsertList(String COMMAND, String info){
try {
JSONObject reader = new JSONObject(info);
String param_str = reader.getString("info");
if (_Db == null)
_Db = getWritableDatabase();
if (_LastId == -1)
{
Cursor c = _Db.query(TABLE_NAME, new String[] {"max(ID)"}, null, null, null, null, COMMAND, param_str);
if (c != null && c.moveToFirst()) {
_LastId = c.getInt(0);
c.close();
}
else
_LastId = 0;
c.close();
}
try {
ContentValues cv = new ContentValues();
cv.put("ID",++_LastId);
cv.put("COMMAND",String.valueOf(COMMAND));
cv.put("PARAMS",PARAMS);
_Db.insert(TABLE_NAME, "", cv);
} catch (Exception e){
Log.d("Log2","Error:"+e.getMessage());
}
} catch (JSONException e1) {
Log.d("Log2","Error:"+e1.getMessage());
}
return _LastId;
}
Basically the exception i am getting from the addList function
adding Exception : Exception invalid LIMIT clauses
How to consider inserting json object into sqlite
These are the parameters of the query() method:
Cursor c = _Db.query(
TABLE_NAME, // table
new String[] {"max(ID)"}, // columns
null, // selection
null, // selectionArgs
null, // groupBy
null, // having
COMMAND, // orderBy
param_str); // limit
The orderBy and limit parameters do not make sense. To find the largest ID in the entire table, these parameters must be null.
Anyway, there is a helper function that makes it reasier to read a single number from the database without having to muck around with a cursor:
long lastID = DatabaseUtils.longForQuery(_Db, "SELECT max(ID) FROM "+TABLE_NAME, null);
And if you had declared the ID column as INTEGER PRIMARY KEY, it would be autoincremented, and you would not have to set it manually.

Cursor Exception during Async Task

I am running a background task that goes out and downloads a JSON file, pareses it, then adds it to the contents to a SQLite database.
I am getting a couple of errors when it runs.
Caused by: android.database.CursorWindowAllocationException: Cursor
window allocation of 2048 kb failed. # Open Cursors=728 (# cursors
opened by this proc=728)
E/CursorWindow: Could not allocate CursorWindow
'/data/data/com.mycompany.inventory/databases/dbInventory.sql' of size
2097152 due to error -12.
The JSON has about 1500 items in it.
Here is the method my async task calls:
public void addModelsToDB(JSONObject dict){
String insertQuery = "";
String deleteQuery = "DROP TABLE IF EXISTS 'tblModels'";
String createQuery = "CREATE TABLE 'tblModels' ('modelsID' INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,'makeKey' INTEGER, 'modelName' TEXT, 'modelKey' INTEGER)";
Cursor cursor = dbLocals.executeRawQuery(deleteQuery, null);
cursor.moveToFirst();
cursor = dbLocals.executeRawQuery(createQuery, null);
cursor.moveToFirst();
try {
JSONArray dicRecordSet = dict.getJSONArray("Recordset");
JSONObject dicRecords = dicRecordSet.getJSONObject(0);
JSONArray arrRecords = dicRecords.getJSONArray("Record");
for (int i = 0; i < arrRecords.length(); i++) {
JSONObject record = arrRecords.getJSONObject(i);
insertQuery = "INSERT INTO 'tblModels' VALUES(" + null + ", "
+ record.getString("MODMAKlMakeKey") + ", '"
+ record.getString("MODvc50Name").replaceAll("'", "''") + "', "
+ record.getString("MODlModelKey")
+")";
cursor = dbLocals.executeRawQuery(insertQuery, null);
cursor.moveToFirst();
}
} catch (JSONException e) {
e.printStackTrace();
}
cursor.close();
}
My database a manager returns a cursor.
public Cursor executeRawQuery(String query, String[] selectionArgs) {
Cursor cursor = databaseConn.rawQuery(query, selectionArgs);
return cursor;
}
What am I doing wrong?
You can't reuse the cursor variable because it shadows the original one, and therefore you can't close it:
Cursor cursor = dbLocals.executeRawQuery(deleteQuery, null);
then
cursor = dbLocals.executeRawQuery(insertQuery, null);
this second assignment means you can't close the original cursor.
Also, why are you creating the table here?
Edit:
Use it like this:
public void addModelsToDB(JSONObject dict){
String insertQuery = "";
String deleteQuery = "DROP TABLE IF EXISTS 'tblModels'";
String createQuery = "CREATE TABLE 'tblModels' ('modelsID' INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,'makeKey' INTEGER, 'modelName' TEXT, 'modelKey' INTEGER)";
Cursor cursor = dbLocals.executeRawQuery(deleteQuery, null);
try {
cursor.moveToFirst();
cursor = dbLocals.executeRawQuery(createQuery, null);
cursor.moveToFirst();
} finally {
cursor.close();
}
try {
JSONArray dicRecordSet = dict.getJSONArray("Recordset");
JSONObject dicRecords = dicRecordSet.getJSONObject(0);
JSONArray arrRecords = dicRecords.getJSONArray("Record");
for (int i = 0; i < arrRecords.length(); i++) {
JSONObject record = arrRecords.getJSONObject(i);
insertQuery = "INSERT INTO 'tblModels' VALUES(" + null + ", "
+ record.getString("MODMAKlMakeKey") + ", '"
+ record.getString("MODvc50Name").replaceAll("'", "''") + "', "
+ record.getString("MODlModelKey")
+")";
cursor = dbLocals.executeRawQuery(insertQuery, null);
try {
cursor.moveToFirst();
} finally {
cursor.close();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
You should close cursors after using them. Inside the loop, you are creating a cursor every iteration, without ever closing it. Apparently there is a limit for the number of open cursors and you hit that limit.

Android: Get entire column data

Im trying to get the data of an entire column into a string array. My database contains two columns Id and Names. I want to read all the entries of the names column and put it into a array. Please help.
EDIT #1:
Im using the following code but i can get only one name with this code.
String query = "Select * FROM " + TABLE_APPS + " WHERE " + COLUMN_NAME + " = \"" + productname + "\"";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
cursor.moveToFirst();
name = cursor.getString(1);
cursor.close();
} else {
name = null;
}
db.close();
int total=0;
Cursor csr=sdb.query("tablename", null, null,null,null,null,null);
csr.moveToFirst();
while(!csr.isAfterLast())
{
total++;
csr.moveToNext();
}
String strarray[] = new String[total];
Cursor csrs=sdb.query("tablename", null, null,null,null,null,null);
csrs.moveToFirst();
int aray=0;
while(!csrs.isAfterLast())
{
strarray[aray]=csrs.getString(1);
aray++;
csrs.moveToNext();
}

Categories

Resources