插入和查看数据时出错

时间:2014-10-29 15:21:08

标签: android eclipse sqlite

我目前正在撰写关于Android应用程序开发的论文,我想创建一个注册屏幕,用户可以输入他们的数据和存储在SQLite数据库中的数据,我在youtube上观看了新的波士顿频道这个功能,并以完全相同的方式,但它不起作用。我不知道什么是错的,我甚至都不知道我的数据输入是否正确, 你能帮我告诉我这些代码中有什么问题吗? 谢谢。

package com.thesis.teamizer;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class Database {

public static final String DATABASE_NAME = "TeamizerDB.db";
public static final String TABLE_MEMBER = "Member";
public static final int DATABASE_VERSION = 1;
public static final String MEMBER_USERNAME = "Username";
public static final String MEMBER_PASSWORD = "Password";
public static final String MEMBER_EMAIL = "Email";
public static final String MEMBER_PHONE = "Phone";
public DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;

public static class DbHelper extends SQLiteOpenHelper {

    public DbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        db.execSQL("CREATE TABLE " + TABLE_MEMBER + " (" + MEMBER_USERNAME
                + " TEXT PRIMARY KEY NOT NULL, " + MEMBER_PASSWORD
                + " TEXT NOT NULL, " + MEMBER_EMAIL + " TEXT NOT NULL, "
                + MEMBER_PHONE + "INTEGER NOT NULL);");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_MEMBER);
        onCreate(db);
    }

}

public Database(Context c) {
    ourContext = c;
}

public Database open() throws SQLException {
    ourHelper = new DbHelper(ourContext);
    ourDatabase = ourHelper.getWritableDatabase();
    return this;
}

public void close() {

    ourHelper.close();
}

public boolean createEntry(String username, String pass, String email,
        String phone) {
    // TODO Auto-generated method stub
    ContentValues cv = new ContentValues();
    cv.put(MEMBER_USERNAME, username);
    cv.put(MEMBER_PASSWORD, pass);
    cv.put(MEMBER_EMAIL, email);
    cv.put(MEMBER_PHONE, phone);
    ourDatabase.insert(TABLE_MEMBER, null, cv);
    return true;
}

public String getData() {
    // TODO Auto-generated method stub
    String[] columns = new String[] { MEMBER_USERNAME, MEMBER_PASSWORD,
            MEMBER_EMAIL, MEMBER_PHONE };
    Cursor c = ourDatabase.query(TABLE_MEMBER, columns, null, null, null,
            null, null);
    /*
     * Cursor c = ourDatabase.query(TABLE_MEMBER, columns, null, null, null,
     * null, null);
     */
    String result = "";

    int iUsername = c.getColumnIndex(MEMBER_USERNAME);
    int iPassword = c.getColumnIndex(MEMBER_PASSWORD);
    int iEmail = c.getColumnIndex(MEMBER_EMAIL);
    int iPhone = c.getColumnIndex(MEMBER_PHONE);

    for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {

        result = result + c.getString(iUsername) + "\n";

    }
    return result;
}
}

RegisScreen.java

package com.thesis.teamizer; 

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class RegisScreen extends Activity {

private EditText emailEditText;
private EditText usernameEditText;
private EditText passEditText;
private EditText confPassEditText;
private EditText phoneEditText;
private Button registerButton;


@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.regis_screen);

    declaration();
    validation();

}

private void validation() {
    // TODO Auto-generated method stub
    registerButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            int flag = 0;
            final String username = usernameEditText.getText().toString();
            final String email = emailEditText.getText().toString();
            final String pass = passEditText.getText().toString();
            final String confpas = confPassEditText.getText().toString();
            final String phone = phoneEditText.getText().toString();
            // Validating username
            if (!isValidUsername(username)) {
                usernameEditText
                        .setError("Username Must be Filled, Have at Least 6 Characters Long, and Must Not Contain Space");
                flag++;
            }
            // Validating email
            if (!isValidEmail(email)) {
                emailEditText.setError("Invalid Email Format");
                flag++;
            }
            // Validating password
            if (!isValidPassword(pass)) {
                passEditText.setError("Invalid Password");
                flag++;
            }
            // Validating confirm password
            if (!isValidConfPass(confpas, pass)) {
                confPassEditText.setError("Password missmatch");
                flag++;
            }
            // Validating phone
            if (!isValidPhone(phone)) {
                phoneEditText
                        .setError("Phone can only between 10-12 digits long");
                flag++;
            }

            // If every validation == true
            if (flag == 0) {
                boolean didItWork = true;
                try {
                    Database entry = new Database(RegisScreen.this);
                    entry.open();
                    entry.createEntry(username, pass, email, phone);
                    entry.close();
                } catch (Exception e) {
                } finally {
                    if (didItWork) {
                        Dialog d = new Dialog(RegisScreen.this);
                        d.setTitle("Yoii");
                        TextView tv = new TextView(RegisScreen.this);
                        tv.setText("Success");
                        d.setContentView(tv);
                        d.show();
                    }
                }
                    Intent intent = new Intent("com.thesis.teamizer.SQLVIEWS");
                    startActivity(intent);

            }
        }

    });
}

private void declaration() {
    // TODO Auto-generated method stub
    usernameEditText = (EditText) findViewById(R.id.editText_username);
    emailEditText = (EditText) findViewById(R.id.editText_email);
    passEditText = (EditText) findViewById(R.id.editText_password);
    confPassEditText = (EditText) findViewById(R.id.editText_confpassword);
    phoneEditText = (EditText) findViewById(R.id.editText_phone);
    registerButton = (Button) findViewById(R.id.btn_signup);
}

// Username Validation
private boolean isValidUsername(String username) {
    // TODO Auto-generated method stub

    if (username != null && username.length() > 6
            && !username.contains(" ")) {
        return true;
    }

    return false;
}

// Email Validation
private boolean isValidEmail(String email) {
    String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
            + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

    Pattern pattern = Pattern.compile(EMAIL_PATTERN);
    Matcher matcher = pattern.matcher(email);
    return matcher.matches();
}

// Password Validation
private boolean isValidPassword(String pass) {
    if (pass != null && pass.length() > 6) {
        return true;
    }
    return false;
}

private boolean isValidConfPass(String confpas, String pass) {
    if (confpas.equals(pass)) {
        return true;
    }
    return false;
}

private boolean isValidPhone(String phone) {
    if (phone.length() > 9 || phone.length() < 13) {
        return true;
    }
    return false;
}
}

SQLViews.java

package com.thesis.teamizer;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class SQLViews extends Activity{

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.sqlview);
    TextView tv = (TextView) findViewById(R.id.tvSQLinfo);
    Database info = new Database (this);
    info.open();
    String data = info.getData();       
    info.close();
    tv.setText(data); 

} 

}

以下是日志猫:

    10-29 23:27:12.421: E/SQLiteDatabase(30715): Error inserting Email=djdjsj@sjsjsjs.com     Password=juliusleo Username=sjsjsjsjs
10-29 23:27:12.421: E/SQLiteDatabase(30715): android.database.sqlite.SQLiteConstraintException: Member.PhoneINTEGER may not be NULL (code 19)
10-29 23:27:12.421: E/SQLiteDatabase(30715):    at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
10-29 23:27:12.421: E/SQLiteDatabase(30715):    at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:972)
10-29 23:27:12.421: E/SQLiteDatabase(30715):    at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
10-29 23:27:12.421: E/SQLiteDatabase(30715):    at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
10-29 23:27:12.421: E/SQLiteDatabase(30715):    at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1603)
10-29 23:27:12.421: E/SQLiteDatabase(30715):    at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1473)
10-29 23:27:12.421: E/SQLiteDatabase(30715):    at com.thesis.teamizer.Database.createEntry(Database.java:69)
10-29 23:27:12.421: E/SQLiteDatabase(30715):    at com.thesis.teamizer.RegisScreen$1.onClick(RegisScreen.java:83)
10-29 23:27:12.421: E/SQLiteDatabase(30715):    at android.view.View.performClick(View.java:4654)
10-29 23:27:12.421: E/SQLiteDatabase(30715):    at android.view.View$PerformClick.run(View.java:19438)
10-29 23:27:12.421: E/SQLiteDatabase(30715):    at android.os.Handler.handleCallback(Handler.java:733)
10-29 23:27:12.421: E/SQLiteDatabase(30715):    at android.os.Handler.dispatchMessage(Handler.java:95)
10-29 23:27:12.421: E/SQLiteDatabase(30715):    at android.os.Looper.loop(Looper.java:146)
10-29 23:27:12.421: E/SQLiteDatabase(30715):    at android.app.ActivityThread.main(ActivityThread.java:5602)
10-29 23:27:12.421: E/SQLiteDatabase(30715):    at java.lang.reflect.Method.invokeNative(Native Method)
10-29 23:27:12.421: E/SQLiteDatabase(30715):    at java.lang.reflect.Method.invoke(Method.java:515)
10-29 23:27:12.421: E/SQLiteDatabase(30715):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
10-29 23:27:12.421: E/SQLiteDatabase(30715):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
10-29 23:27:12.421: E/SQLiteDatabase(30715):    at dalvik.system.NativeStart.main(Native Method)
10-29 23:27:12.446: D/TextLayoutCache(30715): Enable myanmar Zawgyi converter
10-29 23:27:12.446: D/TextLayoutCache(30715): Enable myanmar Zawgyi converter
10-29 23:27:12.501: D/TextLayoutCache(30715): Enable myanmar Zawgyi converter
10-29 23:27:12.501: D/TextLayoutCache(30715): Enable myanmar Zawgyi converter
10-29 23:27:12.551: E/SQLiteLog(30715): (1) no such column: Phone
10-29 23:27:12.551: D/AndroidRuntime(30715): Shutting down VM
10-29 23:27:12.551: W/dalvikvm(30715): threadid=1: thread exiting with uncaught exception (group=0x41d92c08)
10-29 23:27:12.556: E/AndroidRuntime(30715): FATAL EXCEPTION: main
10-29 23:27:12.556: E/AndroidRuntime(30715): Process: com.thesis.teamizer, PID: 30715
10-29 23:27:12.556: E/AndroidRuntime(30715): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.thesis.teamizer/com.thesis.teamizer.SQLViews}: android.database.sqlite.SQLiteException: no such column: Phone (code 1): , while compiling: SELECT Username, Password, Email, Phone FROM Member
10-29 23:27:12.556: E/AndroidRuntime(30715):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2413)
10-29 23:27:12.556: E/AndroidRuntime(30715):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2471)
10-29 23:27:12.556: E/AndroidRuntime(30715):    at android.app.ActivityThread.access$900(ActivityThread.java:175)
10-29 23:27:12.556: E/AndroidRuntime(30715):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
10-29 23:27:12.556: E/AndroidRuntime(30715):    at android.os.Handler.dispatchMessage(Handler.java:102)
10-29 23:27:12.556: E/AndroidRuntime(30715):    at android.os.Looper.loop(Looper.java:146)
10-29 23:27:12.556: E/AndroidRuntime(30715):    at android.app.ActivityThread.main(ActivityThread.java:5602)
10-29 23:27:12.556: E/AndroidRuntime(30715):    at java.lang.reflect.Method.invokeNative(Native Method)
10-29 23:27:12.556: E/AndroidRuntime(30715):    at java.lang.reflect.Method.invoke(Method.java:515)
10-29 23:27:12.556: E/AndroidRuntime(30715):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
10-29 23:27:12.556: E/AndroidRuntime(30715):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
10-29 23:27:12.556: E/AndroidRuntime(30715):    at dalvik.system.NativeStart.main(Native Method)
10-29 23:27:12.556: E/AndroidRuntime(30715): Caused by: android.database.sqlite.SQLiteException: no such column: Phone (code 1): , while compiling: SELECT Username, Password, Email, Phone FROM Member
10-29 23:27:12.556: E/AndroidRuntime(30715):    at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
10-29 23:27:12.556: E/AndroidRuntime(30715):    at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1113)
10-29 23:27:12.556: E/AndroidRuntime(30715):    at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:690)
10-29 23:27:12.556: E/AndroidRuntime(30715):    at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
10-29 23:27:12.556: E/AndroidRuntime(30715):    at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
10-29 23:27:12.556: E/AndroidRuntime(30715):    at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
10-29 23:27:12.556: E/AndroidRuntime(30715):    at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
10-29 23:27:12.556: E/AndroidRuntime(30715):    at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1448)
10-29 23:27:12.556: E/AndroidRuntime(30715):    at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1295)
10-29 23:27:12.556: E/AndroidRuntime(30715):    at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1166)
10-29 23:27:12.556: E/AndroidRuntime(30715):    at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1334)
10-29 23:27:12.556: E/AndroidRuntime(30715):    at com.thesis.teamizer.Database.getData(Database.java:77)
10-29 23:27:12.556: E/AndroidRuntime(30715):    at com.thesis.teamizer.SQLViews.onCreate(SQLViews.java:17)
10-29 23:27:12.556: E/AndroidRuntime(30715):    at android.app.Activity.performCreate(Activity.java:5451)
10-29 23:27:12.556: E/AndroidRuntime(30715):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
10-29 23:27:12.556: E/AndroidRuntime(30715):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2377)
10-29 23:27:12.556: E/AndroidRuntime(30715):    ... 11 more
10-29 23:27:14.241: I/dalvikvm-heap(30856): Grow heap (frag case) to 12.955MB for 4367376-byte allocation
10-29 23:27:14.341: D/TextLayoutCache(30856): Enable myanmar Zawgyi converter
10-29 23:27:14.341: D/TextLayoutCache(30856): Enable myanmar Zawgyi converter
10-29 23:27:14.341: D/TextLayoutCache(30856): Enable myanmar Zawgyi converter
10-29 23:27:14.341: D/TextLayoutCache(30856): Enable myanmar Zawgyi converter
10-29 23:27:14.361: D/libEGL(30856): loaded /system/lib/egl/libEGL_mali.so
10-29 23:27:14.366: D/libEGL(30856): loaded /system/lib/egl/libGLESv1_CM_mali.so
10-29 23:27:14.371: D/libEGL(30856): loaded /system/lib/egl/libGLESv2_mali.so
10-29 23:27:14.376: E/(30856): Device driver API match
10-29 23:27:14.376: E/(30856): Device driver API version: 29
10-29 23:27:14.376: E/(30856): User space API version: 29 
10-29 23:27:14.376: E/(30856): mali: REVISION=Linux-r3p2-01rel3 BUILD_DATE=Tue Jul 22 19:59:34 KST 2014 

1 个答案:

答案 0 :(得分:1)

我没有看到您的代码有任何问题,但是您没有提供任何LogCat,并且明显缺乏任何调试输出,所以没有它,它就是对于什么是错误的,他们会在黑暗中被刺伤。

关于一般提示和提示,您可以尝试:

  1. 如果使用模拟器,您可以使用Eclipse中的DDMS浏览到您的数据库文件,应该位于:/data/data/com.YOURAPP/databases/YOURDB-拉动数据库后,您可以使用一个免费的工具,例如:SQLiteStudio你可以检查你的数据库中有什么(如果有的话)。

  2. 如果您在设备上运行,则可以使用批处理脚本,例如:

    cd C:\adt-bundle-windows-x86_64-20140321\sdk\platform-tools adb -d shell "run-as com.goosesys.gaggle cat /data/data/com.goosesys.gaggle/databases/goosemob > /sdcard/goosemob.sqlite" pause

  3. 我用它来拉取我的数据库和cp if到SD卡以便于检索。您必须更改路径等(对于adb和您的应用/数据库路径)。

    如果做不到这一点,你将不得不向我们提供更多信息。如果只做一个简单的SELECT *,或者从查询返回的行数,可能会添加一些显示行数的输出。任何事都会有所帮助。

    当您提供更多信息时,我很乐意提供更多帮助。

    编辑

    发现了这个:

    db.execSQL("CREATE TABLE " + TABLE_MEMBER + " (" + MEMBER_USERNAME
                + " TEXT PRIMARY KEY NOT NULL, " + MEMBER_PASSWORD
                + " TEXT NOT NULL, " + MEMBER_EMAIL + " TEXT NOT NULL, "
                + MEMBER_PHONE + "INTEGER NOT NULL);");
    

    应该是:

    db.execSQL("CREATE TABLE " + TABLE_MEMBER + " (" + MEMBER_USERNAME
                + " TEXT PRIMARY KEY NOT NULL, " + MEMBER_PASSWORD
                + " TEXT NOT NULL, " + MEMBER_EMAIL + " TEXT NOT NULL, "
                + MEMBER_PHONE + " INTEGER NOT NULL);"); // NOTE THE SPACE IN FRONT OF "INTEGER NOT NULL"
    

    您的数据库可能甚至没有被创建过。因此,您应该在LogCat中看到异常。

    编辑 Funkystein打败了我!

    编辑

    android.database.sqlite.SQLiteConstraintException: Member.PhoneINTEGER may not be NULL (code 19)
    

    那里有一个问题。您没有为PhoneINTEGER输入值,因为您正在寻找手机。我删除了你的数据库并重新开始。您可能会发现它有效。