我正在使用android中的内容提供程序创建一个数据库,但数据库根本不工作

时间:2017-03-18 07:30:02

标签: java android sqlite

这是笔记应用编码的主页:

public class Note_mainActivity extends Fragment implements NoteRecyclerAdapter.NoteOnClick,LoaderManager.LoaderCallbacks<Cursor>{

private RecyclerView mRecycler8;
private NoteRecyclerAdapter mAdapter8;
private List savedNote;
private MyDbHelper myDbHelper;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View rootView1 = inflater.inflate(R.layout.activity_note_main,container,false);
    savedNote = new ArrayList<>();
    mRecycler8 = (RecyclerView)rootView1.findViewById(R.id.show_note);
    WrappedLinearLayoutManager linearLayoutManager = new WrappedLinearLayoutManager(getActivity());
    mRecycler8.setLayoutManager(linearLayoutManager);
    mAdapter8 = new NoteRecyclerAdapter(getActivity(),this);
    mRecycler8.setItemAnimator(new SlideInDownAnimator());
    mRecycler8.setHasFixedSize(true);
    mAdapter8.setData(savedNote);
    myDbHelper = new MyDbHelper(getActivity());
    getActivity().getSupportLoaderManager().initLoader(0,null,this);
    getActivity().getSupportLoaderManager().initLoader(1,null,this);
    return rootView1;
}

@Override
public void containerOnClick(int t) {

}

@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    if(id==0){
        return new CursorLoader(getActivity(), NoteContract.NoteItemRow.CONTENT_URI,null,null,null,null);
    }else{
        return new CursorLoader(getActivity(), NoteContract.NoteItemRow.CONTENT_URI_NEWS,null,null,null,null);
    }

}

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    if(loader.getId() ==0){
        if(data.moveToFirst()){
            do{
                int title1 = data.getColumnIndex(NoteContract.NoteItemRow.NOTE);
                int date1 = data.getColumnIndex(NoteContract.NoteItemRow.DATE);
                String title2 = data.getString(title1);
                String date2 = data.getString(date1);
                Notesetter setter1 = new Notesetter(title2,date2);
                savedNote.add(setter1);
                mAdapter8.notifyDataSetChanged();
            }while(data.moveToNext());

        }
    }else{
      /*  if(data.moveToFirst()){
            do{
                int title2 = data.getColumnIndex(NoteContract.NoteItemRow.NEWS_TITLE);
                int image_url = data.getColumnIndex(NoteContract.NoteItemRow.NEWS_IMAGE);
                int source_url = data.getColumnIndex(NoteContract.NoteItemRow.NEWS_URL);
                int date3 = data.getColumnIndex(NoteContract.NoteItemRow.NEWS_DATE);
                String title3 = data.getString(title2);
                String image_url_3 = data.getString(image_url);
                String sources_url3 =data.getString(source_url);
                String date_saved3 = data.getString(date3);
                NewsNotesetter setter1 = new NewsNotesetter(title3,image_url_3,sources_url3,date_saved3);
                savedNote.add(setter1);
                mAdapter8.notifyDataSetChanged();
            }while(data.moveToNext());

        }*/
    }

}

@Override
public void onLoaderReset(Loader<Cursor> loader) {

}

}

是我的内容提供商编码:

public class TheNewProvider extends ContentProvider {       
 private MyDbHelper myDbHelper;
 private static final String LOG_TAG = TheNewProvider.class.getSimpleName();
 private static final int SIMPLE_NOTE =100;
 private static final int SIMPLE_NOTE_ID=101;
 private static final int NEWS_NOTE =102;
 private static final int NEWS_NOTE_ID =103;
 private static final UriMatcher sUriMAtcher = new    UriMatcher(UriMatcher.NO_MATCH);

static{
    sUriMAtcher.addURI(NoteContract.CONTENT_AUTHORITY, NoteContract.path_note,SIMPLE_NOTE);
    sUriMAtcher.addURI(NoteContract.CONTENT_AUTHORITY, NoteContract.path_note+"/#",SIMPLE_NOTE_ID);
    sUriMAtcher.addURI(NoteContract.CONTENT_AUTHORITY, NoteContract.path_news,NEWS_NOTE);
    sUriMAtcher.addURI(NoteContract.CONTENT_AUTHORITY, NoteContract.path_news+"/#",NEWS_NOTE_ID);

}

@Override
public boolean onCreate() {
    myDbHelper = new MyDbHelper(getContext());
    return true;
}

@Nullable
@Override
public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {
    SQLiteDatabase sqLiteDatabase = myDbHelper.getReadableDatabase();
    Cursor cursor;
    int match = sUriMAtcher.match(uri);
    switch (match){
        case SIMPLE_NOTE:
            cursor = sqLiteDatabase.query(NoteContract.NoteItemRow.TABLE_NAME,projection,selection,selectionArgs,null,null,sortOrder);
            break;
        case SIMPLE_NOTE_ID:
            selection = NoteContract.NoteItemRow._ID+"=?";
            selectionArgs = new String[]{String.valueOf(ContentUris.parseId(uri))};
            cursor = sqLiteDatabase.query(NoteContract.NoteItemRow.TABLE_NAME,projection,selection,selectionArgs,null,null,sortOrder);

            break;
        case NEWS_NOTE:
            cursor = sqLiteDatabase.query(NoteContract.NoteItemRow.TABLE_NAME,projection,selection,selectionArgs,null,null,sortOrder);
            break;
        case NEWS_NOTE_ID:
            selection = NoteContract.NoteItemRow._ID+"=?";
            selectionArgs = new String[]{String.valueOf(ContentUris.parseId(uri))};
            cursor = sqLiteDatabase.query(NoteContract.NoteItemRow.TABLE_NAME,projection,selection,selectionArgs,null,null,sortOrder);
            break;
        default:
            throw new IllegalArgumentException("Insertion is not supported" +uri);

    }
    cursor.setNotificationUri(getContext().getContentResolver(), NoteContract.NoteItemRow.CONTENT_URI);
    cursor.setNotificationUri(getContext().getContentResolver(), NoteContract.NoteItemRow.CONTENT_URI_NEWS);
    return cursor;
}

@Nullable
@Override
public String getType(@NonNull Uri uri) {
    return null;
}

@Nullable
@Override
public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
    final int match = sUriMAtcher.match(uri);
    switch (match){
        case SIMPLE_NOTE:
            return save(uri,values);

        case NEWS_NOTE:
            return saveNews(uri,values);
        default:
            throw new IllegalArgumentException("Insertion is not supported" +uri);
    }
}

@Override
public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
    return 0;
}

@Override
public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {
    final int match = sUriMAtcher.match(uri);
    switch (match){
        case SIMPLE_NOTE:
            return UpdateNote(uri,values,selection,selectionArgs);
        case SIMPLE_NOTE_ID:
            selection = NoteContract.NoteItemRow._ID+"=?";
            selectionArgs = new String[]{String.valueOf(ContentUris.parseId(uri))};
            return UpdateNote(uri,values,selection,selectionArgs);
        case NEWS_NOTE:
            return UpdateNews(uri,values,selection,selectionArgs);
        case NEWS_NOTE_ID:
            selection = NoteContract.NoteItemRow._ID+"=?";
            selectionArgs = new String[]{String.valueOf(ContentUris.parseId(uri))};
            return UpdateNews(uri,values,selection,selectionArgs);
        default:
            throw new IllegalArgumentException("Insertion is not supported" +uri);
    }
}

private Uri save(Uri url,ContentValues values){
    String name  = values.getAsString(NoteContract.NoteItemRow.TITLE);
    if(name == null){
        throw new IllegalArgumentException("no title");
    }
    String notes  = values.getAsString(NoteContract.NoteItemRow.NOTE);
    if(notes == null){
        throw new IllegalArgumentException("no note");
    }
    String date  = values.getAsString(NoteContract.NoteItemRow.DATE);
    if(date == null){
        throw new IllegalArgumentException("no date");
    }
    SQLiteDatabase db = myDbHelper.getWritableDatabase();
    long id = db.insert(NoteContract.NoteItemRow.TABLE_NAME,null,values);
    if(id==-1){
        Log.v("the note","saved");
    }
    getContext().getContentResolver().notifyChange(url,null);
    return ContentUris.withAppendedId(url,id);
}
private Uri saveNews(Uri url,ContentValues values){
    String name  = values.getAsString(NoteContract.NoteItemRow.NEWS_TITLE);
    if(name == null){
        throw new IllegalArgumentException("no title");
    }
    String notes  = values.getAsString(NoteContract.NoteItemRow.NEWS_URL);
    if(notes == null){
        throw new IllegalArgumentException("no note");
    }
    String date  = values.getAsString(NoteContract.NoteItemRow.NEWS_DATE);
    if(date == null){
        throw new IllegalArgumentException("no date");
    }
    String image_url  = values.getAsString(NoteContract.NoteItemRow.NEWS_IMAGE);
    if(image_url == null){
        throw new IllegalArgumentException("no image");
    }
    SQLiteDatabase db = myDbHelper.getWritableDatabase();
    long id = db.insert(NoteContract.NoteItemRow.TABLE_NAME,null,values);
    if(id==-1){
        Log.v("the note","saved");
    }
    getContext().getContentResolver().notifyChange(url,null);
    return ContentUris.withAppendedId(url,id);
}
private int UpdateNote(Uri url,ContentValues values,String selection,String[]selectionArgs){
    String name  = values.getAsString(NoteContract.NoteItemRow.TITLE);
    if(name == null){
        throw new IllegalArgumentException("no title");
    }
    String notes  = values.getAsString(NoteContract.NoteItemRow.NOTE);
    if(notes == null){
        throw new IllegalArgumentException("no note");
    }
    String date  = values.getAsString(NoteContract.NoteItemRow.DATE);
    if(date == null){
        throw new IllegalArgumentException("no date");
    }
    SQLiteDatabase db = myDbHelper.getWritableDatabase();
    int rowUpdated = db.update(NoteContract.NoteItemRow.TABLE_NAME,values,selection,selectionArgs);
    if(rowUpdated!=0){
        getContext().getContentResolver().notifyChange(url,null);
    }

    return rowUpdated;
}
private int UpdateNews(Uri url,ContentValues values,String selection,String[]selectionArgs){
    String name  = values.getAsString(NoteContract.NoteItemRow.NEWS_TITLE);
    if(name == null){
        throw new IllegalArgumentException("no title");
    }
    String notes  = values.getAsString(NoteContract.NoteItemRow.NEWS_URL);
    if(notes == null){
        throw new IllegalArgumentException("no note");
    }
    String date  = values.getAsString(NoteContract.NoteItemRow.NEWS_DATE);
    if(date == null){
        throw new IllegalArgumentException("no date");
    }
    String image_url  = values.getAsString(NoteContract.NoteItemRow.NEWS_IMAGE);
    if(image_url == null){
        throw new IllegalArgumentException("no image");
    }
    SQLiteDatabase db = myDbHelper.getWritableDatabase();
    int rowUpdated = db.update(NoteContract.NoteItemRow.TABLE_NAME,values,selection,selectionArgs);
    if(rowUpdated!=0){
        getContext().getContentResolver().notifyChange(url,null);
    }

    return rowUpdated;
}

}

这是我的databasehelper类:

public class MyDbHelper extends SQLiteOpenHelper {
private static final int DATABSE_VERSION = 1;
private static final String DATABASE_NAME ="simpleTable.db";

private static final String createDatabase = "CREATE TABLE "
        + NoteItemRow.TABLE_NAME
        +"("+NoteItemRow._ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "
        +NoteItemRow.TITLE+" TEXT, "
        +NoteItemRow.NOTE+" TEXT NOT NULL, "
        +NoteItemRow.DATE+" TEXT NOT NULL);";

private static final String createDatabase2 = "CREATE TABLE "
        + NoteItemRow.TABLE_NAME2
        +"("+NoteItemRow._ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "
        +NoteItemRow.NEWS_TITLE+" TEXT, "
        +NoteItemRow.NEWS_URL+" TEXT NOT NULL, "
        +NoteItemRow.NEWS_DATE+" TEXT NOT NULL, "
        +NoteItemRow.NEWS_IMAGE+" TEXT NOT NULL);";

private static final String UPGRADE_DB = "DROP TABLE IF EXISTS"+ NoteItemRow.TABLE_NAME;

private static final String UPGRADE_DB2 = "DROP TABLE IF EXISTS"+ NoteItemRow.TABLE_NAME2;

public MyDbHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABSE_VERSION);
}


@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(createDatabase);
    db.execSQL(createDatabase2);

}

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

    db.execSQL(UPGRADE_DB);
    db.execSQL(UPGRADE_DB2);
    onCreate(db);
}

} 这是我的编辑课:

public class EditActivity extends AppCompatActivity {
private EditText mTitle,mNote;
String title1;
String note_detail;
private MyDbHelper mDbHelper;
private Uri cureenturi;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.note_editor);
    mTitle = (EditText)findViewById(R.id.title_note);
    mNote = (EditText)findViewById(R.id.take_note);


}
private void savenote(){
     title1 = mTitle.getText().toString().trim();
     note_detail = mNote.getText().toString().trim();
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy");
    Date date = new Date();
    String date_cur = sdf.format(date);
    mDbHelper = new MyDbHelper(this);

    ContentValues values = new ContentValues();
    values.put(NoteContract.NoteItemRow.TITLE,title1);
    values.put(NoteContract.NoteItemRow.NOTE,note_detail);
    values.put(NoteContract.NoteItemRow.DATE,date_cur);
    cureenturi = getContentResolver().insert(NoteContract.NoteItemRow.CONTENT_URI,values);
    if(cureenturi == null){
        return;
    }else {
        int updateRow = getContentResolver().update(cureenturi,values,null,null);
        if(updateRow==0){

        }else {
            Toast.makeText(EditActivity.this,"note updated",Toast.LENGTH_SHORT).show();
        }

    }
    Uri newUriContent =  getContentResolver().insert(NoteContract.NoteItemRow.CONTENT_URI,values);
    if(newUriContent==null){
        Toast.makeText(EditActivity.this,"can't created the note",Toast.LENGTH_SHORT).show();
    }else{
        Toast.makeText(EditActivity.this,"note inserted",Toast.LENGTH_SHORT).show();
    }

}

@Override
public void onBackPressed() {
    super.onBackPressed();
    if(TextUtils.isEmpty(title1)&&TextUtils.isEmpty(note_detail)){
        finish();
    }else{
        savenote();
    }

}

当我启动应用程序时,错误日志显示此错误:

Process: com.example.user.inforting, PID: 5490
                                                                      java.lang.NullPointerException: Attempt to invoke interface method 'boolean android.database.Cursor.moveToFirst()' on a null object reference
                                                                          at com.example.user.inforting.Note_mainActivity.onLoadFinished(Note_mainActivity.java:72)
                                                                          at com.example.user.inforting.Note_mainActivity.onLoadFinished(Note_mainActivity.java:30)
                                                                          at android.support.v4.app.LoaderManagerImpl$LoaderInfo.callOnLoadFinished(LoaderManager.java:476)
                                                                          at android.support.v4.app.LoaderManagerImpl$LoaderInfo.onLoadComplete(LoaderManager.java:444)
                                                                          at android.support.v4.content.Loader.deliverResult(Loader.java:126)
                                                                          at android.support.v4.content.CursorLoader.deliverResult(CursorLoader.java:105)
                                                                          at android.support.v4.content.CursorLoader.deliverResult(CursorLoader.java:37)
                                                                          at android.support.v4.content.AsyncTaskLoader.dispatchOnLoadComplete(AsyncTaskLoader.java:252)
                                                                          at android.support.v4.content.AsyncTaskLoader$LoadTask.onPostExecute(AsyncTaskLoader.java:80)
                                                                          at android.support.v4.content.ModernAsyncTask.finish(ModernAsyncTask.java:485)
                                                                          at android.support.v4.content.ModernAsyncTask$InternalHandler.handleMessage(ModernAsyncTask.java:502)
                                                                          at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                          at android.os.Looper.loop(Looper.java:154)
                                                                          at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                          at java.lang.reflect.Method.invoke(Native Method)
                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
有人可以帮助纠正我。你的帮助很高兴。

1 个答案:

答案 0 :(得分:0)

正如我看到的程序错误日志所示:

对空对象引用

'boolean android.database.Cursor.moveToFirst()'

还有 MoveToFirst 方法,将光标移动到第一行。

因此,根据我的意见,您尚未启动SQLiteDataBase,或者您通过程序丢失了DataBase的引用对象。

希望它会有所帮助。