I checked a bunch of questions here and I cannot find correct answer. I have problem with retrieving data from my database. I get android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 0 exception. My code for creating database:
String KREIRAJ_TABELU = "CREATE TABLE " + IME_TABELE + "("
+ ID + " INTEGER PRIMARY KEY," + PITANJE + " TEXT,"
+ PRVI_NETACAN + " TEXT," + DRUGI_NETACAN + " TEXT," + TRECI_NETACAN + " TEXT," + TACAN_ODGOVOR + " TEXT" + ")";
db.execSQL(KREIRAJ_TABELU);
String dodajPitanjaIOdgovore = "INSERT INTO pitanja (ID,PITANJE,PRVI_NETACAN,DRUGI_NETACAN,TRECI_NETACAN,TACAN_ODGOVOR)\n" +
"VALUES (0,\"Ovo je prvo pitanje:\",\"Netacan odgovor\",\"Netacan odgovor\",\"Netacan odgovor\",\"Tacan odgovor\");\n" +
"\n" + ...
db.execSQL(dodajPitanjaIOdgovore);
And for retriving data I use this piece of code:
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(IME_TABELE, new String[]{ID,
PITANJE, PRVI_NETACAN, DRUGI_NETACAN, TRECI_NETACAN, TACAN_ODGOVOR}, ID + "=?",
new String[]{String.valueOf(id)}, null, null, null, null);
if(cursor.getCount() > 0)
{
cursor.moveToFirst();
}
podaciOPitanjima podaci = new podaciOPitanjima(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5));
return podaci;
Edit: I also tried this:
if (cursor.moveToFirst()) {
podaciOPitanjima podaci = new podaciOPitanjima(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5));
}
else{
podaciOPitanjima podaci;
}
podaciOPitanjima podaci = new podaciOPitanjima(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5));
return podaci;
Change
if (cursor.getCount() > 0) {
cursor.moveToFirst();
}
//do operations here
To
if (cursor.moveToFirst()) {
//do operations here
}
Explanation - the problem is this line:
podaci = new poda...ima(Integer.parseInt(cursor.getString(0)), ...);
When you use cursor.getString the cursor is not actually at a row (because there is no row), so you cannot get a cell/column which is what this command is asking for.
The full solution:
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(IME_TABELE, new String[]{ID, PITANJE, PRVI_NETACAN, DRUGI_NETACAN, TRECI_NETACAN, TACAN_ODGOVOR}, ID + "=?", new String[]{String.valueOf(id)}, null, null, null, null);
podaciOPitanjima podaci = null;
if (cursor.moveToFirst()) {
//Note: using getColumnIndex avoids errors if the columns are ever returned in a changed order
podaci = new podaciOPitanjima(
cursor.getInteger( cursor.getColumnIndex(ID) ),
cursor.getString( cursor.getColumnIndex(PITANJE) ),
cursor.getString( cursor.getColumnIndex(PRVI_NETACAN) ),
cursor.getString( cursor.getColumnIndex(DRUGI_NETACAN) ),
cursor.getString( cursor.getColumnIndex(TRECI_NETACAN) ),
cursor.getString( cursor.getColumnIndex(TACAN_ODGOVOR) ));
}
return podaci;
Now remember wherever you are calling this method, that you might get null back and that you need to check for that.
Related
I have this SQL method below, it is suppose to return multiple rows of data, but it is only returning one item every time I try to display the data.
How do I fix that?
//Constant
public static final String COL_4 = "LikeSong";
//Database Table
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE UserInfo(ID INTEGER PRIMARY KEY AUTOINCREMENT, Users_Name TEXT, PlaylistName TEXT,likeAlbum TEXT,LikeSong TEXT)");
}
public String[] getLikedSongs() {
SQLiteDatabase db = this.getReadableDatabase();
String[] LikeSong = null;
Cursor cursor = db.rawQuery(" SELECT " + COL_4 + " FROM " + Table_Name + " WHERE " + COL_4 + " IS NOT NULL", null);
while (cursor.moveToNext()) {
String note = cursor.getString(0);
LikeSong = note.split(",");
}
cursor.close();
db.close();
return LikeSong;
}
Inside the while loop in each iteration you change the value of LikeSong, so when the loop ends, LikeSong has the last value assigned to it.
I think that you want a list of arrays returned by your method getLikedSongs() like this:
public List<String[]> getLikedSongs() {
SQLiteDatabase db = this.getReadableDatabase();
List<String[]> list = new ArrayList<>();
Cursor cursor = db.rawQuery(" SELECT " + COL_4 + " FROM " + Table_Name + " WHERE " + COL_4 + " IS NOT NULL", null);
while (cursor.moveToNext()) {
String note = cursor.getString(0);
LikeSong.add(note.split(","));
}
cursor.close();
db.close();
return LikeSong;
}
Okay...now I see. You are reassigning LikeSong for each iteration of the while loop and returning the String array after the while loop has completed. So obviously, you will get value of only the last row.
First of all i'm new to Android Development.
I'm having some issues with fetching data from database. Whenever i try to fetch a data, the cursor is being empty.
Here is my code:
public ArrayList<Word> getWords(){
SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT * FROM " + TABLE_NAME;
Cursor cursor = db.rawQuery(query, null);
ArrayList<Word> List = new ArrayList<Word>();
if(cursor != null){
cursor.moveToFirst();
while (cursor.moveToNext()){
List.add(new Word(cursor.getString(cursor.getPosition())));
}
}
cursor.close();
db.close();
return List;
}
The size of the cursor is always 1 but the size of the "List" variable is always 0.
I didn't understand the problem, thanks for helping me.
You are shifting the cursor position twice. Just remove the line cursor.moveToFirst(); The moveToNext method is sufficient as it moves to the first position on the first iteration.
you can use this code:
1-If you need first row:
if(cursor != null){
cursor.moveToFirst();
if(cursor.isAfterLast() == false){
List.add(new Word(cursor.getString(cursor.getPosition())));
}
}
2- if you need several rows :
if(cursor != null){
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
List.add(new Word(cursor.getString(cursor.getPosition())));
cursor.moveToNext();
}
}
I checked everything but your recommendations didn't worked. Just to be sure: I want to fetch all rows.
Try like this
public ArrayList<Word> getWords(){
SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT * FROM " + TABLE_NAME;
Cursor cursor = db.rawQuery(query, null);
ArrayList<Word> list = new ArrayList<Word>();
if(cursor != null){
while (cursor.moveToNext()){
list.add(new Word(cursor.getString(cursor.getPosition())));
}
}
cursor.close();
db.close();
return list;
}
I just realised that the program does not go into the while loop in the code that i given above. I think there is a problem with database.
I used that query to create database:
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + TABLE_NAME + " (" +
COLUMN_NAME_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_NAME_TURKISH + " TEXT, " +
COLUMN_NAME_ENGLISH + " TEXT, " +
COLUMN_NAME_GERMAN + " TEXT, " +
COLUMN_NAME_FRENCH + " TEXT, " +
COLUMN_NAME_ARABIC + " TEXT, " +
COLUMN_NAME_RUSSIAN + " TEXT, " +
COLUMN_NAME_SPANISH + " TEXT, " +
COLUMN_NAME_ITALIAN + " TEXT)";
I feel like a idiot because i forgot to type the database name at the constructor method like that:
Old
super(context, null, null, 1);
Now
super(context, "database", null, 1);
Thanks for your help!
I want to search my database for a row where KEY_TOR == place.getTor()
Here I call the method:
DB_Place tor = db_tore.getDBPlace(place.getTor());
This is the method:
public DB_Place getDBPlace(String name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_DB_TORE_Eintrag, new String[] { KEY_ID,
KEY_PLACE_ID, KEY_NAME, KEY_LONGITUDE, KEY_LATITUDE, KEY_TOR }, KEY_TOR + "=?",
new String[]{name}, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
DB_Place place = new DB_Place(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5));
return place;
}
Looks good to me, except that I am getting this error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.x.x/com.example.ahok.x.UI_MainActivity}: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
What am I missing here? Is it possible that it has something to do with a few of the columns being null?
Looks like you don't have any data inserted in your database. Moreover, you've some logical error in your code.
I would like to edit your function like this.
public DB_Place getDBPlace(String name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_DB_TORE_Eintrag, new String[] { KEY_ID,
KEY_PLACE_ID, KEY_NAME, KEY_LONGITUDE, KEY_LATITUDE, KEY_TOR }, KEY_TOR + "=?",
new String[]{name}, null, null, null, null);
DB_Place place = null;
if (cursor != null && cursor.getCount() > 0 && cursor.moveToFirst()) {
place = new DB_Place(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5));
}
return place;
}
Update
So if you think its an error of your query, then run simple query like this.
Cursor cursor = db.rawQuery("Select * from " + TABLE_DB_TORE_Eintrag + " where " + KEY_TOR + " = '" + name + "'", null);
I want to check SQLite database table record . Whether table row is exist then update or delete my table row or.When I run my app the table row insert duplicate.How to avoid it . I want to insert newly record when I run first time , when open the activity second time my database is update. I have tried but db is not show record there.Please help me.Thanks to appreciates
Here is my code
public boolean Exists(String _id)
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("select Company_Id from Company where Company_Id = ?",
new String[]{_id});
boolean exists = (cursor.getCount() > 0);
cursor.close();
return exists;
}
My fragment code
if(jsonStr != null)
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String jsonResult = jsonObj.toString().trim();
Log.e("jsonResult ", " = " + jsonResult);
JSONObject companyList = jsonObj.getJSONObject("Get_CompanyResult");
Log.e("companyList ", " = " + companyList.toString());
JSONArray jarr = companyList.getJSONArray("CompanylList");
Log.e("jarr ", " = " + jarr.toString());
for (int i = 0; i < jarr.length(); i++) {
JSONObject jobCompanyDetails = jarr.getJSONObject(i);
str_CompanyId = jobCompanyDetails.getString("Company_ID");
str_CompanyName = jobCompanyDetails.getString("Company_Name");
Log.e("str_CompanyId ", " = " + str_CompanyId);
Log.e("str_CompanyName ", " = " + str_CompanyName);
if(dbhelper.Exists(str_CompanyId))
{
Log.e("Row is Already ","Exist");
}
else
{
dbhelper.insertCompany(str_CompanyId, str_CompanyName);
Log.e("Data insert into ", " Company Table Succesively !!! = ");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Use below method
public boolean isIDExist(String _id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(Company, new String[] { KEY_your_id}, KEY_your_id + "=?" ,
new String[] { String.valueOf( _id)}, null, null, null, null);
if (cursor != null){
if(cursor.getCount() == 0){
cursor.close();
db.close();
return false;
}else{
cursor.close();
db.close();
return true;
}
}
return false;
}
Change your code to this
public boolean Exists(String _id)
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("select Company_Id from Company where Company_Id ='"+ String _id + "'", null);
boolean exists = (cursor.getCount() > 0);
cursor.close();
return true;
}
I think the simplest way to do this is to create a Primary Key in the table, and then use INSERT OR REPLACE command instead of just using INSERT.
INSERT OR REPLACE will automatically REPLACE the existing row when it encounters a Primary Key violation, with the new data being inserted.
In this case, you can have OrgId as the Primary Key and if you have some record like:
ORGID ORGNAME
1 ABC
and you insert like INSERT OR REPLACE INTO ORG_MASTER(1,'EFG'), the table will now have one row like
ORGID ORGNAME
1 EFG
Hope this helps :)
I have a db made with this statement:
DATABASE_CREATE = "create table "
+ TABLE_BANDS + "(" + COLUMN_ID
+ " integer primary key autoincrement, " + COLUMN_NAME
+ " text unique not null, " + COLUMN_GENDER + " text, " + COLUMN_POPULARITY + " real not null);";
I add to it a row with this statement:
private long addBand(String bandName, String gender) {
ContentValues values = new ContentValues();
values.put(BandsSQLiteOpenHelper.COLUMN_NAME, "\"" + bandName.trim().toLowerCase() + "\"");
values.put(BandsSQLiteOpenHelper.COLUMN_POPULARITY, 1);
values.put(BandsSQLiteOpenHelper.COLUMN_GENDER, "");
long insertId = database.insert(BandsSQLiteOpenHelper.TABLE_BANDS, null,
values);
return insertId;
}
I get insertId > 0, so I think that the insertion was ok.
Then I try to select a row that I just inserted with this code:
public Band getBand(String name) {
Cursor cursor = database.query(BandsSQLiteOpenHelper.TABLE_BANDS,
new String[] {BandsSQLiteOpenHelper.COLUMN_NAME, BandsSQLiteOpenHelper.COLUMN_POPULARITY}, BandsSQLiteOpenHelper.COLUMN_NAME + " = \"" + name.trim().toLowerCase() + "\"", null,
null, null, null);
cursor.moveToFirst();
Band band = getBandFromCursor(cursor);
cursor.close();
return band;
}
But it always returns me a cursor with 0 length.
I tried to remove the quotes around the name, but after it query doent work.
Besides I tried to use a rawQuery, but the result is the same.
Cursor cursor = database.rawQuery("Select * from " + BandsSQLiteOpenHelper.TABLE_BANDS + " where band_name = \"" + name.trim().toLowerCase() + "\"", null);
UPDATE:
I tried single quotes:
Cursor cursor = database.query(BandsSQLiteOpenHelper.TABLE_BANDS,
new String[] {BandsSQLiteOpenHelper.COLUMN_NAME, BandsSQLiteOpenHelper.COLUMN_POPULARITY}, BandsSQLiteOpenHelper.COLUMN_NAME + " = \'" + name.trim().toLowerCase() + "\'", null,
null, null, null);
and
private long addBand(String bandName, String gender) {
ContentValues values = new ContentValues();
values.put(BandsSQLiteOpenHelper.COLUMN_NAME, "\'" + bandName.trim().toLowerCase() + "\'");
values.put(BandsSQLiteOpenHelper.COLUMN_POPULARITY, 1);
values.put(BandsSQLiteOpenHelper.COLUMN_GENDER, "");
long insertId = database.insert(BandsSQLiteOpenHelper.TABLE_BANDS, null,
values);
return insertId;
}
As before insertion is ok, selection returns 0 rows.
When inserting the values, I doubt you need to put the double quotes around the values you insert since you specified in your DB Creation string that the fields are TEXT.
As for your rawQuery, try this:
"SELECT * FROM " + BandsSQLiteOpenhelper.TABLE_BANDS + " WHERE band_name = '" + name.trim().toLowerCase() + "'";
Try single quotes instead of double quotes when using Strings as identifiers in WHERE statements.