2016-01-21 81 views
-2

我想知道是否有人可以幫助我這個。Android遊標返回null

我打算在我的應用程序中使用Sqlite3,之前我從來沒有使用過它,所以我想製作一個單獨的項目來測試它,以確保我能夠把它記下來。

我遇到了這個問題,我插入幾個文本值到單個列表中,這似乎很好。在查詢表中的所有名稱並通過光標移動以獲取信息後,會發生此問題。

我測試這種方式是通過有幾個TextViews和一個按鈕。當按下按鈕時,TextView將其文本設置爲光標第一位置的值,然後將調用moveToNext(),並且下一個TextView將更新等。

第一個TextView始終正確更新,但是隻要在第一次調用moveToNext()後嘗試設置下一個,我會得到一個空例外。

有沒有辦法在調試器中看到Cursor的內容?我似乎無法弄清楚。

任何想法?下面的代碼:

MainActivity.java

package com.firsttread.anthony.databasetest; 

import android.content.ContentValues; 
import android.database.Cursor; 
import android.database.sqlite.SQLiteDatabase; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.widget.Button; 
import android.widget.ImageView; 
import android.widget.TextView; 

import com.firsttread.anthony.databasetest.DBContract.DBInfo; 

public class MainActivity extends AppCompatActivity { 

private Button testButton; 
private TextView text1, text2, text3, text4; 
private SQLiteDatabase db; 

private DatabaseHelper DBHelper; 



@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    testButton = (Button) findViewById(R.id.button); 
    text1 = (TextView) findViewById(R.id.textView); 
    text1 = (TextView) findViewById(R.id.textView2); 
    text1 = (TextView) findViewById(R.id.textView3); 
    text1 = (TextView) findViewById(R.id.textView4); 

    DBHelper = DatabaseHelper.getInstance(this); 

    db = DBHelper.getWritableDatabase(); 
    Log.d("MainActivity", "getWritable successful"); 

    ContentValues sessionValues1 = new ContentValues(); 
    sessionValues1.put(DBInfo.COLUMN_SESSION_NAME, "Sleep"); 

    ContentValues sessionValues2 = new ContentValues(); 
    sessionValues2.put(DBInfo.COLUMN_SESSION_NAME, "Work"); 

    ContentValues sessionValues3 = new ContentValues(); 
    sessionValues3.put(DBInfo.COLUMN_SESSION_NAME, "Reading"); 

    ContentValues sessionValues4 = new ContentValues(); 
    sessionValues4.put(DBInfo.COLUMN_SESSION_NAME, "Walking"); 


    long newRowId1, newRowId2, newRowId3, newRowId4; 
    //newRowId1 = db.insert(DBInfo.TABLE_SESSIONS, null, sessionValues1); 
    //newRowId2 = db.insert(DBInfo.TABLE_SESSIONS, null, sessionValues2); 
    //newRowId3 = db.insert(DBInfo.TABLE_SESSIONS, null, sessionValues3); 
    //newRowId4 = db.insert(DBInfo.TABLE_SESSIONS, null, sessionValues4); 

    String[] columns = {DBInfo.COLUMN_SESSION_NAME}; 

    //DBHelper.deleteDB(db); 

    final Cursor c = db.query(
      DBInfo.TABLE_SESSIONS, 
      columns, 
      null, 
      null, 
      null, 
      null, 
      null, 
      null 
    ); 


    testButton.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      c.moveToFirst(); 
      text1.setText(c.getString(c.getColumnIndex(DBInfo.COLUMN_SESSION_NAME))); 
      c.moveToNext(); 
      text2.setText(c.getString(c.getColumnIndex(DBInfo.COLUMN_SESSION_NAME))); 
      c.moveToNext(); 
      text3.setText(c.getString(c.getColumnIndex(DBInfo.COLUMN_SESSION_NAME))); 
      c.moveToNext(); 
      text4.setText(c.getString(c.getColumnIndex(DBInfo.COLUMN_SESSION_NAME))); 
     } 
    }); 


} 


@Override 
protected void onStop() { 
    super.onStop(); 
    db.close(); 
} 


} 

DataBaseHelper.java

package com.firsttread.anthony.databasetest; 


import android.content.Context; 
import android.database.sqlite.SQLiteDatabase; 
import android.database.sqlite.SQLiteOpenHelper; 
import android.util.Log; 

import com.firsttread.anthony.databasetest.DBContract.DBInfo; 

public class DatabaseHelper extends SQLiteOpenHelper { 

private static final String DATABASE_NAME = "SoundScope.db"; 
private static final int DATABASE_VERSION = 1; 

private static final String SQL_CREATE_TABLES = 
     "CREATE TABLE " + DBInfo.TABLE_SESSIONS +  " ("       + 
       DBInfo.COLUMN_SESSION_NAME  +  " TEXT NOT NULL PRIMARY KEY);" + 

     "CREATE TABLE " + DBInfo.TABLE_SOUND_INFO +  " ("       + 
       DBInfo._ID      +  " INTEGER PRIMARY KEY, "  + 
       DBInfo.COLUMN_SESSION_NAME  +  " TEXT NOT NULL, "    + 
       DBInfo.COLUMN_SOUND    +  " TEXT NOT NULL, "    + 
       DBInfo.COLUMN_VOLUME    +  " REAL NOT NULL); "   + 

     "CREATE TABLE " + DBInfo.TABLE_SOUNDS  +  " ("       + 
       DBInfo.COLUMN_SOUND_NAME   +  " TEXT NOT NULL PRIMARY KEY, " + 
       DBInfo.COLUMN_RAW     +  " INTEGER NOT NULL, "   + 
       DBInfo.COLUMN_DRAWABLE   +  " INTEGER NOT NULL);"   ; 



private static final String SQL_DELETE_TABLES = 
     "DROP TABLE IF EXISTS " + DBInfo.TABLE_SOUNDS  + ";" + 
     "DROP TABLE IF EXISTS " + DBInfo.TABLE_SOUND_INFO + ";" + 
     "DROP TABLE IF EXISTS " + DBInfo.TABLE_SESSIONS + ";" ; 



private static DatabaseHelper mInstance; 

public static synchronized DatabaseHelper getInstance(Context context){ 
    if(mInstance == null){ 
     mInstance = new DatabaseHelper(context.getApplicationContext()); 
     Log.d("DatabaseHelper","DatabaseHelper instance successful"); 
    } 
    return mInstance; 
} 

//private to ensure singleton 
private DatabaseHelper(Context context){ 
    super(context,DATABASE_NAME, null, DATABASE_VERSION); 
} 

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

@Override 
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 

} 

public void deleteDB(SQLiteDatabase db){ 
    db.delete(DBInfo.TABLE_SESSIONS,null,null); 
    //db.delete(DBInfo.TABLE_SOUND_INFO,null,null); 
    //db.delete(DBInfo.TABLE_SOUNDS,null,null); 
    db.execSQL(SQL_DELETE_TABLES); 
} 


} 

DBContract.java

package com.firsttread.anthony.databasetest; 


import android.provider.BaseColumns; 

public final class DBContract { 

public DBContract(){} 

public static abstract class DBInfo implements BaseColumns{ 

    /* 
    * 
    * database schema 
    * 
    * */ 

    //sessions table 
    public static final String TABLE_SESSIONS = "sessions"; 
    public static final String COLUMN_SESSION_NAME = "name"; 


    //sound_info 
    //uses BaseColumns _ID 
    public static final String TABLE_SOUND_INFO = "sound_info"; 
    public static final String COLUMN_SESSION = "session"; 
    public static final String COLUMN_SOUND = "sound"; 
    public static final String COLUMN_VOLUME = "volume"; 


    //soundS 
    public static final String TABLE_SOUNDS = "sounds"; 
    public static final String COLUMN_SOUND_NAME = "name"; 
    public static final String COLUMN_RAW = "raw"; 
    public static final String COLUMN_DRAWABLE = "drawable"; 

} 

} 

以及錯誤的堆棧跟蹤:

01-21 11:17:12.319 9149-9149/? E/Zygote: MountEmulatedStorage() 
01-21 11:17:12.319 9149-9149/? E/Zygote: v2 
01-21 11:17:12.319 9149-9149/? I/libpersona: KNOX_SDCARD checking this for 10075 
01-21 11:17:12.319 9149-9149/? I/libpersona: KNOX_SDCARD not a persona 
01-21 11:17:12.319 9149-9149/? I/SELinux: Function: selinux_compare_spd_ram, SPD-policy is existed. and_ver=SEPF_SAMSUNG-SM-N910A_5.1.1 ver=38 
01-21 11:17:12.319 9149-9149/? I/SELinux: Function: selinux_compare_spd_ram , priority [1] , priority version is VE=SEPF_SAMSUNG-SM-N910A_5.1.1_0038 
01-21 11:17:12.319 9149-9149/? E/Zygote: accessInfo : 0 
01-21 11:17:12.319 9149-9149/? E/SELinux: [DEBUG] get_category: variable seinfo: default sensitivity: NULL, cateogry: NULL 
01-21 11:17:12.319 9149-9149/? I/art: Late-enabling -Xcheck:jni 
01-21 11:17:12.359 9149-9149/? D/TimaKeyStoreProvider: TimaSignature is unavailable 
01-21 11:17:12.359 9149-9149/? D/ActivityThread: Added TimaKeyStore provider 
01-21 11:17:12.449 9149-9149/com.firsttread.anthony.databasetest D/SecWifiDisplayUtil: Metadata value : none 
01-21 11:17:12.489 9149-9149/com.firsttread.anthony.databasetest D/PhoneWindow: *FMB* installDecor mIsFloating : false 
01-21 11:17:12.489 9149-9149/com.firsttread.anthony.databasetest D/PhoneWindow: *FMB* installDecor flags : -2139029248 
01-21 11:17:12.549 9149-9149/com.firsttread.anthony.databasetest D/DatabaseHelper: DatabaseHelper instance successful 
01-21 11:17:12.559 9149-9149/com.firsttread.anthony.databasetest D/MainActivity: getWritable successful 
01-21 11:17:12.569 9149-9196/com.firsttread.anthony.databasetest D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true 
01-21 11:17:12.579 9149-9149/com.firsttread.anthony.databasetest D/PhoneWindow: *FMB* isFloatingMenuEnabled mFloatingMenuBtn : null 
01-21 11:17:12.579 9149-9149/com.firsttread.anthony.databasetest D/PhoneWindow: *FMB* isFloatingMenuEnabled return false 
01-21 11:17:12.599 9149-9149/com.firsttread.anthony.databasetest D/SRIB_DCS: log_dcs ThreadedRenderer::initialize entered! 
01-21 11:17:12.609 9149-9196/com.firsttread.anthony.databasetest I/Adreno: EGLInit: QTI Build: 07/16/15, 126f54a, If3804f16ae 
01-21 11:17:12.619 9149-9196/com.firsttread.anthony.databasetest I/OpenGLRenderer: Initialized EGL, version 1.4 
01-21 11:17:12.629 9149-9196/com.firsttread.anthony.databasetest D/OpenGLRenderer: Get maximum texture size. GL_MAX_TEXTURE_SIZE is 16384 
01-21 11:17:12.629 9149-9196/com.firsttread.anthony.databasetest D/OpenGLRenderer: Enabling debug mode 0 
01-21 11:17:12.699 9149-9149/com.firsttread.anthony.databasetest I/Timeline: Timeline: Activity_idle id: [email protected] time:177267508 
01-21 11:17:15.329 9149-9149/com.firsttread.anthony.databasetest D/ViewRootImpl: ViewPostImeInputStage ACTION_DOWN 
01-21 11:17:15.429 9149-9149/com.firsttread.anthony.databasetest D/AndroidRuntime: Shutting down VM 
01-21 11:17:15.429 9149-9149/com.firsttread.anthony.databasetest E/AndroidRuntime: FATAL EXCEPTION: main 
                       Process: com.firsttread.anthony.databasetest, PID: 9149 
                       java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference 
                        at com.firsttread.anthony.databasetest.MainActivity$1.onClick(MainActivity.java:87) 
                        at android.view.View.performClick(View.java:5242) 
                        at android.widget.TextView.performClick(TextView.java:10530) 
                        at android.view.View$PerformClick.run(View.java:21185) 
                        at android.os.Handler.handleCallback(Handler.java:739) 
                        at android.os.Handler.dispatchMessage(Handler.java:95) 
                        at android.os.Looper.loop(Looper.java:145) 
                        at android.app.ActivityThread.main(ActivityThread.java:6872) 
                        at java.lang.reflect.Method.invoke(Native Method) 
                        at java.lang.reflect.Method.invoke(Method.java:372) 
                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404) 
                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199) 

謝謝。

+0

您的CREATE_TABLES和DELETE_TABLES錯誤。您不能通過用分號分隔它們來執行多個SQL命令。您必須一次執行SQL命令。 –

+0

我認爲moveToNext會返回一個布爾值,您可以檢查。還DatabaseUtils.dumpCursorToString()幫助很多 –

+0

@ HrundiV.Bakshi這不是問題。多SQL命令似乎工作正常。問題在於,當通過id查找時,我將所有TextView都設置爲text1。它解決了這個問題。 –

回答

2

您與findViewById()

text1 = (TextView) findViewById(R.id.textView); 
text1 = (TextView) findViewById(R.id.textView2); 
text1 = (TextView) findViewById(R.id.textView3); 
text1 = (TextView) findViewById(R.id.textView4); 

你分配到唯一text1獲得NPE因爲一個問題,然後嘗試setText對他人(text2text3text4),這是空值。

+0

哇!謝謝。非常尷尬。 –