Getting Exception Index 1 requested, with a size of 1 - java

I am getting exception while fetching data from database in my android project. I am trying to get value of column index 1 from this line of code String ques=c.getString(1);
And this is the code where i am calling database class and trying to fetch database,
try{
c=db.getText(Integer.toString(subid));
if(c==null)
return;
//if(c.getCount()> 0)
//{
//int max=c.getCount();
//int min=0;
Random rn = new Random();
int randomNum = rn.nextInt(max-1) + rowid;
c.moveToPosition(randomNum);
String ques=c.getString(1);
tv.setText(ques+" ");
cans=c.getString(2);
shuffleArray(ans);
int[] a = new int[4];
int j=0;
for (int i = 0; i < ans.length; i++)
{
a[j]=ans[i];
j++;
}
ans1=c.getString(a[0]);
ans2=c.getString(a[1]);
ans3=c.getString(a[2]);
ans4=c.getString(a[3]);
rb1.setText(ans1);
rb2.setText(ans2);
rb3.setText(ans3);
rb4.setText(ans4);
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), e.getMessage()+"exception", Toast.LENGTH_LONG).show();
}
Snap shot of my database content,
this is my database class,
public Cursor getText(String subId) throws SQLException //here it'll get all rows of subId=1 or whatever the value of subId
{
Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] {
KEY_id, KEY_ques, KEY_correctans, KEY_wrongans1,KEY_wrongans2, KEY_wrongans3},
KEY_subjectid + "=" + " '" + subId + "' " , null,null,null, null,null);
if (mCursor != null)
{
mCursor.moveToFirst();
}
return mCursor;
}
Please help me and hope my question is clear.
Thanks in Advance.

You have an error:
Index 1 requested, with a size of 1
It says, that the size of your cursor is 1 and you know that indexing starts with 0. Therefore, if you write:
String ques = c.getString(1);
you try to get SECOND element, not the first one. If you want to get first element, you have to write:
String ques = c.getString(0);

Remove c.MovetoPosition(randomno);
Instead try this:
c.moveToFirst();
int rw_cnt=c.getCount();
int rndm = ((Math.random())*10000)%rw_cnt); //generates a random no btwn 1 and rw_cnt
for(int i=0;i<rndm;i++) //move cursor rand times
c.moveToNext();
This definitely would be slower than c.moveToPostion(); but it wouldn't make much of a difference unless you have thousands of rows

Related

SQLite Check if column exist or not

I want to check columns (not value) at agregasi table, if columns exist do something, but if columns does not exist show/print message 'Column does not exist'.
I could run code below while columns exist:
String keywords1={'pesawat','terbang'};
String sql1 = "SELECT " + keywords + " FROM agregasi"; //columns exist at agregasi table
Cursor c1 = myDbHelper.rawQuery(sql1, null);
if (c1.moveToFirst()) {
// i can do something (no problem)
}
But i have problem when columns name i change on purpose (to check). What should i do to print error message (in android/java way)?
**String keywords2={'psawat','terang'};**
String sql2 = "SELECT " + keywords + " FROM agregasi"; //columns does not exist at table
Cursor c2 = myDbHelper.rawQuery(sql2, null);
// what should i do get error message and show/print using toast
You're looking for getColumnIndex(String columnName).
int index = c2.getColumnIndex("someColumnName");
if (index == -1) {
// Column doesn't exist
} else {
...
}
Here's a general method you can use to check whether a particular column exists in a particular table:
public boolean isColumnExists(SQLiteDatabase sqliteDatabase,
String tableName,
String columnToFind) {
Cursor cursor = null;
try {
cursor = sqLiteDatabase.rawQuery(
"PRAGMA table_info(" + tableName + ")",
null
);
int nameColumnIndex = cursor.getColumnIndexOrThrow("name");
while (cursor.moveToNext()) {
String name = cursor.getString(nameColumnIndex);
if (name.equals(columnToFind)) {
return true;
}
}
return false;
} finally {
if (cursor != null) {
cursor.close();
}
}
}
Try this it works fine :)
Cursor res = db.rawQuery("PRAGMA table_info("+tableName+")",null);
int value = res.getColumnIndex(fieldName);

Saving SQLite list as an array: Not Working [duplicate]

This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 7 years ago.
I have an SQLite Database, and within it, one of the columns stores Strings which include numbers. I am trying to retrieve the numbers, store them as doubles in an array, and then take the mean of the array. However, it's not working. The App crashes every time I get to that part. I know the problem has to be somewhere within the array because I am able to list the SQLite Database as a string.
public int getDataCount() {
String countQuery = "SELECT * FROM " + TABLE_PRODUCTS + " WHERE 1";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int cnt = cursor.getCount();
cursor.close();
return cnt;
}
public double databaseAverage(){
String dbString = "";
int dbInt = 0;
double dbDouble = 0;
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_PRODUCTS + " WHERE 1";
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
int rowCount = getDataCount();
Double[] array = new Double[rowCount];
int i = 0;
while (!c.isAfterLast()) {
if (c.getString(c.getColumnIndex("productname")) != null) {
dbString += c.getString(c.getColumnIndex("productname"));
dbInt = Integer.parseInt(dbString.replaceAll("[\\D]",""));
dbDouble = (double) dbInt;
array[i] = dbDouble;
i++;
}
c.moveToNext();
}
db.close();
double sum = 0;
for(int v=0; v < array.length ; v++) {
sum = sum + array[i];
}
double average = sum / array.length;
return average;
}
please check your syntax :
String query = "SELECT * FROM " + TABLE_PRODUCTS + " WHERE 1";
While it should be :
String query = "SELECT * FROM " + TABLE_PRODUCTS + " WHERE "+ {your coloumn name }+"=1";
Check above query in both methode getDataCount and databaseAverage

Getting SQLite DB data in 2d array and returning in android

I have the below function which I use to query the SQLite Db, put the retrieved records in to an array and return it back.
public String[][] getrecords(){
Log.i("SENDSERVER", "Get Records Called");
SQLiteDatabase sampleDB = this.getReadableDatabase();
Cursor c = sampleDB.rawQuery("SELECT id,welawa,lati,longi FROM " +
TABLE_LOCATIONS + " LIMIT 5", null);
String[][] aryDB = new String[5][4];
int i = 0;
if (c != null ) {
if (c.moveToFirst()) {
do {
String db_id = c.getString(c.getColumnIndex("id"));
String welawa = c.getString(c.getColumnIndex("welawa"));
String latitude = c.getString(c.getColumnIndex("lati"));
String longitude = c.getString(c.getColumnIndex("longi"));
aryDB[i][0] = db_id;
aryDB[i][1] = welawa;
aryDB[i][2] = latitude;
aryDB[i][3] = longitude;
Log.i("SENDSERVER", "Record Added"); //This doesn't get logged
i++;
}while (c.moveToNext());
}
}
Log.i("SENDSERVER", "Return Records");
return aryDB;
}
I try to retrieve the records and use them as below from my service class.
String aryDB[][] = dbh.getrecords();
Log.i("SENDSERVER", "GET DB RECORDS");
int i = 0;
int id = 0;
String welawa = "";
String lati = "";
String longi = "";
while(i < 5){
id = Integer.parseInt(aryDB[i][0]);
welawa = aryDB[i][1];
lati = aryDB[i][2];
longi = aryDB[i][3];
Log.i("SENDSERVERDB", id + " - " + welawa + " - " + lati + " - " + longi);
i++;
}
For some reason the array is not being returned.
My possible guesses are,
1. The defining of the function is wrong. My intention is to return the array.
2. I am getting the db connection / my retrieval code is wrong.
3. Some thing else that my noob brain can't comprehend.
Your help is greatly appreciated guys.
------EDIT
After adding some more logs the app crashes at
Cursor c = sampleDB.rawQuery("SELECT id,welawa,lati,longi FROM " +
TABLE_LOCATIONS + " LIMIT 5", null);
Any issue in my query?
It was a DB issue. Wrong ColumnName used.
The Cursor never returns null when there is no row which the requested conditions, just return a empty Cursor.
You code still has problem when the rawQuery returns 0 rows, cursor won't be null and do while loop will execute at least once.
So there will be problem on this line when the cursor is empty
c.getString(c.getColumnIndex("id"));
Change your code to this:
c.moveToFirst();
while (c.moveToNext())
{
String db_id = c.getString(c.getColumnIndex("id"));
String welawa = c.getString(c.getColumnIndex("welawa"));
String latitude = c.getString(c.getColumnIndex("lati"));
String longitude = c.getString(c.getColumnIndex("longi"));
aryDB[i][0] = db_id;
aryDB[i][1] = welawa;
aryDB[i][2] = latitude;
aryDB[i][3] = longitude;
Log.i("SENDSERVER", "Record Added"); //This doesn't get logged
i++;
}

Getting Exception Index 50 requested, with a size of 50

I am getting exception while fetching data from database. I am trying to get value of column index 1 from this line of code String ques=c.getString(1);
this is the code where i am calling database class and trying to fetch database,
try{
c=db.getText(Integer.toString(subid));
if(c==null)
return;
//if(c.getCount()> 0)
//{
//int max=c.getCount();
//int min=0;
Random rn = new Random();
int randomNum = rn.nextInt(max-1) + rowid;
c.moveToPosition(randomNum);
String ques=c.getString(1);
tv.setText(ques+" ");
cans=c.getString(2);
shuffleArray(ans);
int[] a = new int[4];
int j=0;
for (int i = 0; i < ans.length; i++)
{
a[j]=ans[i];
j++;
}
ans1=c.getString(a[0]);
ans2=c.getString(a[1]);
ans3=c.getString(a[2]);
ans4=c.getString(a[3]);
rb1.setText(ans1);
rb2.setText(ans2);
rb3.setText(ans3);
rb4.setText(ans4);
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), e.getMessage()+"exception", Toast.LENGTH_LONG).show();
}
Snap shot of my database content,
And this is my database class,
public Cursor getText(String subId) throws SQLException //here it'll get all rows of subId=1 or whatever the value of subId
{
Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] {
KEY_id, KEY_ques, KEY_correctans, KEY_wrongans1,KEY_wrongans2, KEY_wrongans3},
KEY_subjectid + "=" + " '" + subId + "' " , null,null,null, null,null);
if (mCursor != null)
{
mCursor.moveToFirst();
}
return mCursor;
}
As my above details and code, When the value of subId is 1 then it is fetching all the content from the database of subId 1 without any Exception but when i am passing the value of subId=2 then it give CursorIndexOutOfBound: Index 50 requested, with a size of 50 Exception
And when i am passing subId=3 then i am getting Index 49 requested, with a size of 49
Is there any problem in Random number generator or what ?
Actually i am not able to get whats the problem here.
I need help.
Thanks in Advance.
Use space in query " = " actually your column name become "KEY_subjectid=" which is wrong
KEY_subjectid + " =" + " '" + subId + "' " , null,null,null, null,null);
Try generating your random number this way: (I'm assuming c is a Cursor)
int randomNum = rowid + (rn.nextInt() % (c.getCount() - rowid));
Hope this helps :)

How I can return query result from Server to Client

I have a webservice where from the Client-side some parameters are passed to perform a query on the DB, the Server-Side is supposed to carry out the query and return the results.Since the result might be more than one row and i will have to use it on the client-side to show an output this what i did:
1.Perform the query
2.take each row of the result and put it in an array
3.convert the array to String and pass it to the client side(converted array to String, because it was simple)
BUT the problem is that it doesnt pass the the array-turned-string but only the value which was used to initialize the string, here is the code
String ris = "";
String q;
String beta = null;
String one="";
String errore = connetti();
try {
if (errore.equals("")) {
Statement st = conn.createStatement();
//ESECUZIONE QUERY
q = "SELECT DISTINCT nome FROM malattia WHERE eta='" + age + "' AND sesso='" + sexstr + "' AND etnia='" + etniastr + "' AND sintomi IN(" + tes + ")";
ResultSet rs = st.executeQuery(q);
if (!rs.last()) {
ris = "no";
}
//This is the part which i'm talking about
else {
//getRowCount is another class used to find out number of rows,I use it to declare an array which would contain the result of the query
int two=getRowCount(rs);
String[] alpha= new String[two];
//Loop through the resultstatement and put result from the column **nome** in the array **alpha**
while(rs.next()){
alpha[i]=rs.getString("nome");
i++;
}
//The value of ris which is empty, is returned
ris="";
//instead of this one, where i convert the array **alpha** to String
ris=arrayToString(alpha,",");
}
}
else {
ris = errore;
}
conn.close();
} catch (Exception e) {
ris = e.toString();
}
return ris;
}
//returns the number of rows of **ris**
public static int getRowCount(ResultSet set) throws SQLException
{
int rowCount;
int currentRow = set.getRow(); // Get current row
rowCount = set.last() ? set.getRow() : 0; // Determine number of rows
if (currentRow == 0) // If there was no current row
set.beforeFirst(); // We want next() to go to first row
else // If there WAS a current row
set.absolute(currentRow); // Restore it
return rowCount;
}
//converts the array to String
public String arrayToString(String[] array, String delimiter) {
StringBuilder arTostr = new StringBuilder();
if (array.length > 0) {
arTostr.append(array[0]);
for (int i=1; i<array.length; i++) {
arTostr.append(delimiter);
arTostr.append(array[i]);
}
}
return arTostr.toString();
Thanks alot in advance!
After conn.close() you return beta instead of ris. This may be the cause of the behavior you are experiencing. However, I am not sure because I can not properly see how you open and close the curly brackets.

Categories

Resources