Cursor to String - android

I'm new to android, and I don't know why I am getting CursorIndexOutOfBoundsException: Index 0 requested with a size of 0. I'm trying to display it on another class using listview. Here are my codes:
public void onItemClick(AdapterView<?> arg0, View view, int position,
long id) {
// TODO Auto-generated method stub
position = position + 1;
Cursor a = MainActivity.sqldb
.rawQuery("Select name from " + MainActivity.tblpb
+ " where _pid = " + position + ";", null);
String aa = a.getString(a.getColumnIndex("name"));
Cursor b = MainActivity.sqldb
.rawQuery("Select phone from " + MainActivity.tblpb
+ " where _pid = " + position + ";", null);
String bb = b.getString(b.getColumnIndex("phone"));
Intent next = new Intent (this, ThirdActivity.class);
startActivity(next);
}
I know that there's something really wrong here. And I wonder what it is.
Create Table:
sqldb = this.openOrCreateDatabase(dbpb, MODE_PRIVATE, null);
sqldb.execSQL("CREATE TABLE IF NOT EXISTS "
+ tblpb
+ " (_pid INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, phone INTEGER);");
Insert Table:
sqldb.execSQL("Insert into " + tblpb
+ " (name, phone) Values ('" + x + "' , '"
+ y + "' );");

Try doing this:
public void onItemClick(AdapterView<?> arg0, View view, int position,
long id) {
// TODO Auto-generated method stub
String aa = null;
String bb = null;
// do not alter the position, DB starts the same position as ItemClick for
// adapter view
// position = position + 1;
Cursor a = MainActivity.sqldb
.rawQuery("Select name from " + MainActivity.tblpb
+ " where _pid = " + position + ";", null);
if(a != null){
// Force cursor to position 0
if(a.moveToFirst()){
// make sure the column actually exists
aa = a.getString(a.getColumnIndexOrThrow("name"));
Log.d("Cursor A - Name", "name column val: "+ aa);
}else{
Log.d("Cursor A", "cursor A failed to move to first");
}
}else{
Log.d("Cursor A null", "cannot access cursor A");
}
Cursor b = MainActivity.sqldb.rawQuery("Select phone from " + MainActivity.tblpb + " where _pid = " + position + ";", null);
if(b != null){
// Force cursor to position 0
if(b.moveToFirst()){
// make sure the column actually exists
bb = b.getString(b.getColumnIndexOrThrow("phone"));
Log.d("Cursor B - Phone", "phone column val: "+ bb);
}else{
Log.d("Cursor B", "cursor B failed to move to first");
}
}else{
Log.d("Cursor B null", "cannot access cursor B");
}
Intent next = new Intent (this, ThirdActivity.class);
next.putExtra("NAME", aa);
next.putExtra("PHONE", bb);
startActivity(next);
}
Then in your second Activity do:
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.content_file);
Bundle extras = getIntent().getExtras();
if(extras != null){
String aa = extras.getString("NAME");
String bb = extras.getString("PHONE");
// Since you cannot tell if these are null check them
if(aa != null){
// ... Use on your TextView
}
// Since you cannot tell if these are null check them
if(bb != null){
// ... Use on your TextView
}
}
}

The error indicates that you are trying to access the first element (index 0) of an empty list (size 0) meaning your queries are returning no results. Make sure your queries are correct.
EDIT:
It's also a good idea to call cursor.moveToFirst() and check its result before doing any operations on the data from a query.
http://developer.android.com/reference/android/database/Cursor.html#moveToFirst%28%29

Related

How can I repeat a ListView item a certain number of times using Android and SQLite data and changing one column each iteration?

I am trying to repeat certain data from a table in a ListView with one row changing each iteration of the item. I want to have a user input an int of the times to repeat and press a button to update the list.
I am working with dates as the updating item. So if a user inputs '3', I want 3 rows added to the list, and inserted into the table, adding 1 month to the date for the 3 months.
Main Activity
planAheadButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (planAheadMonths.getText().toString().trim().isEmpty()) {
Toast.makeText(getBaseContext(), "Add months to plan by", Toast.LENGTH_SHORT).show();
} else {
int plan = Integer.parseInt(planAheadMonths.getText().toString());
mDBHelper.updateCheckingPlanner(plan, mChecking.getCheckingId());
planAheadMonths.setText("");
mDBHelper.getTransRepeater(plan, mChecking.getCheckingId());
}
}
});
DBHelper
public void getTransactionRepeater(int repeat, int id) {
SQLiteDatabase db = this.getWritableDatabase();
String whereclause = TRANSACTION_DATE + " BETWEEN " + getCurrentMonth() + " AND " + getFutureMonth() + " AND " +
TRANSACTION_CHECKING_ID + " = " + id + " AND " + TRANSACTION_REPEAT + " != 'NONE' ";
String[] whereargs = new String[1];
Cursor res = db.query(TABLE_TRANSACTIONS, null, whereclause, null, null, null, TRANSACTION_DATE + " ASC, " + TRANSACTION_ID);
db.beginTransaction();
while (res.moveToNext()) {
if (res.getString(res.getColumnIndex(TRANSACTION_REPEAT)).equals("MONTH")) {
for (int i = 0; i < repeat; i++) {
+ i);
ContentValues cv = new ContentValues();
cv.put(TRANSACTION_NAME, res.getString(res.getColumnIndex(TRANSACTION_NAME)));
cv.put(TRANSACTION_TYPE, res.getString(res.getColumnIndex(TRANSACTION_TYPE)));
cv.put(TRANSACTION_DATE, sdf.format(cFuture.getTime()) + res.getString(res.getColumnIndex(TRANSACTION_NAME)) + i);
cv.put(TRANSACTION_AMOUNT, res.getInt(res.getColumnIndex(TRANSACTION_AMOUNT)));
cv.put(TRANSACTION_NOTES, res.getString(res.getColumnIndex(TRANSACTION_NOTES)));
cv.put(TRANSACTION_REPEAT, res.getString(res.getColumnIndex(TRANSACTION_REPEAT)));
cv.put(TRANSACTION_CHECKING_ID, res.getInt(res.getColumnIndex(TRANSACTION_CHECKING_ID)));
cv.put(TRANSACTION_NEW_BALANCE, res.getInt(res.getColumnIndex(TRANSACTION_NEW_BALANCE)));
cv.put(TRANSACTION_CREDIT_ID, res.getString(res.getColumnIndex(TRANSACTION_CREDIT_ID)));
whereargs[0] = res.getString(res.getColumnIndex(TRANSACTION_DATE));
db.insert(TABLE_TRANSACTIONS, null, cv);
}
}
}
res.close();
db.setTransactionSuccessful();
db.endTransaction();
}

Error with passing data over Intent

I'm trying to pass an ID from one class to another using intent after watching a youtube tutorial. However, it always passes over the default value of -1 rather than the value I want.
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String homeTeam = adapterView.getItemAtPosition(i).toString();
Log.d(TAG, "onItemClick: You Clicked on " + homeTeam);
Cursor data = myDB.getMatch(homeTeam); //get the id associated with that name
int itemID = -1;
while(data.moveToNext()){
itemID = data.getInt(0);
}
if(itemID > -1){
//Log.d(TAG, "onItemClick: The ID is: " + itemID);
Intent editScreenIntent = new Intent(ViewMatchesActivity.this, UpdateMatchActivity.class);
editScreenIntent.putExtra("MatchId", itemID);
editScreenIntent.putExtra("homeTeam",homeTeam);
startActivity(editScreenIntent);
}
else{
toastMessage("No ID associated with that name");
}
}
});
}
The class it goes to:
//get the intent extra from the ListDataActivity
Intent receivedIntent = getIntent();
//now get the itemID we passed as an extra
selectedID = receivedIntent.getIntExtra("matchId", -1); //NOTE: -1 is just the default value
//now get the name we passed as an extra
selectedName = receivedIntent.getStringExtra("homeTeam");
//set the text to show the current selected name
editable_item.setText(selectedName);
In his tutorial, it works fine but when I try it after I edit a match, in my log it comes up with MatchId = -1 when it shouldn't be.
I'll include the method in the database also:
public void updateName(String newName, int id, String oldName){
SQLiteDatabase db = this.getWritableDatabase();
String query = "UPDATE " + MATCH_TABLE + " SET " + MATCH_HOME_TEAM_COL +
" = '" + newName + "' WHERE " + MATCH_ID_COL + " = '" + id + "'" +
" AND " + MATCH_HOME_TEAM_COL + " = '" + oldName + "'";
Log.d(TAG, "updateName: query: " + query);
Log.d(TAG, "updateName: Setting name to " + newName);
db.execSQL(query);
}
In the Recieving Activity Change the code
//get the intent extra from the ListDataActivity
Intent receivedIntent = getIntent();
//now get the itemID we passed as an extra
selectedID = receivedIntent.getIntExtra("MatchId", -1); //NOTE: -1 is just the default value
//now get the name we passed as an extra
selectedName = receivedIntent.getStringExtra("homeTeam");
//set the text to show the current selected name
editable_item.setText(selectedName);
You should use MatchId instaed of matchID. Java is Case Sensitive.
The key which you have passing is MatchId and you are fetching data from matchId, Which are not same.
Replace your code to
selectedID = receivedIntent.getIntExtra("MatchId", -1); //NOTE: -1 is just the default value

Query (The query is good!!) in Listview and DialogFragment

Hi guys i have a huge problem that in cannot reoslve... it's simple, y have a ListView and when y click in a one item of the ListView I get the "Rubro" of that item and it's fine...the problem is that I have a method that I do a query of comapre this Rubro and get a Long att form the table but, the query dont work!! but i know that the query is good because I prove it whit the DB Brwoser for SQLite!! so here is the code where i call the method:
public void onClick(DialogInterface dialog, int id) {
TextView selectR = (TextView) view.findViewById(R.id.Rubro);
TextView selectV = (TextView) view.findViewById(R.id.Valor);
Long ac = db.Buscar_Rubro(selectR.getText().toString()); //THIS IS THE METHOD!
EditText r = (EditText) dialogV.findViewById(R.id.Mod);
Long Sum = Long.parseLong(r.getText().toString());
db.ModRubros(Long.parseLong(selectV.getText().toString()),ac,Sum);
Cursor cT = db.ListarRubros();//RefreshRubros(cT, from, to);
}
And here is the Method:
public long Buscar_Rubro(String Rubro){
SQLiteDatabase DB = database.getReadableDatabase();
String Query ="SELECT " + Database.ValorActrual + " FROM "+ Database.Taba_Rubros + " WHERE " + Database.Rubro + " LIKE '"+ Rubro +"'" ;
Cursor c = DB.rawQuery(Query,null);
Long ac = c.getLong(1);
return ac;
}
Please help me! I lost all the day to correct this!
PD: This is the error that i get but it's obvios becuae the query dont work!
android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1
You should do like
String Query ="SELECT " + Database.ValorActrual + " FROM "+ Database.Taba_Rubros + " WHERE " + Database.Rubro + " LIKE '"+ Rubro +"'" ;
Cursor c = DB.rawQuery(Query,null);
if (c != null && c.moveToFirst()) {
Long ac = c.getLong(0);
}

Retrieve records from sqllite using Array list

I am retrieving all records from database and saving all records in array list.when i show array list records ,repeated data displayed,i don't know what's the prolblem??
Calling this function in view_record class:
public ArrayList<tuple> getdata() { // TODO Auto-generated method stub
tuple obj=new tuple();
Cursor c = ourDatabase.query(DATABASE_TABLE, PROJECTION_ALL, null, null, null, null, null);
if(c == null) {
return null;
}
ArrayList <tuple> data = new ArrayList<tuple>();
// String result = " ";
int i=0;
for(c.moveToFirst();!c.isAfterLast();c.moveToNext()){
obj.ROWID= c.getString(c.getColumnIndexOrThrow(KEY_ROWID));
obj.CNAME= c.getString(c.getColumnIndexOrThrow(KEY_CNAME));
obj.SNAME= c.getString(c.getColumnIndexOrThrow(KEY_SNAME));
obj.FAMILY= c.getString(c.getColumnIndexOrThrow(KEY_FAMILY));
obj.LOCATION= c.getString(c.getColumnIndexOrThrow(KEY_LOCATION));
obj.IMAGE1= c.getBlob(c.getColumnIndexOrThrow(KEY_IMAGE1));
obj.IMAGE2= c.getBlob(c.getColumnIndexOrThrow(KEY_IMAGE2));
obj.IMAGE3= c.getBlob(c.getColumnIndexOrThrow(KEY_IMAGE3));
data.add(i, obj);
i++;
}
c.close();
return data; }
My view_record class
public class view_record extends Activity {
#Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.db_view);
TextView tv=(TextView) findViewById(R.id.tvSqlinfo);
ImageView img=(ImageView) findViewById(R.id.img_view);
db_handler info=new db_handler(this);
info.open();
// Log.d("abc", "adb");
ArrayList <tuple> data=info.getdata();
Log.d("abc", "adb");
String result="";
for(int i=0;i<data.size();i++){
result +=" " + data.get(i).ROWID + " " + data.get(i).CNAME + " " + data.get(i).SNAME + " " + data.get(i).FAMILY + " " + data.get(i).LOCATION + "\n";
tv.setText(result);
img.setImageBitmap(Utilities.getImage(data.get(0).IMAGE2));
}
info.close(); } }
I want to view as follows :
" 1 cname sname family location "
" 2 cname sname family location "
But i am getting
" 2 cname sname family location "
" 2 cname sname family location "
Means last record displayed two times.
and one more thing ,i want to get all records where cname=something,getting error while doing it so
you are not making a new project in your for loop. That is whay you are getting same results. just do...
on start of for loop add this line obj=new tuple();
Answer to your Second Question
for(int i=0;i<data.size();i++){
result +=" " + data.get(i).ROWID + " " + data.get(i).CNAME + " " + data.get(i).SNAME + " " + data.get(i).FAMILY + " " + data.get(i).LOCATION + "\n";
img.setImageBitmap(Utilities.getImage(data.get(0).IMAGE2));
}
tv.setText(Html.fromHtml(result));

Android Application did not close cursor or database

Im running into an issue inserting items into my database. It really odd that the program will run through 4 rows and insert them fine, but on the 5th row it crashes and I got three reports of Application did not close cursor or database. In my code I am closing and reopening both the cursor and the database so I am really confused on how this is happening. Here is the code.
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case REQUEST_CODE_NEW:
if (resultCode == -1) {
Integer chapterId = data.getIntExtra("chapterId", -1);
Toast toast = Toast.makeText(this, "Selected Chapter: " + chapterId.toString(), Toast.LENGTH_LONG);
if (chapterId != -1) {
DbHelper db = new DbHelper(this);
for (int i = 0; i < questions.getTitle().size(); i++) {
db.insertQuestion(chapterId.toString(), questions.getTitle().get(i), questions.getAnswer().get(i), questions.getAr().get(i));
}
}
toast.show();
}
break;
}
}
Thats calling the database to be created through a dbhelper class. Here is the database helper
public void insertQuestion(String cat_id, String title, String answer, String article) {
db.execSQL("INSERT INTO " + QUESTION_TABLE_NAME + " (title,answer,article,picture) VALUES ('" + title + "','" + answer + "','" + article + "','none')");
String id = getQuestionId(title);
db.execSQL("INSERT INTO " + REL_TABLE_NAME + " (question_id, cat_id) VALUES (" + id + "," + cat_id + ")");
}
public String getQuestionId(String title) {
String id;
cursor = this.db.rawQuery("SELECT question_id FROM " + QUESTION_TABLE_NAME + " WHERE title = '" + title + "' LIMIT 1", null);
cursor.moveToFirst();
id = cursor.getString(0);
cursor.close();
db.close();
return id;
}
I put the cursor at the class level so I can try to manage it better, but still to no avail. Its still crashing after 4 queries.
Try this "fix":
DbHelper db = new DbHelper(this);
try{
for (int i = 0; i < questions.getTitle().size(); i++) {
db.insertQuestion(chapterId.toString(), questions.getTitle().get(i), questions.getAnswer().get(i), questions.getAr().get(i));
}
}catch(Exception e1){
android.util.Log.v("DbHelper Error","Crash: "+e1.getMessage(), e1);
}finally{
db.close();
}

Categories

Resources