SQLiteDatabase上的nullPointerException db = dbHelper.getWritableDatabase();插入ContentProvider的方法

时间:2013-05-15 00:06:57

标签: android sqlite android-contentprovider

我在行上有一个nullPointerException,listView.setAdapter(adapter);在主要活动类中,无法弄清楚是什么原因造成的,有什么想法吗?

mainActivity类的onCreate方法

 public class MainActivity extends Activity implements LoaderManager.LoaderCallbacks<Cursor>{

private SimpleCursorAdapter adapter;
private LoaderManager loaderManager;
private CursorLoader cursorLoader;
private ListView listView;
private int primaryKey;
private String primaryKeyString;
private String testTitle;
private String testText;
private static final int LOADER_ID = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    primaryKey = 0;
    testTitle = "test title";
    testText = "test text";

    primaryKeyString = String.valueOf(primaryKey);
    getLoaderManager().initLoader(LOADER_ID, null, this);
    adapter = new SimpleCursorAdapter(this, R.layout.row_layout, null,
            new String[]{primaryKeyString, testTitle, testText}, new int[]{R.id.textView1, R.id.textView2, R.id.textView3},
            Adapter.NO_SELECTION);
    listView = (ListView) findViewById(R.id.listView1);
    listView.setAdapter(adapter);

    // load database with test values
    loadDatabase();

}

// load database with test data
public void loadDatabase(){
    Uri mNewUri;

    ContentValues mNewValues = new ContentValues();
    mNewValues.put(ProviderExample.NoteItems.TITLE, "test title");
    mNewValues.put(ProviderExample.NoteItems.TEXT, "test text value");

    mNewUri = getContentResolver().insert(ProviderExample.NoteItems.CONTENT_URI, mNewValues);

}

内容提供商类

 public class ProviderExample extends ContentProvider {

public static final String DATABASE_NAME = "notes.db";
public static final int DATABASE_VERSION = 1;
public static final String TABLE_NAME = "notes";
public static final String AUTHORITY = "com.example.contentproviderexample.providerexample";
public static final UriMatcher sUriMatcher;
private static final int NOTES = 1;
private static final int NOTES_ID = 2;
private static HashMap<String, String> notesProjectionMap;

 static {
        sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        sUriMatcher.addURI(AUTHORITY, TABLE_NAME, NOTES);
        sUriMatcher.addURI(AUTHORITY, TABLE_NAME + "/#", NOTES_ID);
    }

 public static interface NoteItems extends BaseColumns {

        // notes in the CONTENT_URI is often plural where the actual table name is often singular version of this word
        public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/notes");
        public static final String _ID = "_id";
        public static final String TITLE = "title";
        public static final String TEXT = "text";
        public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/vnd.example.providerexample";
        // static final String SINGLE_RECORD = "vnd.android.cursor.item/vnd.example.providerexample";
        public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/vnd.example.providerexample";
        // static final String MULTIPLE_RECORDS = "vnd.android.cursor.dir/vnd.example.providerexample"; 
        public static final String[] PROJECTION_ALL = {_ID, TITLE, TEXT};
        public static final String SORT_ORDER_DEFAULT = TITLE + " ASC";

 } // end LentItems interface

 private static class DatabaseHelper extends SQLiteOpenHelper{

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

     @Override
     public void onCreate(SQLiteDatabase db) {
     db.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" + NoteItems._ID + "ID INTEGER PRIMARY KEY AUTOINCREMENT, " +  
             NoteItems.TITLE + " TEXT, " + NoteItems.TEXT + " TEXT);");

     }

     @Override
     public void onUpgrade(SQLiteDatabase db, int previousVersion, int newVersion) {
     db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
     onCreate(db);
     }

 }

private DatabaseHelper dbHelper;

 @Override
public Uri insert(Uri uri, ContentValues initialValues) {
    if(sUriMatcher.match(uri)!=NOTES){
    throw new IllegalArgumentException("Unknown URI" + uri);
    }
    ContentValues values;
    if(initialValues!=null){
        values = new ContentValues(initialValues);
    }else{
        values = new ContentValues();
    }
  SQLiteDatabase db = dbHelper.getWritableDatabase(); // <--- nullPointerException here
    long rowId = db.insert(TABLE_NAME, null, values);

if(rowId > 0){
    Uri noteUri = ContentUris.withAppendedId(NoteItems.CONTENT_URI, rowId);
    getContext().getContentResolver().notifyChange(noteUri, null);
    return noteUri;
}
throw new SQLException("Failed to insert row into " + uri);
 }

编辑:现在nullPointerException已更改为SQLiteDatabase db = dbHelper.getWritableDatabase();插入方法

stakctrace:

AndroidRuntime(19638): FATAL EXCEPTION: main
AndroidRuntime(19638): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.contentproviderexample/com.example.contentproviderexample.MainActivity}: java.lang.NullPointerException
AndroidRuntime(19638): Caused by: java.lang.NullPointerException
AndroidRuntime(19638):  at com.example.contentproviderexample.ProviderExample.insert(ProviderExample.java:104)
AndroidRuntime(19638):  at android.content.ContentProvider$Transport.insert(ContentProvider.java:189)
AndroidRuntime(19638):  at android.content.ContentResolver.insert(ContentResolver.java:730)
AndroidRuntime(19638):  at com.example.contentproviderexample.MainActivity.loadDatabase(MainActivity.java:76)
/AndroidRuntime(19638):     at com.example.contentproviderexample.MainActivity.onCreate(MainActivity.java:47)

1 个答案:

答案 0 :(得分:0)

很难说没有堆栈跟踪,但似乎空指针不是适配器,而是listview。看起来你没有调用setContentView(),所以你的findViewById()方法可能返回null,然后你试图设置一个适配器到那个空对象。