1

This is my problem: I have an SQLite DB set up to store some values. In this case, its pretty simple. Two columns (_id, name). I know data is getting stored in the database and I know the cursor I am using to pass that information is also populating. However, when I try to add a cursor value to an ArrayList, I get an error. This is the code for my problem method:

public void sqltest(LDatabase LConnector){
     cursor = LConnector.getAllRecords(); //gets the cursor from my db 
     try{
     cursor.moveToFirst();}
     catch (Exception e){
          log.i("Failed", "Couldn't moveToFirst"); //I get a successful moveToFirst
     }
     while(cursor.moveToNext()){
         try{
         getWork.add(cursor.getString(cursor.getColumnIndex("name")));
        } catch (Exception h){
         Log.i("FAILED", cursor.getString(cursor.getColumnIndex("name")));
     }
  }

I set up that last log to tell me the value of the cursor at that position. The values entered for the DB always print out so I know the cursor is being populated. Anyone have any idea what I am doing wrong here?

EDIT: LogCat shows these two lines after this is called when an activity starts:

04-12 23:26:26.606: I/MOVED(9478): MOVED TO FIRST
04-12 23:26:26.606: I/FAILED(9478): test1

There are no more verbose errors that describe it better, that is why I am so confused. It just doesn't get stored to the AssetList at all.

This is the code for the getAllRecords() mehod:

public Cursor getAllLifts() throws SQLiteException
{
    open();
    return database.rawQuery("SELECT * FROM  contacts"+";", null);  
}

Additionally, here is the create code + the code used for inserting:

Create:

 String createQuery = "CREATE TABLE contacts" +
     "(_id auto_increment integer primary key," +
     "name text);";

  db.execSQL(createQuery); // execute the query

Insert: open(); // open the database try{ //add more later to get data to insert from usr, just for testing database.execSQL("INSERT INTO contacts(name) VALUES('test1')"); database.execSQL("INSERT INTO contacts(name) VALUES('test2')");}

catch (Exception insert){
   Log.i("INSERT", "INSERT FAILED");
}
close(); // close the database

EDIT: rest of the activity w/ imports

package com.jydev.llogger2;

import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.content.Context;
import android.database.Cursor;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Create extends Activity implements OnClickListener {

Button buttonNext; //continue button
Button buttonBack; //back button
EditText nameEditText; //editText w/ workout name
EditText commentEditText; //editText w/ comments
Intent info; //intent used to pass extras
String wName = null; 
String wComments = null; 
ArrayList<String> getWork;
Cursor cursor;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.create);

    commentEditText = (EditText)findViewById(R.id.commentEditText);
    buttonBack = (Button)findViewById(R.id.create_back);
    buttonNext = (Button)findViewById(R.id.create_continue);
    nameEditText = (EditText)findViewById(R.id.nameEditText);

    LtDatabase LConnector = new LDatabase(this);
    LConnector.insert();
    sqltest(LConnector);

}
7
  • 3
    We have no idea what error you get if you do not tell us what the error is. Post your logcat Commented Apr 13, 2013 at 4:22
  • added to original q as requested Commented Apr 13, 2013 at 4:28
  • Post your code for getAllRecords() and the whole logcat. You can only get exception if "name" is not valid. Commented Apr 13, 2013 at 4:35
  • put detail logcat including error logs Commented Apr 13, 2013 at 4:40
  • and show the declaration of getwork Commented Apr 13, 2013 at 4:42

2 Answers 2

2

There are several wrong things. First moveToFirst() returns a boolean so you will never get an exception thrown. Second the while statement will skip one row since you call moveToNext(), thus the first row is skipped. Finally, you get an exception because you did not initialize getwork.

public void sqltest(LDatabase LConnector)
{
     cursor = LConnector.getAllRecords(); //gets the cursor from my db 

     if (cursor.moveToFirst())
     { 
        do 
        {
            try{
            getWork.add(cursor.getString(cursor.getColumnIndex("name")));
            } catch (Exception h){
            Log.i("FAILED", cursor.getString(cursor.getColumnIndex("name")));  
            }
          while (cursor.moveToNext()); 
          }
     }
 }  

In your declaration of getWork

ArrayList<String> getWork = new ArrayList<String>();
Sign up to request clarification or add additional context in comments.

1 Comment

Worked beautifully! Thanks from an android newbie.
1

for my queries i'm using the following

public ArrayList<T> findAllBy(String selection) {
    final SQLiteDatabase db = HELPER.getReadableDatabase();     
    final ArrayList<T> result = new ArrayList<T>();
    final Cursor cursor = db.query(TABLE_NAME, SELECTED_COLS, WHERE, null, null, null, null);

    try {
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            T model = CREATEOBJECT(cursor);
            result.add(model);
            cursor.moveToNext();
        }

        return result;
    } finally {
        cursor.close();
        db.close();
    }
}

Where:

  • HELPER is a instance extendes from SQLiteOpenHelper
  • TABLE_NAME is a string with the name of the table
  • SELECTED_COLS is a String[] array with the columns names i want get
  • WHERE is a string like "COL_NAME = 'value'" or null
  • CREATEOBJECT is a method for create Object of type T want in my ArrayList<T>

Example CREATEOBJECT

public T CREATEOBJECT(Cursor cursor) {
    new T(
        cursor.getInt(0), cursor.getString(1)
    );
}

public class T {
    private long   id; 
    private String name;    

    T(int id, String name) {
        this.id = id;
        this.name = name;
    }
    //...
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.