Android SQLite INSERT导致应用程序崩溃

时间:2012-04-27 20:04:06

标签: android sqlite insert crash

我正在尝试将一些数据插入到我创建的表中。我有这门课:

public class DataBase extends SQLiteOpenHelper {
private static final String DB_NAME = "db_mydatabase";
private static final int DB_VERSION = 1;

private static final String TBL_USERS = "users";
private static final String TBL_USERSE_CREATE = "CREATE TABLE IF NOT EXISTS "
                            + TBL_USERS + "(id integer PRIMARY KEY AUTOINCREMENT, "
                            + "usr varchar(128) NOT NULL UNIQUE, psw varchar(512));";

public DataBase(Context context) {
    super(context, DB_NAME, null, DB_VERSION);
}

public List<String> GetUsersList() {
    List<String> users = new ArrayList<String>();
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor c = db.rawQuery("SELECT id, usr FROM " + TBL_USERS, null);
    if (c != null ) {
        if  (c.moveToFirst()) {
            do {
                String firstName = c.getString(c.getColumnIndex("USR"));
                users.add(firstName);
                } while (c.moveToNext());
        }
    }
    return users;
}

public void CreateNewUser(String username, String password) {
    SQLiteDatabase db = this.getWritableDatabase();
    db.execSQL("INSERT INTO " + TBL_USERS + " (usr, psw) VALUES ('" + username + "', '" + password + "')");
            //If I comment this line, it doesn't crashes anymore, but I don't see why
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(TBL_USERSE_CREATE);
}

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

}

因此,当我按下REGISTER按钮时,EditText中的用户名和密码将被发送到CreateNewUser。我的Activity类看起来像这样:

public class RegisterActivity extends Activity {
List<String> values;
DataBase dtb;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.register);

    ListView listView = (ListView) findViewById(R.id.listView1);

    dtb = new DataBase(MainActivity.MainContext);
    values = dtb.GetUsersList();

    listView.setAdapter(new ArrayAdapter<String>(MainActivity.MainContext, R.layout.listitem, values));

    Button Create = (Button) findViewById(R.id.Create);
    Create.setOnClickListener(new View.OnClickListener() {
       public void onClick(View arg0) {
           EditText username = (EditText)findViewById(R.id.Username);
           EditText password = (EditText)findViewById(R.id.Password);
           if (username.getText().length()>0 && password.getText().length()>0) {
               if (values.indexOf(username.getText())<0) {
                   dtb.CreateNewUser(username.getText().toString(), password.getText().toString());
                   values = dtb.GetUsersList();
               }
           }
       }
    });
}

}

我是SQLite程序员的初学者,我得到了这个可理解的严重错误并崩溃了

> **04-24 12:30:51.340: E/CursorWindow(7986): Bad request for field slot 0,-1. numRows = 1, numColumns = 2** 04-24 12:30:51.350:
> D/AndroidRuntime(7986): Shutting down VM 04-24 12:30:51.350:
> W/dalvikvm(7986): threadid=3: thread exiting with uncaught exception
> (group=0x4001b188) 04-24 12:30:51.350: E/AndroidRuntime(7986):
> Uncaught handler: thread main exiting due to uncaught exception
> **04-24 12:30:51.380: E/AndroidRuntime(7986): java.lang.IllegalStateException: get field slot from row 0 col -1
> failed** 04-24 12:30:51.380: E/AndroidRuntime(7986):  at
> android.database.CursorWindow.getString_native(Native Method) 04-24
> 12:30:51.380: E/AndroidRuntime(7986):     at
> android.database.CursorWindow.getString(CursorWindow.java:329) 04-24
> 12:30:51.380: E/AndroidRuntime(7986):     at
> android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:49)
> 04-24 12:30:51.380: E/AndroidRuntime(7986):   at
> com.bma.myagenda.DataBase.GetUsersList(DataBase.java:32) 04-24
> 12:30:51.380: E/AndroidRuntime(7986):     at
> com.bma.myagenda.RegisterActivity$1.onClick(RegisterActivity.java:46)
> 04-24 12:30:51.380: E/AndroidRuntime(7986):   at
> android.view.View.performClick(View.java:2364) 04-24 12:30:51.380:
> E/AndroidRuntime(7986):   at
> android.view.View.onTouchEvent(View.java:4179) 04-24 12:30:51.380:
> E/AndroidRuntime(7986):   at
> android.widget.TextView.onTouchEvent(TextView.java:6541) 04-24
> 12:30:51.380: E/AndroidRuntime(7986):     at
> android.view.View.dispatchTouchEvent(View.java:3709) 04-24
> 12:30:51.380: E/AndroidRuntime(7986):     at
> android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884) 04-24
> 12:30:51.380: E/AndroidRuntime(7986):     at
> android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884) 04-24
> 12:30:51.380: E/AndroidRuntime(7986):     at
> android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884) 04-24
> 12:30:51.380: E/AndroidRuntime(7986):     at
> android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884) 04-24
> 12:30:51.380: E/AndroidRuntime(7986):     at
> android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884) 04-24
> 12:30:51.380: E/AndroidRuntime(7986):     at
> com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1659)
> 04-24 12:30:51.380: E/AndroidRuntime(7986):   at
> com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1107)
> 04-24 12:30:51.380: E/AndroidRuntime(7986):   at
> android.app.Activity.dispatchTouchEvent(Activity.java:2061) 04-24
> 12:30:51.380: E/AndroidRuntime(7986):     at
> com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1643)
> 04-24 12:30:51.380: E/AndroidRuntime(7986):   at
> android.view.ViewRoot.handleMessage(ViewRoot.java:1691) 04-24
> 12:30:51.380: E/AndroidRuntime(7986):     at
> android.os.Handler.dispatchMessage(Handler.java:99) 04-24
> 12:30:51.380: E/AndroidRuntime(7986):     at
> android.os.Looper.loop(Looper.java:123) 04-24 12:30:51.380:
> E/AndroidRuntime(7986):   at
> android.app.ActivityThread.main(ActivityThread.java:4363) 04-24
> 12:30:51.380: E/AndroidRuntime(7986):     at
> java.lang.reflect.Method.invokeNative(Native Method) 04-24
> 12:30:51.380: E/AndroidRuntime(7986):     at
> java.lang.reflect.Method.invoke(Method.java:521) 04-24 12:30:51.380:
> E/AndroidRuntime(7986):   at
> com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
> 04-24 12:30:51.380: E/AndroidRuntime(7986):   at
> com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618) 04-24
> 12:30:51.380: E/AndroidRuntime(7986):     at
> dalvik.system.NativeStart.main(Native Method)

3 个答案:

答案 0 :(得分:1)

尝试用以下代码替换插入代码:

public void CreateNewUser(String username, String password) {
    SQLiteDatabase db = this.getWritableDatabase();

ContentValues initialValues = new ContentValues();
initialValues.put(usr, username);
initialValues.put(psw, password);

db.insert(TBL_USERS, null, initialValues);
}

答案 1 :(得分:1)

变化

String firstName = c.getString(c.getColumnIndex("USR"));

String firstName = c.getString(1);

错误

CursorWindow(7986): Bad request for field slot 0,-1. numRows = 1, numColumns = 2
...java.lang.IllegalStateException: get field slot from row 0 col -1 failed

表示您在Cursor的第一行中请求索引为-1的列。从Cursor请求数据的代码中唯一的部分是c.getString(columnIndex)。这意味着你到达那里的columnIndex必须是-1。现在,如果您阅读了Cursor.getColumnIndex "USR",您会看到:

  

返回给定列名的从零开始的索引,如果该列不存在,则返回-1。

意味着没有名为"usr"的列。如果查看表定义,可以看到将其命名为String firstName = c.getString(c.getColumnIndex("usr")); 。所以要修复你的错误,你可以做到

Cursor

但是(这是可选的并且可能会导致错误):由于您SELECT id, usr FROM .. id的请求,因此我们保证0是列usr和{{1}您的1中的列Cursor就是1,您可以直接使用if (c != null ) { while(c.moveToNext()) { String firstName = c.getString(1); users.add(firstName); } c.close(); }

还有其他一些可以改进的事情:

if () do {} while ()

a)您可以将while() {}简化为简单Cursor
b)一旦您不需要,您应该关闭INSERT。你至少可以防止这种警告。

您还应该使用execSQL的bindArgs版本进行'针对错误/注入攻击的保存。尝试在用户名中输入',您会看到它会以您的方式崩溃。使用bindArgs会阻止它,因为它会自动转义db.execSQL("INSERT INTO " + TBL_USERS + " (usr, psw) VALUES (?, ?)", new String[]{ username, password });

Cursor
  

如果我评论这一行,它不会再崩溃,但我不明白为什么

这是因为varchar(128)为空,然后您没有找到导致错误的代码。

最后一件事:{{1}}在SQLite中没有任何影响,因为:

  

请注意,SQLite会忽略括号后面的数字参数(例如:“VARCHAR(255)”) - SQLite不会对字符串,BLOB或数值的长度施加任何长度限制。 documentation

答案 2 :(得分:1)

变化:

String firstName = c.getString(c.getColumnIndex("USR"));

要:

String firstName = c.getString(c.getColumnIndex("usr"));  //USR != usr