Using following query to get column data:
public String getR(String str) {
String strR = "SELECT col_no FROM tracking where col_id = '"+str+"' ORDER BY col_no DESC LIMIT 1";
return strR;
}
In Activity, I am trying to read returned strR :
String string = mydb.getR("1400");
Toast.makeText(SyncAll.this, string, Toast.LENGTH_SHORT).show();
But in Toast, I am getting my Select query itself instead of Record, like this:
SELECT col_no FROM tracking where col_id = '1400' ORDER BY col_no DESC LIMIT 1
May I know ! Where I am doing mistake ?
I tried the same way suggested by prosper k above, and finally got the solution:
public String getR(String str) {
String strR = "SELECT col_no FROM tracking where col_id = '"+str+"' ORDER BY col_no DESC LIMIT 1";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(strR, null);
if (cursor != null)
cursor.moveToFirst();
strR = cursor.getString(0);
return strR;
}
You're calling the function getR, which is returning the string value strR.
I'm assuming that mydb is an extended object from class SQLiteOpenHelper, and that you have followed the documentation here https://developer.android.com/training/basics/data-storage/databases.html then you'll have to execute the query like:
Cursor cursor = null;
try {
SQLiteDatabase db = this.getWritableDatabase();
synchronized(this) {
cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
col_no = cursor.getInt(0);
}
}
} finally {
if (null != cursor)
cursor.close();
}
return col_no;
Related
I have some data from the database that I want to show randomly and only 5 data appear, I've tried using ORDER BY RAND () but the app crashes when I open it
below is my syntax query
public List<Soal> getSoal(){
List<Soal> listSoal = new ArrayList<Soal>();
String query = "select * from tbl_soal ORDER BY RAND() LIMIT 5";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(query, null);
if(cursor.moveToFirst()){
do{
Soal s = new Soal();
s.setSoal(cursor.getString(1));
s.setPil_a(cursor.getString(2));
s.setPil_b(cursor.getString(3));
s.setPil_c(cursor.getString(4));
s.setPil_d(cursor.getString(5));
s.setJwban(cursor.getInt(6));
s.setGambar(cursor.getInt(7));
listSoal.add(s);
}while(cursor.moveToNext());
}
return listSoal;
}
so where is the error, or is there any solution for my problem ?
You can check this answer as well
https://stackoverflow.com/a/23628508/6672577
public List<Soal> getSoal() {
List<Soal> listSoal = new ArrayList<Soal>();
String query = "SELECT * FROM table ORDER BY RANDOM() LIMIT 5";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(query, null);
if (cursor != null) { // To check that cursor is not null.
if (cursor.moveToFirst()) {
do {
Soal s = new Soal();
s.setSoal(cursor.getString(1));
s.setPil_a(cursor.getString(2));
s.setPil_b(cursor.getString(3));
s.setPil_c(cursor.getString(4));
s.setPil_d(cursor.getString(5));
s.setJwban(cursor.getInt(6));
s.setGambar(cursor.getInt(7));
listSoal.add(s);
} while (cursor.moveToNext());
}
}
return listSoal;
}
I'm writing an app that manipulates with database consists of 3 tables. I created this database from json file using models (Worker model, specialty model) with getters and setters. Now I want to get specific info from this database. I'v already made it but my code is pretty silly. What I need is to change the architecture of my app but I don't know how exactly it should looks like.
This is the examples of my methods, and they are pretty week
This is how I add info into database. I like it, I think it's correct:
public void addWorker(Worker worker){
List<Specialty> specialty;
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
//fixind names
String f_name = fixName(worker.getF_name());
String l_name = fixName(worker.getL_name());
String birthday = fixDate(worker.getBirthday());
values.put(KEY_F_NAME, f_name);
values.put(KEY_L_NAME, l_name);
values.put(KEY_BIRTHDAY, birthday);
values.put(KEY_AVATR_URL, worker.getAvart_url());
specialty = worker.getSpecialty();
long worker_id = db.insert(TABLE_WORKERS,null,values);
//add unique specialty
for (Specialty spec: specialty){
createRelations(worker_id, spec.getSpecialty_id());
if (getCount(spec.getSpecialty_id()) == 0){
addSpecialty(spec);
}
}
}
And this is how I take info from database:
public String[] getFullInfo(String worker_name){
String selectQuery = "HUGE QUERY HERE "where workers.f_name =?";
Log.e(LOG_TAG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, new String [] {worker_name});
String[] details = new String[5];
c.moveToFirst();
while (c.isAfterLast() == false){
details[0] = c.getString(c.getColumnIndex(KEY_F_NAME));
details[1] = c.getString(c.getColumnIndex(KEY_L_NAME));
details[2] = c.getString(c.getColumnIndex(KEY_BIRTHDAY));
details[3] = c.getString(c.getColumnIndex("age"));
details[4] = c.getString(c.getColumnIndex(KEY_SPEC_NAME));
c.moveToNext();
}
return details;
}
This is my another query and it has different return type:
public List<Map<String ,String>> getWorkerListBySpec(String spec_name){
String selectQuery = "HUGE QUERY HERE
"where specialty.spec_name=?";
Log.e(LOG_TAG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, new String [] {spec_name});
//making list of workers
List<Map<String ,String>> data = new ArrayList<Map<String,String>>();
c.moveToFirst();
while (c.isAfterLast() == false){
Map<String,String> datum = new HashMap<String,String>(2);
datum.put(KEY_F_NAME, c.getString(c.getColumnIndex(KEY_F_NAME)));
datum.put(KEY_L_NAME, c.getString(c.getColumnIndex(KEY_L_NAME)));
datum.put(KEY_BIRTHDAY, c.getString(c.getColumnIndex(KEY_BIRTHDAY)));
data.add(datum);
c.moveToNext();
}
return data;
}
and the third one, which also have different return type:
public List<String> getAllSpecs_Names(){
List<String> spec_names = new ArrayList<String>();
String selectQuery = "select * from " + TABLE_SPECIALTY;
Log.e(LOG_TAG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
if (c.moveToFirst()){
do{
spec_names.add(c.getString(c.getColumnIndex(KEY_SPEC_NAME)));
}while (c.moveToNext());
}
return spec_names;
}
I know, that this is all wrong.
Please tell me how I should make all my queries.
It will be good if you give me the link to check how the app should look like
instead of returning a List or Map, you should better return a own CursorWrapper
so you could could look like this:
public WorkerCursor getWorkerListBySpec(String spec_name){
String selectQuery = "HUGE QUERY HERE
"where specialty.spec_name=?";
Log.e(LOG_TAG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, new String [] {spec_name});
return new WorkerCursor(cursor);
}
public static class WorkerCursor extends CursorWrapper {
/**
* Creates a cursor wrapper.
*
* #param cursor The underlying cursor to wrap.
*/
public WorkerCursor(Cursor cursor) {
super(cursor);
}
public Worker getWorker() {
return getWorkerAtCursor();
}
public Worker getWorker(int position) {
if (moveToPosition(position)) {
return getWorkerCursor();
} else {
return null;
}
}
private Worker getWorkerAtCursor() {
if (isBeforeFirst() || isAfterLast()) {
return null;
}
worker worker = new Worker();
worker.name = c.getString(c.getColumnIndex(KEY_F_NAME));
....
return worker;
}
}
and the same for your List, just with a other CursorWrapper
and don't forget to close the CursorWrapper, when it's no more needed, like in onDestroy of Activity and so
I'm not too sure whether it's appropriate that using 'username' as my selection to retrieve other data instead of using an id. FYI, my username is unique as there will not be any other user having the same username. I'm doing this way because I'm not sure how to use or call the id from the table.
I'm getting this error:
CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1
I have a DatabaseAdapter.java with this code:
public Cursor getData(String username){
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cur = db.query(TABLE_PROFILE, COLUMNS_PROFILE, " username=?", new String[]{username}, null, null, null, null );
if (cur != null){
cur.moveToFirst();
}
return cur;
}
With a EditProfileFragment.java:
dbAdapter = new DatabaseAdapter(getActivity());
dbAdapter = dbAdapter.open();
un = getArguments().getString("username");
Cursor cur = dbAdapter.getData(un);
String password = cur.getString(cur.getColumnIndexOrThrow(DatabaseAdapter.KEY_PASSWORD));
String age = cur.getString(cur.getColumnIndexOrThrow(DatabaseAdapter.KEY_AGE));
String weight = cur.getString(cur.getColumnIndexOrThrow(DatabaseAdapter.KEY_WEIGHT));
String height = cur.getString(cur.getColumnIndexOrThrow(DatabaseAdapter.KEY_HEIGHT));
String gender= cur.getString(cur.getColumnIndexOrThrow(DatabaseAdapter.KEY_GENDER));
I'm getting the String un in my log, means my username is successfully passed. I'm blur with the data retrieving data from the cursor, please help and thank you in advance for the help.
Try this Answer
public Cursor getData(String username){
SQLiteDatabase db = dbHelper.getReadableDatabase();
String sql="select * from " + tableName + " where username =?";
Cursor cursor=database.rawQuery(sql,new String{username});
if (cursor != null)
{ cursor.moveToFirst();}
return cursor;
}
Hope this will help you
Here is small piece of code.Here i am verifying if user exist or not based on username/email and password.I know it is not complete solution but can guide you in right direction (somehow).
public boolean verifyLogin(String email,String password)
{
Cursor mCursor = ourDatabase.rawQuery("SELECT * FROM " + DATABASE_TABLE_USERS + " WHERE Email=? AND Password=?", new String[]{email,password});
if (mCursor != null)
{
if(mCursor.getCount() > 0)
{
return true;
}
}
return false;
}
EditText username;
String S;
S = username.getText().toString();
now run this query
String selectQuery = "SELECT* FROM **TABLE NAME** WHERE username=S ";
Cursor c = db.rawQuery(selectQuery, new String[] { username });
if (c.moveToFirst()) {
temp_address = c.getString(0);
}
c.close();
String name;
name = username.getText().toString();
"select * from yourTable where username= '"+name+"'"
Run this query. I hope it will help you ..!
I am new with android.
I just wanted to take the count of number of rows in table against particular user in DB (uid is column in db).
For this purpose i made following function:
public int getCount(int uid)
{
String query = "select count(*) from "+TABLE_MESSAGES+ " WHERE uid=?";
Cursor c = ourDB.rawQuery(query,uid);
}
But its giving me error:
The method rawQuery(String, String[]) in the type SQLiteDatabase is
not applicable for the arguments (String, int)
also want to know how can i be able to return count from this?
Please help me.
you should use this WAY:
public int getCount(int uid)
{
String query = "select count(*) from "+TABLE_MESSAGES+ " WHERE uid="+uid+"";
Cursor c = ourDB.rawQuery(query,null);
if(c.getCount()>0)
c.moveToFirst();
do{
int id = c.getInt(0);
}while(c.moveToNext());
}
Try this way
public int getCount(int uid){
try{
String query = "select count(*)'count' from "+TABLE_MESSAGES+ " WHERE uid="+uid+"";
Cursor c = ourDB.rawQuery(query,null);
if (c.moveToFirst()) {
return Integer.parseInt(cursor.getString(0));
}
}catch (Throwable e) {
e.printStackTrace();
}
return 0;
}
change your query to:
String query = "select count(*) from "+TABLE_MESSAGES+ " WHERE uid="+uid;
Cursor c = ourDB.rawQuery(query);
The method rawQuery(String, String[]) in the type SQLiteDatabase is
not applicable for the arguments (String, int)
Clearly states you are passing int instead of expected String[]
Cursor c = ourDB.rawQuery(query,new String[]{ uid });
use the query as :
"SELECT * FROM <DB_NAME> WHERE uid="+uid
and then use the getCount() method on the cursor
like :
Cursor csr = db.rawQuery("above query string here");
int count = csr.getCount();
I am getting cursor index out of bounds "index 0 requested: with size 0" error when I search my database for something. The item I am searching for in my database does not exist currently and i am aware of that but how do i handle a query where the item does not exist.
i send in a phone number
public String searchNumber(Context context,String number){
ContactDB db = new ContactDB(context);
db.open();
Cursor curs = db.getIdFromPhone(number);
String test = curs.getString(curs.getColumnIndex(db.PHONE_NUMBER)); //fails here
curs.close();
db.close();
return test;
}
query
public Cursor getIdFromPhone(String where){
Cursor cur = db.query(DATABASE_TABLE, new String [] {ID,PHONE_NUMBER}
, PHONE_NUMBER + "='" + where + "'",null,null,null,null);
if(cur != null)
cur.moveToFirst();
return cur;
}
test search
from = messages.getDisplayOriginatingAddress();
String dbNumber = searchNumber(arg0,from);
if(dbNumber.equals(from)){
//do stuff
}else{
//do other stuff
}
if number is not found it should do the else statement but it does not get that far
Cursor.moveToFirst() returns false if the Cursor is empty. The returned Cursor from the query() call will never be null but it might be empty. You are never checking if the cursor is empty.
public String searchNumber(Context context,String number){
ContactDB db = new ContactDB(context);
db.open();
Cursor curs = db.query(DATABASE_TABLE, new String [] {ID,PHONE_NUMBER}
, PHONE_NUMBER + "='" + number + "'",null,null,null,null);
String test = null;
if(curs.moveToFirst()) { //edit
test = curs.getString(curs.getColumnIndex(db.PHONE_NUMBER)); //fails here
}
curs.close();
db.close();
return test; // this will be null if the cursor is empty
}
And get rid of the getIdFromPhone() method.
While you retrive value you have to use cursor.moveToNext;
if (cursor.moveToFirst()){
do{
String data = cursor.getString(cursor.getColumnIndex("data"));
// do what ever you want here
}while(cursor.moveToNext());
}