将数据插入Android应用程序数据库时数据类型不匹配

时间:2016-07-16 04:34:18

标签: java database string android-studio sql-insert

我不完全确定会发生什么,我知道当我尝试插入时存在不匹配,但是当我仔细检查我的代码时,我无法理解为什么它会吐出那个错误。我只是想插入一个用户名和密码(两个都是字符串)。

背景:

在我的 RegisterLoginActivity.java 中,当用户点击TextView“创建帐户”时,它会抓取用户名和密码并将其转换为字符串。

然后在我的 DatabaseOperations.java 中,我使用函数putInformation()来插入数据。

我的 TableData.java 只包含我的表信息。

RegisterLoginActivity.java;

package com.example.envy.energyvue;

import android.content.Context;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class RegisterLoginActivity extends AppCompatActivity {

    EditText USER_NAME, USER_PASS;
    TextView REG;
    String user_name, user_pass;
    Context ctx = this;
    Button login;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        //getActionBar().hide();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register_login);

        USER_NAME = (EditText) findViewById(R.id.userText);
        USER_PASS = (EditText) findViewById(R.id.passText);
        REG = (TextView) findViewById(R.id.createAccount);
        REG.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                user_name = USER_NAME.getText().toString();
                user_pass = USER_PASS.getText().toString();

                DatabaseOperations DB = new DatabaseOperations(ctx);
                DB.putInformation(DB,user_name, user_pass);
            }
        });

       // IGNORE THIS PORTION, IT IS FOR LOGGING IN AFTER I REGISTER
       //********************************************
        login = (Button) findViewById(R.id.login);
        login.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                user_name = USER_NAME.getText().toString();
                user_pass = USER_NAME.getText().toString();
                DatabaseOperations DB = new DatabaseOperations(ctx);
                Cursor CR = DB.getInformation(DB);
                CR.moveToFirst();
                boolean loginstatus = false;
                String NAME = "";

                do{
                    if(user_name.equals(CR.getString(0)) && user_pass.equals(CR.getString(1))){
                        loginstatus = true;
                    }
                }while(CR.moveToFirst());

                if(loginstatus){
                    Toast.makeText(getBaseContext(), "Login Success", Toast.LENGTH_LONG).show();
                }
                else{
                    Toast.makeText(getBaseContext(), "Login Failed", Toast.LENGTH_LONG).show();
                }
            }
            });
        }


}

DatabaseOperations.java;

package com.example.envy.energyvue;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * Created by Envy on 7/13/2016.
 *
 *     private static final String SQL_CREATE_ENTRIES =
 "CREATE TABLE " + TableData.TableInfo.TABLE_NAME + " (" + TableData.TableInfo._ID +
 " INTEGER PRIMARY KEY," + TableData.TableInfo.COLUMN_NAME_USER_ID + TEXT_TYPE + COMMA_SEP + TableData.TableInfo.COLUMN_NAME_PASSWORD + TEXT_TYPE + " );";
 */
public class DatabaseOperations extends SQLiteOpenHelper{

    public static final int DATABASE_VERSION = 1;
    public static final String DATABASE_NAME = "UserData.db";

    private static final String TEXT_TYPE = " TEXT";
    private static final String COMMA_SEP = ",";
    private static final String SQL_CREATE_ENTRIES =
            "CREATE TABLE " + TableData.TableInfo.TABLE_NAME + " (" + TableData.TableInfo._ID +
                    " INTEGER PRIMARY KEY," + TableData.TableInfo.COLUMN_NAME_USER_ID + TEXT_TYPE + COMMA_SEP + TableData.TableInfo.COLUMN_NAME_PASSWORD + TEXT_TYPE + " );";

    private static final String SQL_DELETE_ENTRIES =
            "DROP TABLE IF EXISTS " + TableData.TableInfo.TABLE_NAME;

    public DatabaseOperations(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    public void onCreate(SQLiteDatabase db) {
        db.execSQL(SQL_CREATE_ENTRIES);
    }

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // This database is only a cache for online data, so its upgrade policy is
        // to simply to discard the data and start over
        db.execSQL(SQL_DELETE_ENTRIES);
        onCreate(db);
    }

    public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        onUpgrade(db, oldVersion, newVersion);
    }

    public void putInformation(DatabaseOperations dop, String user_id, String password){
        SQLiteDatabase SQ = dop.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put(TableData.TableInfo.COLUMN_NAME_USER_ID, user_id);
        cv.put(TableData.TableInfo.COLUMN_NAME_PASSWORD, password);



        System.out.print("LOLOLSDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD");
        long newRowId;
        newRowId = SQ.insert(
                TableData.TableInfo.TABLE_NAME,
                null,
                cv);
    }

    public Cursor getInformation(DatabaseOperations dop){
        SQLiteDatabase SQ = dop.getReadableDatabase();
        String[] projection = {
                TableData.TableInfo._ID,
                TableData.TableInfo.COLUMN_NAME_USER_ID,
                TableData.TableInfo.COLUMN_NAME_PASSWORD
            };
        Cursor CR = SQ.query(TableData.TableInfo.TABLE_NAME, projection, null, null, null, null, null);
        return CR;

    }


}

TableData.java;

package com.example.envy.energyvue;

import android.provider.BaseColumns;

/**
 * Created by Envy on 7/13/2016.
 */
public class TableData {

    public TableData(){}

    public static abstract class TableInfo implements BaseColumns {
        public static final String TABLE_NAME = "login_information";
        public static final String COLUMN_NAME_USER_ID = "user_id";
        public static final String COLUMN_NAME_PASSWORD = "password";

    }

}

错误:

07-15 21:18:47.996 24361-24361/com.example.envy.energyvue E/SQLiteLog: (20) statement aborts at 5: [INSERT INTO login_information(password,user_id) VALUES (?,?)] datatype mismatch
07-15 21:18:47.996 24361-24361/com.example.envy.energyvue E/SQLiteDatabase: Error inserting password= bbb user_id=bbb
                                                                            android.database.sqlite.SQLiteDatatypeMismatchException: datatype mismatch (code 20)
                                                                            #################################################################
                                                                            Error Code : 20 (SQLITE_MISMATCH)
                                                                            Caused By : Data type mismatch.
                                                                                (datatype mismatch (code 20))
                                                                            #################################################################
                                                                                at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
                                                                                at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:915)
                                                                                at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
                                                                                at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
                                                                                at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1609)
                                                                                at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1479)
                                                                                at com.example.envy.energyvue.DatabaseOperations.putInformation(DatabaseOperations.java:59)
                                                                                at com.example.envy.energyvue.RegisterLoginActivity$1.onClick(RegisterLoginActivity.java:37)
                                                                                at android.view.View.performClick(View.java:5697)
                                                                                at android.widget.TextView.performClick(TextView.java:10814)
                                                                                at android.view.View$PerformClick.run(View.java:22526)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:158)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:7229)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

1 个答案:

答案 0 :(得分:0)

好吧......好几个小时之后,我想出来了......我把我的数据库名称加上了“.db”扩展名,这让事情搞得一团糟。