简体   繁体   中英

Receive data from database based on user input in EditText

I have a quick question, I'm sure I'm just making a small mistake but I can't figure it out.I'm trying to get information from the database based on what the user inputs in an EditText. I'm getting error

"java.lang.IllegalStateException: Couldn't read row 0, col 1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.".

Here's My Main Activity Class

public class MainActivity extends AppCompatActivity {

Button create;
Button retrieve;
Button save;
Button clear;
EditText listName;
EditText listDetails;
ToDoListDatabase myDb;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    myDb = new ToDoListDatabase(this);

    create = (Button)findViewById(R.id.createButton);
    retrieve = (Button)findViewById(R.id.retrieveButton);
    save = (Button)findViewById(R.id.saveButton);
    clear = (Button)findViewById(R.id.clearButton);
    listName = (EditText)findViewById(R.id.listName);
    listDetails = (EditText)findViewById(R.id.listDetails);


    create.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        AddList();
    }
});

    retrieve.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showList(listName.getText().toString());
        }
    });
}


//Method Resets EditText back to default
public void resetEditText(){
    listName.setText("");
    listDetails.setText("");
}

//Method Adds List Entered By User To DataBase
public void AddList(){
    boolean isInserted = myDb.insertData(listName.getText().toString(), listDetails.getText().toString());
    if(isInserted == true){
        Toast.makeText(MainActivity.this,"List " + listName.getText().toString() + " successfully created", Toast.LENGTH_LONG).show();
        resetEditText();
    }
    else
        Toast.makeText(MainActivity.this,"Error creating list", Toast.LENGTH_LONG).show();
}


public void showList(String listName){
    Cursor res = myDb.getList(listName);
    if(res.getCount() == 0){
        Toast.makeText(MainActivity.this,"Error finding list", Toast.LENGTH_LONG).show();
       return;
    }

    StringBuffer buffer = new StringBuffer();

    buffer.append(res.getString(2));
    listDetails.setText(buffer); //Not working yet!!!!
}

}

Here's My DataBase Class

public class ToDoListDatabase extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "List_db";
public static final String TABLE_NAME = "List_Table";
public static final String COL_1 = "ID";
public static final String COL_2 = "NAME";
public static final String COL_3 = "LIST";

public ToDoListDatabase(Context context) {
    super(context, DATABASE_NAME, null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,LIST TEXT)");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXITS" + TABLE_NAME);
    onCreate(db);
}

public boolean insertData(String name, String list) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COL_2, name);
    contentValues.put(COL_3, list);
    long result = db.insert(TABLE_NAME, null, contentValues);
    if (result == -1) { //returns -1 if not inserted
        return false;
    } else
        return true;

}

public Cursor getList(String listName) {
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor res = db.rawQuery("SELECT LIST FROM " + TABLE_NAME + " WHERE NAME = '" +listName+"'" , null);
    return res;
 }
}

Here's my Android Monitor

   10-10 13:11:41.618 2643-2643/com.example.stephen.todolist E/AndroidRuntime: FATAL EXCEPTION: main
                                                                        android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 4
                                                                            at android.database.AbstractCursor.checkPosition(AbstractCursor.java:424)
                                                                            at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
                                                                            at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
                                                                            at com.example.stephen.todolist.MainActivity.showList(MainActivity.java:79)
                                                                            at com.example.stephen.todolist.MainActivity$2.onClick(MainActivity.java:47)
                                                                            at android.view.View.performClick(View.java:4439)
                                                                            at android.widget.Button.performClick(Button.java:139)
                                                                            at android.view.View$PerformClick.run(View.java:18395)
                                                                            at android.os.Handler.handleCallback(Handler.java:725)
                                                                            at android.os.Handler.dispatchMessage(Handler.java:92)
                                                                            at android.os.Looper.loop(Looper.java:176)
                                                                            at android.app.ActivityThread.main(ActivityThread.java:5317)
                                                                            at java.lang.reflect.Method.invokeNative(Native Method)
                                                                            at java.lang.reflect.Method.invoke(Method.java:511)
                                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
                                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
                                                                            at dalvik.system.NativeStart.main(Native Method)

Your ToDoListDatabase class does not contain any field with name listName on which you are calling getText(). Also you are not passing any parameter in your getList(). You should pass your EditText query in this getList() and then create query on this param.

Changes:

MainActivy.java

retrieve.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        showList(listName.getText().toString());
    }
});

public void showList(String listName){
    Cursor res = myDb.getList(listName);
    if(res.getCount() == 0){
    Toast.makeText(MainActivity.this,"Error finding list", Toast.LENGTH_LONG).show();
   //return;
    }
}

StringBuffer buffer = new StringBuffer();
    buffer.append(res.getString(2));
listDetails.setText(buffer); //Not working yet!!!!
}

ToDoListDatabase.java

public Cursor getList(String listName) {
  SQLiteDatabase db = this.getWritableDatabase();
  Cursor res = db.rawQuery("SELECT LIST FROM " + TABLE_NAME + " WHERE NAME ='" + listName+"'" , null);
  return res;
}

Update

Change your showList as

public void showList(String listName){
Cursor res = myDb.getList(listName);
if(res.getCount() == 0){
    Toast.makeText(MainActivity.this,"Error finding list", Toast.LENGTH_LONG).show();
   return;
}
  res.moveToFirst();
  StringBuffer buffer = new StringBuffer();
  while (!res.isAfterLast()) {
    buffer.append(res.getString(0));
    res.moveToNext();
  }
   res.close();
  listDetails.setText(buffer); //Not working yet!!!!
}

Good programming practice for database and databesehelper to wrap them around another class, open database when needed not on every query and making queries with strings not with views themselves. Check this thread for creating a singleton DatabaseManager and execute queries with it.

You are using listName (Edidtext) in your SQLiteOpenHelper class so ur getting error kindly pass the value of listName from your activity to method like.

//call and pass value like this.
showList(listName.getText().toString());

//or like this
String mListname = listName.getText().toString();

if(!TextUtils().isEmpty(mListname))//check if not empty
{ 
    showList(mListname);
}else{
    //handle error
}


// your method
public void showList(String listName)
{
   //your implementation
}

SQLiteOpenHelper doesnt extends View so u cannot use view there. but u can pass it to method parameter to access it.

showList(EditText listName)
{
    String val = listName.getText().toString();
}

//and pass your editText
showList(listName);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM