2016-01-21 80 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

哇!谢谢。非常尴尬。 –