Can´t select first row in table - android

I have table subject, when I try the query in adb shell the output is OK
SELECT * FROM subject;
The output is 10 rows...
When I do the same in Java/Android:
public ArrayList<Subject> getSubjectList() {
SQLiteDatabase db = DatabaseManager.getInstance().openDatabase();
ArrayList<Subject> subjects = new ArrayList<Subject>();
String selectQuery = "SELECT * FROM subject";
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
while (cursor.moveToNext()) {
Subject subject = new Subject();
subject.setId_subject(Integer.parseInt(cursor.getString(0)));
subject.setName(cursor.getString(1));
subjects.add(subject);
}
}
cursor.close();
DatabaseManager.getInstance().closeDatabase();
return subjects;
}
The output is 9 rows... the first row with id 1 will not display, why?

Because you move to the next (moveToNext()) row immediately after moving on the first one (moveToFirst())...
What i normally do is something like this:
if (cursor != null)
{
if (cursor.moveToFirst())
{
do
{
// ...
}
while (cursor.moveToNext());
}
}

Because on entering the if statement, you moveToFirst(), then on the first entry to the while loop, you .moveToNext(). Meaning you skip the first record.
So use a do... while() construct instead:
if (cursor.moveToFirst()) {
do {
Subject subject = new Subject();
subject.setId_subject(Integer.parseInt(cursor.getString(0)));
subject.setName(cursor.getString(1));
subjects.add(subject);
}while (cursor.moveToNext())
}
Reference: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html

Related

android show random data

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

Fetch data from Sqlite database

I am creating app in which i register user and store user's information in database,so i have created database and storing value in databse but i don't know how to fetch data from database and show in textview?Using below query to fetch data but it has error.What is correct way?
public void insertEntry(String fname, String lname, String gen,String weight)
{
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("firstname", fname);
values.put("lastname", lname);
values.put("gender", gen);
values.put("weight",weight);
}
public Cursor fetchData()
{
SQLiteDatabase mDB = dbHelper.getWritableDatabase();
return mDB.rawQuery("SELECT * FROM Register WHERE firstname=? lastname =?" , null);
}
Using this to set fetched value on textview in different activity
Cursor name = sqliteDataBase.fetchData();
tv_name.setText((CharSequence) name);
Try this,
try {
SQLiteDatabase mDB = dbHelper.getReadableDatabase();
String selectQuery = "SELECT * FROM Register WHERE firstname= "+first+" lastname =" + last + ";";
cursor = db.rawQuery(selectQuery, null);
if (cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
String firstName = cursor.getString(cursor.getColumnIndex("firstname")));
}
}
} catch(Exception e) {
e.printSTackTrace();
} finally {
if (cursor != null) {
cursor.close();
}
}
public String fecthResults()
{
String name = null;
SQLiteDatabase sqLiteDatabase = getReadableDatabase();
Cursor cursor = sqLiteDatabase.query(TABLE_NAME, null, null, null, null, null, null);
if (cursor.moveToFirst()) {
do {
name = cursor.getString(cursor.getColumnIndex("firstname")
} while (cursor.moveToNext());
cursor.close();
}
sqLiteDatabase.close();
return name;
Get the name and then set it directly to a texView
A Cursor is an interface that provides random read-write access to the result set returned by the query. It contains multiple rows of data and this data can be easily processed by help of For loop.
Lets take an example to understand the process. Suppose, you need to access data from a column name "col_1" and show the data in TextView. The For loop for the process will be as follows.
for (cursor.moveToNext()) {
textView.setText(cursor.getString(cursor.getColumnIndex("col_1")));
}
Now, if we need only one value (from only one record or tuple) then, we can opt out the For loop and change the code as shown below.
if (cursor.moveToFirst()) {
textView.setText(cursor.getString(cursor.getColumnIndex("col_1")));
}
Always remember to close the cursor after using it.
To close the cursor, use the following line of code.
cursor.close();
For more information, please visit the following links:
https://developer.android.com/reference/android/database/Cursor.html
https://developer.android.com/training/basics/data-storage/databases.html#ReadDbRow

How to store database column in ArrayList in android?

Here I want to store data in ArrayList visible Sections please help me...
Here's my code.
public DataSingleton() {
try {
db = openOrCreateDatabase("/sdcard/Download/Nanhikali_db.db", Context.MODE_PRIVATE, null);
Cursor c = db.rawQuery("select label from nanhikali where level = 1", null);
if (c.moveToFirst()) {
while (c.moveToNext()) {
String lb = c.getString(c.getColumnIndex("label"));
visibleSections.add(lb);
visibleSections = new ArrayList<>();
}
}
}
catch(Exception e)
{
}
Your column string maybe wrong:
Try like this.
if(c.moveToFirst()){
while(c.moveToNext()){
String lb = c.getString(c.getColumnIndex("label"));
visibleSections.add(lb);
}
}
Not "lebel".
You are re assigning the array list every time your loop iterates.
remove visibleSections = new ArrayList<>(); from your loop.
and use While Loop as
while(!cursor.isAfterLast())
{
//get All data here then
cursor.moveToNext();
}

select from db in sqlite database

what is wrong with this code
when i run it the program don,t response
public Cursor checkauth(String username,String password)
{
Ecommerce=getReadableDatabase();
// Cursor curser =Ecommerce.rawQuery("select * from customer where username = ? and password =?", new String []{username,password});
//String [] details={"id","custname","gender"};
Cursor c = Ecommerce.rawQuery("select id from customer where username = ? AND password = ?" , new String[] {username,password });
//Cursor cursor = Ecommerce.query(true, "customer",details,"username = ? AND password = ?", new String[] { username, password },null, null, null, null, null);
while(c != null)
{
c.moveToFirst();
}
return c;
}
in activity
public void onClick(View arg0) {
// TODO Auto-generated method stub
user_name=username.getText().toString();
passwords=password.getText().toString();
Cursor c=data.checkauth(user_name, passwords);
while(!c.isAfterLast())
{
username.setText(String.valueOf(c.getInt(0)));
c.moveToNext();
}
}
![enter image description here][1]
You're blocking your UI thread.
This loop never completes:
while(c != null)
{
c.moveToFirst();
}
The while condition is always true. The loop doesn't seem to be doing anything useful, you can probably just leave a plain c.moveToFirst() there.
Try with this..
String selectQuery = "Write select query" ;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
boolean result = false;
if (cursor.moveToFirst())
{
do
{
result = true;
} while (cursor.moveToNext());
}
else
{
result = false;
}
Even though this question is answered already, I'd like to suggest a simple improvement. What you're doing is kind of useless. Your goal is to know whether or not a user exists and what his or her id is.
public int checkAuth(String username, String password) {
String sql = "select id from customer where username = ? AND password = ?";
Ecommerce = getReadableDatabase(); //field names never start with uppercase
Cursor c;
try {
c = Ecommerce.rawQuery(sql, new String[] { username, password });
if (c.moveToFirst()) //if the cursor has any records, this returns true, else false
return c.getInt(0); //so if a user exists with given params, we can return an id
else
return -1; //if not, we return -1, which means: user/pass-combination not found
}
finally { //but after the whole method, we need to do some things:
if (c != null && !c.isClosed())
c.close(); //close the cursor
closeDatabase(); //and close the database
}
}
This way you keep your UI code separated from your database code. A cursor shouldn't appear in UI-code. Which above modifications, the UI code looks a lot cleaner
int i = data.checkAuth(username, password);
if (i == -1) {
//alert of some kind
}
else
username.setText(String.valueOf(i));

I can't get data from Cursor Object

I've following table structure in my SQLite Database.
In my SqliteOpenHelper class, I wrote following method.
public Form getAllForms(){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from "+FORM_TABLE, null);
int count = cursor.getCount();
String formID = cursor.getString(0);
Form form = new Form();
form.setId(formID);
cursor.close();
db.close();
return form;
}
I'm sure there's some data in it because I already watched count in debugging mode and I saw the quantity of row that actually existing in database. But CursorIndexOutOfBoundException shows up at cursor.getString(0). plus cursor.getInt(0) and cursor.getString(1) didn't work also. What's the problem might be?
You need to move the cursor to a valid row.
Valid rows are indexed from 0 to count-1. At first the cursor will point to row index -1 i.e. the one just before the first row.
The canonical way of looping through all rows is
if (cursor.moveToFirst()) {
do {
// now access cursor columns
} while (cursor.moveToNext());
}
Try this
try {
cursor.moveToFirst();
for (int i = 0; i < cursor.getCount(); i++) {
Form form = new Form();
form.setId(formID);
cursor.moveToNext();
}
} finally {
// database.close();
cursor.close();
dbHelper.close();
}
You need to call moveToFirst() to get to the first row before asking for values:
if ((cursor!= null) && (cursor.getCount() > 0)) {
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
}
So Simply use your code as
public Form getAllForms(){
Form form = new Form();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from "+FORM_TABLE, null);
if ((cursor != null) && (cursor.getCount() > 0)) {
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
String formID = cursor.getString(0);
form.setId(formID);
cursor.moveToNext();
}
cursor.close();
}
db.close();
return form;
}

Categories

Resources