从Fragment扩展活动获取上下文

时间:2015-02-25 19:58:48

标签: android database sqlite android-fragments android-context

我有一个" app"它有一个带有三个标签的标签布局:
在第一个尝试从SQLite数据库中检索某些行并在ListView中显示它们时。

处理标签布局的类称为PageFragment

public class PageFragment extends Fragment {
    public static final String ARG_PAGE = "ARG_PAGE";

    private int mPage;
    public MainActivity Main;

    public static PageFragment newInstance(int page) {
        Bundle args = new Bundle();
        args.putInt(ARG_PAGE, page);
        PageFragment fragment = new PageFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPage = getArguments().getInt(ARG_PAGE);
    }

    ListView ItemsLst;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = null;
        switch(mPage)
        {
            case 1:
                view = inflater.inflate(R.layout.layout_schedule, container, false);

                DatabaseHandler db = new DatabaseHandler(getActivity().getApplicationContext());

                Medicine med = new Medicine("Cardioaspirina", "Pillola", 1, "2015-02-25", "12:00:00");

                db.AddMedicine(med);

                ScheduleList(view, db.GetAllMedicines());

                return view;
            case 2:
                view = inflater.inflate(R.layout.layout_settings, container, false);
                return view;
            case 3:
                view = inflater.inflate(R.layout.layout_info, container, false);
                return view;
        }
        return view;
    }

    public void ScheduleList(View v, List<Medicine> medicines) {
        ItemsLst = (ListView) v.findViewById(R.id.listview);
        ArrayAdapter<Medicine> adapter = new ArrayAdapter<Medicine>(getActivity(), android.R.layout.simple_list_item_1, medicines);
        ItemsLst.setAdapter(adapter);
    }
}

如您所见,在onCreateView()方法中,我管理了标签布局。 为了从数据库中检索数据,我创建了一个名为DatabaseHandler的类,其中包含AddRecordGetRecordGetAllRecords等方法。 问题是DatabaseHandler构造函数需要Context变量,我尝试使用以下内容为其提供上下文:

DatabaseHandler db = new DatabaseHandler(getActivity().getApplicationContext());

我也尝试只使用getActivity(),但它会抛出NullPointerException。

如果有用,这里是DatabaseHandler构造函数:

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

所以任何人都知道如何从PageFragment类获取应用程序上下文?提前谢谢!

P.S。这是堆栈跟踪:

02-25 21:04:52.588    1947-1947/com.mms.dailypill I/art﹕ Not late-enabling -Xcheck:jni (already on)
02-25 21:04:53.092    1947-1959/com.mms.dailypill I/art﹕ Background sticky concurrent mark sweep GC freed 2943(255KB) AllocSpace objects, 0(0B) LOS objects, 29% free, 796KB/1135KB, paused 30.424ms total 49.618ms
02-25 21:04:53.093    1947-1972/com.mms.dailypill D/OpenGLRenderer﹕ Render dirty regions requested: true
02-25 21:04:53.094    1947-1947/com.mms.dailypill D/﹕ HostConnection::get() New Host Connection established 0xa6840570, tid 1947
02-25 21:04:53.106    1947-1947/com.mms.dailypill D/Atlas﹕ Validating map...
02-25 21:04:53.125    1947-1947/com.mms.dailypill E/SQLiteLog﹕ (1) near "TABLEDailyPill": syntax error
02-25 21:04:53.125    1947-1947/com.mms.dailypill D/AndroidRuntime﹕ Shutting down VM
02-25 21:04:53.183    1947-1947/com.mms.dailypill E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.mms.dailypill, PID: 1947
    android.database.sqlite.SQLiteException: near "TABLEDailyPill": syntax error (code 1): , while compiling: CREATE TABLEDailyPill(id INTEGER AUTOINCREMENT, name VARCHAR(50), format VARCHAR(15), amount INTEGER, exp_dateDATE, time HOUR, PRIMARY KEY(id));
            at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
            at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
            at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
            at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
            at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
            at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
            at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1674)
            at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1605)
            at com.mms.dailypill.DatabaseHandler.onCreate(DatabaseHandler.java:63)
            at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:251)
            at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
            at com.mms.dailypill.DatabaseHandler.AddMedicine(DatabaseHandler.java:84)
            at com.mms.dailypill.PageFragment.onCreateView(PageFragment.java:48)
            at android.support.v4.app.Fragment.performCreateView(Fragment.java:1786)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:947)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1126)
            at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:739)
            at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1489)
            at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:486)
            at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
            at android.support.v4.view.ViewPager.populate(ViewPager.java:1073)
            at android.support.v4.view.ViewPager.populate(ViewPager.java:919)
            at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1441)
            at android.view.View.measure(View.java:17430)
            at android.widget.LinearLayout.measureVertical(LinearLayout.java:875)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
            at android.view.View.measure(View.java:17430)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
            at android.view.View.measure(View.java:17430)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
            at android.support.v7.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:453)
            at android.view.View.measure(View.java:17430)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
            at android.view.View.measure(View.java:17430)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
            at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
            at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
            at android.view.View.measure(View.java:17430)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
            at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2560)
            at android.view.View.measure(View.java:17430)
            at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2001)
            at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1166)
            at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1372)
            at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1054)
            at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5779)
            at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
            at android.view.Choreographer.doCallbacks(Chor
02-25 21:04:55.795    1947-1947/com.mms.dailypill I/Process﹕ Sending signal. PID: 1947 SIG: 9

2 个答案:

答案 0 :(得分:1)

首先不要使用 getApplicationContext(),因为这个帖子中的原因解释了:

When to call activity context OR application context?

关于如何获取片段中的上下文的问题,请创建一个全局变量:

private Context context;

//onCreate method 
context = this;

在创建视图方法时使用此上下文。

最后一点是,我不认为您的问题与上下文有关,但是您的数据库创建是因为日志清除状态附近存在问题&#34; TABLEDailyPill&#34;:我认为您的查询需要修复。

答案 1 :(得分:0)

android.database.sqlite.SQLiteException: near "TABLEDailyPill": syntax error (code 1): , while compiling: CREATE TABLEDailyPill(id INTEGER AUTOINCREMENT, name VARCHAR(50), format VARCHAR(15), amount INTEGER, exp_dateDATE, time HOUR, PRIMARY KEY(id));

您在TABLEDailyPill之间缺少空格,假设DailyPill应该是表名。