2015-09-30 58 views
0

所以我想用一個數據庫來填充一個片段內的列表視圖。到目前爲止,我正試圖將數據插入到空表中,但每當我運行插入方法時,應用程序都會崩潰。據我所知,錯誤是一個NullPointerException在創建數據庫時,由於上下文沒有被正確地返回而導致。但是,我沒有看到上下文有什麼問題。我將嘗試包括任何相關的類。Android,在數據庫構建中找不到上下文

合同類

public final class NotesContract { 

//Empty Constructor 
public NotesContract(){} 

/* Inner class that defines the table contents */ 
public static abstract class FeedEntry implements BaseColumns { 
    public static final String TABLE_NAME = "notes"; 
    public static final String COLUMN_NAME_TITLE = "title"; 
    public static final String COLUMN_NAME_BODY = "body"; 
    //add more columns for database here 
} 

} 

SQLiteOpenHelper

public class MySQLiteHelper extends SQLiteOpenHelper { 

private static final String TEXT_TYPE = " TEXT"; 
private static final String INT_TYPE = " INTEGER"; 
private static final String COMMA_SEP = ","; 
private static final String SQL_CREATE_ENTRIES = 
     "CREATE TABLE " + FeedEntry.TABLE_NAME + " (" + 
       FeedEntry._ID + " INTEGER PRIMARY KEY," + 
       FeedEntry.COLUMN_NAME_TITLE + TEXT_TYPE + COMMA_SEP + 
       FeedEntry.COLUMN_NAME_BODY + TEXT_TYPE + 
     ")"; 

private static final String SQL_DELETE_ENTRIES = 
     "DROP TABLE IF EXISTS " + FeedEntry.TABLE_NAME; 



// If you change the database schema, you must increment the database version. 
public static final int DATABASE_VERSION = 1; 
public static final String DATABASE_NAME = "FeedReader.db"; 

public MySQLiteHelper(Context context) { 
    super(context, DATABASE_NAME, null, DATABASE_VERSION); 
} 
public void onCreate(SQLiteDatabase db) { 
    db.execSQL(SQL_CREATE_ENTRIES); 
} 
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
    // This database is only a cache for online data, so its upgrade policy is 
    // to simply to discard the data and start over 
    db.execSQL(SQL_DELETE_ENTRIES); 
    onCreate(db); 
} 
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
    onUpgrade(db, oldVersion, newVersion); 
} 
} 

MainActivityFragment

public class MainActivityFragment extends Fragment { 

//Databse instatiation 
MySQLiteHelper mDbHelper = new MySQLiteHelper(getActivity()); 

//other stuff 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 
    //Primary View Inflator 
    final View rootView = inflater.inflate(R.layout.fragment_main, container, false); 

//other stuff 

final ImageButton button2 = (ImageButton) rootView.findViewById(R.id.addNoteButton); 

    button2.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 

     if((noteTitle.getText().toString().trim()).equals("")){ 
      Toast.makeText(getActivity().getBaseContext(), "No Title Specified", Toast.LENGTH_SHORT).show(); 
     }else { 
      String noteTitleString = noteTitle.getText().toString(); 
      String noteBodyString = noteBody.getText().toString(); 

      Toast.makeText(getActivity().getBaseContext(), "Added: " + noteTitleString, Toast.LENGTH_SHORT).show(); 

      //Clear text fields and hide keyboard 
      noteTitle.getText().clear(); 
      noteBody.getText().clear(); 
      final InputMethodManager imm = (InputMethodManager) 
        getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); 
      imm.hideSoftInputFromWindow(getView().getWindowToken(), 0); 

      addNotes(noteTitleString, noteBodyString); 
     } 
     } 
    }); 

} 

private void addNotes(String title, String body){ 

    // Gets the data repository in write mode 
    SQLiteDatabase db = mDbHelper.getWritableDatabase(); 

// Create a new map of values, where column names are the keys 
    ContentValues values = new ContentValues(); 
    values.put(FeedEntry.COLUMN_NAME_TITLE, title); 
    values.put(FeedEntry.COLUMN_NAME_BODY, body); 

// Insert the new row, returning the primary key value of the new row 
    long newRowId; 
    newRowId = db.insert(
      FeedEntry.TABLE_NAME, 
      null, 
      values); 

    db.close(); 
} 

錯誤堆

Process: com.example.ggould.scribble, PID: 21011 
    java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase android.content.Context.openOrCreateDatabase(java.lang.String, int, android.database.sqlite.SQLiteDatabase$CursorFactory, android.database.DatabaseErrorHandler)' on a null object reference 
      at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:223) 
      at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163) 
      at com.example.ggould.scribble.MainActivityFragment.addNotes(MainActivityFragment.java:228) 
      at com.example.ggould.scribble.MainActivityFragment.access$000(MainActivityFragment.java:26) 
      at com.example.ggould.scribble.MainActivityFragment$2.onClick(MainActivityFragment.java:136) 
      at android.view.View.performClick(View.java:4756) 
      at android.view.View$PerformClick.run(View.java:19749) 
      at android.os.Handler.handleCallback(Handler.java:739) 
      at android.os.Handler.dispatchMessage(Handler.java:95) 
      at android.os.Looper.loop(Looper.java:135) 
      at android.app.ActivityThread.main(ActivityThread.java:5221) 
      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:899) 
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694) 

回答

3

當您致電MySQLiteHelper mDbHelper = new MySQLiteHelper(getActivity());該片段尚未附加到Activity時,所以getActivity()返回null。嘗試在onCreateView方法中創建MySQLiteHelper對象。

+0

哇,那太超級簡單了。馬上工作。爲什麼它們在onCreateView之前沒有關聯的活動? –

+0

實際上只有在onCreateView之後,當調用onAttach()方法時,Fragment纔會附加到活動上。那麼,片段必須在被附加到活動之前創建,所以... –