尝试在空对象引用上调用虚方法'android.content.res.Resources android.content.Context.getResources()'

时间:2016-09-04 20:47:11

标签: java android sqlite android-fragments nullpointerexception

我正在开发一个包含5个片段的应用。在所有片段中,我有从sqlite检索的数据的列表视图。我做到了这一点,但我遇到了错误:

09-04 23:13:22.226 20797-20797/? E/AndroidRuntime: FATAL EXCEPTION: main

                                                   java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
                                                       at com.smartfon_apps.timetable_sch32.Db$DbHelper.onCreate(Db.java:68)
                                                       at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:251)
                                                       at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:187)
                                                       at com.smartfon_apps.timetable_sch32.Db.getAllItems(Db.java:38)
                                                       at com.smartfon_apps.timetable_sch32.MondayFragment.onCreateView(MondayFragment.java:33)
                                                       at android.support.v4.app.Fragment.performCreateView(Fragment.java:2074)
                                                       at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
                                                       at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1286)
                                                       at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:758)
                                                       at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:1632)
                                                       at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:637)
                                                       at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:143)
                                                       at android.support.v4.view.ViewPager.populate(ViewPager.java:1237)
                                                       at android.support.v4.view.ViewPager.populate(ViewPager.java:1085)
                                                       at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1611)
                                                       at android.view.View.measure(View.java:17496)
                                                       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5466)
                                                       at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:671)
                                                       at android.support.design.widget.HeaderScrollingViewBehavior.onMeasureChild(HeaderScrollingViewBehavior.java:90)
                                                       at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onMeasureChild(AppBarLayout.java:1319)
                                                       at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:736)
                                                       at android.view.View.measure(View.java:17496)
                                                       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5466)
                                                       at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
                                                       at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
                                                       at android.view.View.measure(View.java:17496)
                                                       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5466)
                                                       at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1438)
                                                       at android.widget.LinearLayout.measureVertical(LinearLayout.java:724)
                                                       at android.widget.LinearLayout.onMeasure(LinearLayout.java:615)
                                                       at android.view.View.measure(View.java:17496)
                                                       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5466)
                                                       at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
                                                       at android.view.View.measure(View.java:17496)
                                                       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5466)
                                                       at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1438)
                                                       at android.widget.LinearLayout.measureVertical(LinearLayout.java:724)
                                                       at android.widget.LinearLayout.onMeasure(LinearLayout.java:615)
                                                       at android.view.View.measure(View.java:17496)
                                                       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5466)
                                                       at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
                                                       at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2636)
                                                       at android.view.View.measure(View.java:17496)
                                                       at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2031)
                                                       at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1193)
                                                       at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1400)
                                                       at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1078)
                                                       at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5875)
                                                       at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
                                                          at android.view.Choreographer.doCallbacks(Choreographer.java:580)
                                                       at android.view.Choreographer.doFrame(Choreographer.java:550)
                                                    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java

我的DB.java

package com.xxx.xxx;

import java.io.IOException;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.content.ContentValues;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.XmlResourceParser;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class Db {

public static final String CLASS_COLUMN = "clas";
public static final String NUMBER_COLUMN = "number";
public static final String NAZVANIE_COLUMN = "nazvanie";
public static final String DAY_COLUMN = "day";
public static final String TIME_COLUMN = "time";
public static final String ROOM_COLUMN = "room";
public static final String TEACHER_COLUMN = "teacher";
public static final String DATABASE_NAME = "lessons_database.db";
public static final String TABLE_NAME = "lessonstable";
private static final int DATABASE_VERSION = 1;

private DbHelper mDbHelper;
private SQLiteDatabase mDb;

public Db(Context context) {
    mDbHelper = new DbHelper(context);
}

public Cursor getAllItems() {
    mDb = mDbHelper.getReadableDatabase();
    String where = "clas = " + "'1А'";
    return mDb.query(TABLE_NAME, null, where, null, null, null, null);
}

public void close() {
    if (mDbHelper != null) mDbHelper.close();
    if (mDb != null) mDb.close();
}

public class DbHelper extends SQLiteOpenHelper {

    public Context fContext;

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

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        db.execSQL("CREATE TABLE " + TABLE_NAME + " ("
                + CLASS_COLUMN + " TEXT, " + NUMBER_COLUMN + " TEXT,"
                + NAZVANIE_COLUMN + " TEXT, " + DAY_COLUMN + " TEXT,"
                + TIME_COLUMN + " TEXT, " + ROOM_COLUMN + " TEXT,"
                + TEACHER_COLUMN + " TEXT" + ");");

        // Добавляем записи в таблицу
        ContentValues values = new ContentValues();

        // Получим файл из ресурсов
        Resources res = fContext.getResources();

        // Открываем xml-файл
        XmlResourceParser _xml = res.getXml(R.xml.lessons_records);
        try {
            // Ищем конец документа
            int eventType = _xml.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) {
                // Ищем теги record
                if ((eventType == XmlPullParser.START_TAG)
                        && (_xml.getName().equals("record"))) {
                    // Тег Record найден, теперь получим его атрибуты и
                    // вставляем в таблицу
                    String clas = _xml.getAttributeValue(0);
                    String number = _xml.getAttributeValue(1);
                    String nazv = _xml.getAttributeValue(2);
                    String day = _xml.getAttributeValue(3);
                    String time = _xml.getAttributeValue(4);
                    String room = _xml.getAttributeValue(5);
                    String teacher = _xml.getAttributeValue(6);

                    values.put("clas", clas);
                    values.put("number", number);
                    values.put("nazvanie", nazv);
                    values.put("day", day);
                    values.put("time", time);
                    values.put("room", room);
                    values.put("teacher", teacher);
                    db.insert(TABLE_NAME, null, values);
                }
                eventType =
                        _xml.next();
            }
        }
        // Catch errors
        catch (XmlPullParserException | IOException e) {
            Log.e("Test", e.getMessage(), e);
        } finally {
            // Close the xml file
            _xml.close();
        }

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        //Log.w("TestBase", "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);
    }
}

}

1 个答案:

答案 0 :(得分:2)

DBHelper类中,变量fContext永远不会被初始化。您应该在DBHelper构造函数中设置其值:

public DbHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    fContext = context;
}