2017-03-18 12 views
0

數據庫不工作是我的筆記應用程序編碼的主頁:我創造與Android的內容提供商的數據庫,但在所有

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); 
} 

} 這是我editnote類:

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) 

有人能幫助糾正我。你的幫助是欣賞。

回答

0

正如我看到程序錯誤日誌它說:

'布爾android.database.Cursor.moveToFirst()' 上的空對象引用

並且還MoveToFirst方法,將光標移動到第一行。

因此,根據我的觀點,您尚未啓動您的SQLiteDataBase,或者您通過程序丟失了DataBase的引用對象。

希望這會有所幫助。

+0

感謝您的回覆,這對我很有幫助。但現在又出現了另一個問題,那就是片段不能用我的recyclerviewAdapter來擴充我的recyclerview,並且錯誤只顯示任何內容,屏幕只顯示空白屏幕,您能否幫助檢查回收站視圖編碼,並糾正我,也非常感謝。 –

0

我在你Note_mainActivity看,你定義onCreateView了傳統。我建議你使用下面的代碼:希望這將是有益的

public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 
     LayoutInflater factory = LayoutInflater.from(getActivity()); 
     final View myView = factory.inflate(R.layout.YOUR_FRAGMENT_LAYOUT, null); 

     **//IF YOU NEED ACCESS TO THE CONTROL VIEWS IN YOUR XML LAYOUT USE myView** 
     return myView; 
} 

也Android.Developer代碼示例:

public class MyActivity extends Activity { 
    private RecyclerView mRecyclerView; 
    private RecyclerView.Adapter mAdapter; 
    private RecyclerView.LayoutManager mLayoutManager; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.my_activity); 
     mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view); 

     // use this setting to improve performance if you know that changes 
     // in content do not change the layout size of the RecyclerView 
     mRecyclerView.setHasFixedSize(true); 

     // use a linear layout manager 
     mLayoutManager = new LinearLayoutManager(this); 
     mRecyclerView.setLayoutManager(mLayoutManager); 

     // specify an adapter (see also next example) 
     mAdapter = new MyAdapter(myDataset); 
     mRecyclerView.setAdapter(mAdapter); 
    } 
    ... 
} 
+0

非常感謝,但問題仍然存在。我也無法解決問題的出在哪,順便說一句,謝謝。 –