根据EditText中的用户输入从数据库接收数据

时间:2017-10-09 21:37:47

标签: java android sqlite android-sqlite

我有一个简单的问题,我确定我只是犯了一个小错误,但我无法解决。我试图从数据库中获取信息用户在EditText中输入的内容。我收到错误

  

" java.lang.IllegalStateException:无法读取第0行,第1列   CursorWindow。确保之前正确初始化了Cursor   从中访问数据。"。

这是我的主要活动课程

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!!!!
}

}

这是我的数据库类

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;
}

}

这是我的Android监视器

   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)

3 个答案:

答案 0 :(得分:1)

您的ToDoListDatabase类不包含名为listName的任何字段,您在其上调用getText()。您也没有在getList()中传递任何参数。您应该在此getList()中传递EditText查询,然后在此参数上创建查询。

更改:

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;
}

<强>更新

showList 更改为

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!!!!
}

答案 1 :(得分:0)

数据库和databesehelper的良好编程实践将它们包装在另一个类中,在需要时打开数据库而不是每个查询,并使用不具有视图本身的字符串进行查询。检查this thread以创建单例DatabaseManager并使用它执行查询。

答案 2 :(得分:0)

您正在SQLiteOpenHelper类中使用listName(Edidtext),因此您将获得错误,将listName的值从您的活动传递给类似的方法。

//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并不扩展View,所以你不能在那里使用视图。 但你可以将它传递给方法参数来访问它。

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

//and pass your editText
showList(listName);