2014-10-29 47 views
0

我目前在做關於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 protected]  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 
+0

你可以發佈你的logcat輸出嗎?! – 2014-10-29 15:26:14

+1

表未創建,因爲你在這裏錯過了一個空格:'MEMBER_PHONE +「INTEGER NOT NULL)' - 它必須是:'MEMBER_PHONE +」INTEGER NOT NULL)' – 2014-10-29 15:32:22

+0

10另外,'isValidPhone'總是返回'true '... – 2014-10-29 15:35:33

回答

1

我看不出有什麼毛病機智你的代碼,但是你沒有提供任何的LogCat,並且顯然沒有任何調試輸出被看到,所以如果沒有,那將會是一個黑暗中的刺。

至於一般的提示和技巧,你可以嘗試:

  1. 如果使用模擬器,你可以使用DDMS在Eclipse中瀏覽到您的數據庫文件,應該在:/數據/數據/ 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

我用拉我的數據庫和CP如果爲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的值,因爲您正在尋找電話。我會刪除你的數據庫並重新開始。你可能會發現它的工作原理。

+0

它沒有工作,我試圖在整數之前添加額外的空間。我已經添加了日誌貓,請幫助,非常感謝你 – 2014-10-29 16:37:55

+0

@JuliusLeo - 請參閱我的最終編輯。 – LokiSinclair 2014-10-29 16:44:32

+0

是的,我刪除了電話,它真的工作,非常感謝你:) – 2014-10-29 16:46:59