I am fetching data from cursor. Using this cursor i am populating the text for my radio button. While displaying the activity it works fine but when i try to select the radio button, i again try to access my cursor and at that time i get the cursor out of bounds exception. Please help me out.
Cursor cur=db.getForcemodLevelForMenuitem(mnuItmID);
cur.moveToFirst();
while (cur.isAfterLast() == false) {
cnt=1;
//Level 1
if(cur.getInt(0)==1)
{
LinearLayout level1Layout=(LinearLayout)findViewById(R.id.level1Layout);
level1Layout.setVisibility(View.VISIBLE);
//ArrayList menuitemForcemodMapsLevel1=db.GetBaseObjectListFromDBWhere("MenuitemForcemodMapping", "MenuitemID= "+mnuItmID+ " and Level="+1);
menuitemForcemodMapsLevel1=db.getForcemodDetailsForMenuitem(mnuItmID,1);
RadioGroup level1_rg=(RadioGroup) findViewById(R.id.level1_rg);
RadioButton[] rblevel1=new RadioButton[menuitemForcemodMapsLevel1.getCount()];
menuitemForcemodMapsLevel1.moveToFirst();
int i=0;
while (menuitemForcemodMapsLevel1.isAfterLast() == false) {
rblevel1[i] =new RadioButton(AddPopupMenuItem.this);
rblevel1[i].setText(menuitemForcemodMapsLevel1.getString(1).substring(0));
rblevel1[i].setTextColor(R.color.black);
level1_rg.addView(rblevel1[i]);
rblevel1[i].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
menuitemForcemodMapsLevel1.moveToPosition(i);
forceModNameList.add(menuitemForcemodMapsLevel1.getString(1).substring(0));
}
});
i++;
menuitemForcemodMapsLevel1.moveToNext();
}
menuitemForcemodMapsLevel1.close();
rblevel1=null;
}
}
cur.moveToNext();
}
cur.close();
db.close();
}
}
I am getting error at this line
:forceModNameList.add(menuitemForcemodMapsLevel1.getString(1).substring(0));
Thanks ,
Neha
You already retreive the 1st element at :
rblevel1[i].setText(menuitemForcemodMapsLevel1.getString(1).substring(0));
so the cursor is moved ahead. And then you are asking again the same thing to retrieve. Cursor can't move backwards, it moves only forward by default. So you are getting this error.
Why don't you save the value in a String and can thus use again without the need of retreiving it again.
I beleive this will simplify your code and also solve the problem. Try out.
please use this, i think it will solve your issue
Cursor c;
if(c.moveToFirst())
{
do
{
// perform operation in this blocks
}while(c.moveToNext());
}
Related
i basically want to use the query select password from Login_table where username ='this will be given by the user';
Cursor res =db.rawQuery("select password from Login_table where username ='"+x+"'",null);
i guess this is right but still getting a problem
android.database.CursorIndexOutOfBoundsException: Index -1 requested,
with a size of 2
public void checkData(){
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String user_name=usname.getText().toString();
Cursor res =mydb.getData(user_name);
if(res.getCount()==0){
Toast.makeText(MainActivity.this,"Login failed",Toast.LENGTH_SHORT);
}
String check=res.getString(2);
Toast.makeText(MainActivity.this,String.valueOf(check),Toast.LENGTH_SHORT).show();
String pass_Word=pass.getText().toString();
if(pass_Word.compareTo(check)==0){
Toast.makeText(MainActivity.this,"You are Loged IN",Toast.LENGTH_LONG).show();
}
else
Toast.makeTextenter code here(MainActivity.this,"You are Not Loged IN",Toast.LENGTH_SHORT).show();
}
});
}
i just want to retrieve the password and check with the users inputenter code here
The reason why you are getting the index out of bounds is that you are trying to read data from the position that is BEFORE THE FIRST ROW i.e. -1. You have to move to a row to read data from the row.
So before the line String check=res.getString(2); you need to move to a row, probably using the Cursor's moveToFirst method (although according to the message there are 2 rows returned, which is an issue you would probably want to address as it would appear that there are two rows for the same user and perhaps 2 different passwords).
As the moveToFirst method returns a boolean, true if the move could be made, else false, then there is no need to check to see if there are any rows as if there are not then moveToFirst will return false.
Although probably not currently an issue. You should also always close a Cursor when done with it.
As such you may wish to try using :-
public void checkData(){
final DBAssetHelper mydb;
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String user_name=usname.getText().toString();
Cursor res =mydb.getData(user_name);
if (res.moveToFirst()) { //<<<<<<<<<< try to move to a row
Toast.makeText(MainActivity.this,"Login failed", Toast.LENGTH_SHORT);
} else {
if (res.getString(2).equals(pass.getText().toString)) {
Toast.makeText(MainActivity.this,"You are Loged IN",Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this,"You are Not Loged IN",Toast.LENGTH_SHORT).show();
}
}
res.close(); //<<<<<<<<<< Close the Cursor
}
});
}
I have implemented search on my application , it is working . But when the query string dosen't matches with anything it gives me blank screen , instead of that blank screen i want to display "No results found"
Here is my code for searching
public Cursor getSearchResults1(String query) {
// TODO Auto-generated method stub
String[] args=new String[]{query};
return(getReadableDatabase().rawQuery("SELECT _id,section,section_name FROM sections WHERE section_name LIKE '%' || ? || '%'", args));
}
Please help me in this
Thanks In Advance!
Try this.
if(cursor.moveToFirst()){
// Do with the search result
}else{
// no result
}
you can use cursor.getCount() but it is more computation expensive as it returns the number of rows for that query, more the number of row more time it will take. Its better to use cursor.moveToFirst() if you just want to know whether you got any data for query or not.
I have created an activity that refresh quotes when the user clicks a button. Within the same activity there is a check box which the users can click if they like the quote.
Everything works perfectly apart from the check box. When the user clicks they like the quote, I want that check box checked. This only happens when the user moves away from the activity and returns at a later stage.
However when the user stays within the activity and returns to the quote, the old state is shown instead of the users preference.
The check box is configured from the values even in the database, if the value is 1, the check box should be ticked, if not, check box should be clear.
The code is shown below:
When the user clicks the next button, the following code is executed:
Button nextGenerateButton = (Button) findViewById(R.id.btn_next_quotes);
nextGenerateButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String nextQuote = myDbHelper.getnextQuote();
setQuoteDisplay(nextQuote);
btn_favorite.setChecked(myDbHelper.getFavouriteCheckBoxValue());
}
});
The button retrieves the next quote and the getFavouriteCheckBoxValue() confirms whether the favourite column is marked in the database and either returns a true of false which sets the check box value.
public boolean getFavouriteCheckBoxValue()
{
int laballedFavourite = cursor.getInt(0);
if(laballedFavourite == 0)
{
return false;
}
else
{
return true;
}
}
if the user likes the quote, the code executes the addFavourite() which updates the table where the favourite column will be modified on one.
btn_favorite.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked == true)
{
myDbHelper.addFavourite();
}
if(isChecked == false)
{
myDbHelper.removeFavourite();
}
}
});
public void addFavourite()
{
ContentValues vals = new ContentValues();
vals.put("favouriteQuote", 1);
db.update(TABLE_NAME, vals, "columnId = " + cursor.getInt(1), null);
}
Again this only works perfectly when I resume the quote activity and not when I am currently live in the quote activity.
Hope this makes sense.
Any help would be greatly appreciated.
You need to refresh your checkbox to see the changement because you made a changement in you db but not on the UI. You need to observe the db and refresh the checkbox after a modification.
Refreshing cursor solved the problem.
I have an ImageButton that I want to use to set a boolean value for an item in an SQLiteDatabase.
The ImageButton will display one image for a value of "1", and another image for a value of "0". Pressing the image button should toggle the database field and therefore its image.
For some reason, when I press the button the value returned by the currentCursor.getInt() is still the same, despite the update method being called on the database. Do I have to update/refresh the cursor?
In my activity I have:
private void updateFavouriteButton(){
int favourite = currentCursor.getInt(currentCursor.getColumnIndex(Object.favourite));
if (favourite == 1)
{
favouriteButton.setImageDrawable(getResources().getDrawable(R.drawable.favourite_selected));
favouriteButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dbHelper.updateFavourite(selectedId, 0);
updateFavouriteButton();
}
});
}
else
{
favouriteButton.setImageDrawable(getResources().getDrawable(R.drawable.favourite));
favouriteButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dbHelper.updateFavourite(selectedId, 1);
updateFavouriteButton();
}
});
}
}
In my database helper I have:
public void updateFavourite(long rowId, int favourite)
{
db.beginTransaction();
try {
ContentValues args = new ContentValues();
args.put("ZFAVOURITE", favourite);
int rowsAffected = db.update("ZOBJECT", args,"_id" + "=" + rowId, null);
if (rowsAffected > 0)
db.setTransactionSuccessful();
} catch (Exception e) {
Log.e("Error in transaction", e.toString());
} finally {
db.endTransaction();
}
}
requery() is deprecated, the documentation says to just close the old cursor, remake it, and use the new one.
A cursor is a snapshot at the time its created. If the Database is changed, you must requery.
As #Pyrodante had said, it is needed to requery() the cursor in some ways since requery() is deprecated
Not sure how u guys solve it, here is how I solve this problem.
please let me know if there is a better way. thanks!
Cursor newCursor=CreateCursor(); //ChreateCursor() create a method which returns you a new cursor
mAdapter.changeCursor(newCursor); //Change to the new cursor so that the list will be updated
I have a program that relates to a database. I start out my program by inserting a row using the following command.
long id = db.insertMajor(null, null, null, null);
it works perfect. I than alter the information but lets ignore that since for the time being I commented out all those lines. Now I want to check and see if it is null which is should be. If it is not null than I would like to check a checkbox. if it is null than I want to leave the box unchecked. So far I have this line to test.
String change = db.getMajorTitle(value).getString(1);
if (change.equals(null)) {
filled = false;
}
the filled boolean will check the box or not. If the database field is filled or not I always get a checkmark. Whats wrong?
UPDATE:
Since no one has figure it out I will post most of my code to try and help figure it out. I have also reset my emulator to ensure there is not problems with corrupted data.
chk1.setChecked(checker(1));
chk2.setChecked(checker(2));
chk3.setChecked(checker(3));
chk4.setChecked(checker(4));
}
boolean checker(int value){
DBAdapter db = new DBAdapter(this);
boolean filled = false;
db.open();
for (int i = 1; i <= 4; i++) {
String change = db.getMajorTitle(value).getString(1);
if (change == null) {
filled = false;
}else{
filled = true;
}
}
db.close();
return filled;
}
If someone copies this and it works can you please tell me what might be wrong with my emulator or eclipse or whatever. Thanks everyone for there input.
FINISHED:
I noticed that at another part in my program I changed null to "". I would like to thank everyone for being right and showing me different ways to code it.
You really don't need if statements for this.
filled = (change != null);
if (change.equals(null)) {
If change instance is not null, the above condition always returns false. Read Object equality constraints for more info.
If you want to check against null use
if( change == null) {
// change is null, update filled field
} else {
// change is not null, update filled field
}
If the database field is filled or not
I always get a checkmark. Whats wrong?
I guess that you would have initialized the filled field as true and never set it as false since your if condition always returns false or throws NullPointerException.
User ExceptionHandling mechanism. then you will succeed. Like
try {
if(change!=null)
{
//do ur work,if not null
}
else
{
// do some thing
}
}catch(NullPointerException e)
{
//do ur work,if null.
}