在片段

时间:2016-09-05 21:00:24

标签: java android-fragments nullpointerexception android-sqlite android-sharedpreferences

我正在申请5 Fragment s。在Fragment s的活动中,我从SharedPreferences获取数据并更改活动标题。但是在Db.java文件中,我连接到数据库并执行查询,我无法从SharedPreferences获取数据并收到错误:

  

java.lang.NullPointerException:尝试调用接口方法' java.lang.String android.content.SharedPreferences.getString(java.lang.String,java.lang.String)'在null对象引用上                                                                                            at com.smartfon_apps.timetable_sch32.Db.getAllItemsFri(Db.java:77)                                                                                            at com.smartfon_apps.timetable_sch32.FridayFragment.onCreateView(FridayFragment.java:30)                                                                                            在android.support.v4.app.Fragment.performCreateView(Fragment.java:2074)                                                                                            在android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)                                                                                            在android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1286)                                                                                            在android.support.v4.app.BackStackRecord.run(BackStackRecord.java:758)                                                                                            在android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:1632)                                                                                            在android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:637)                                                                                            在android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:143)                                                                                            在android.support.v4.view.ViewPager.populate(ViewPager.java:1237)                                                                                            在android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:668)                                                                                            在android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:630)                                                                                            在android.support.v4.view.ViewPager.setCurrentItem(ViewPager.java:611)                                                                                            在android.support.design.widget.TabLayout $ ViewPagerOnTabSelectedListener.onTabSelected(TabLayout.java:2156)                                                                                            在android.support.design.widget.TabLayout.dispatchTabSelected(TabLayout.java:1138)                                                                                            在android.support.design.widget.TabLayout.selectTab(TabLayout.java:1132)                                                                                            在android.support.design.widget.TabLayout.selectTab(TabLayout.java:1105)                                                                                            在android.support.design.widget.TabLayout $ Tab.select(TabLayout.java:1396)                                                                                            在android.support.design.widget.TabLayout $ TabView.performClick(TabLayout.java:1501)                                                                                            在android.view.View $ PerformClick.run(View.java:19844)                                                                                            在android.os.Handler.handleCallback(Handler.java:739)                                                                                            在android.os.Handler.dispatchMessage(Handler.java:95)                                                                                            在android.os.Looper.loop(Looper.java:135)                                                                                            在android.app.ActivityThread.main(ActivityThread.java:5349)                                                                                            at java.lang.reflect.Method.invoke(Native Method)                                                                                            在java.lang.reflect.Method.invoke(Method.java:372)                                                                                            在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:908)                                                                                            在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)

这是我的Db.java文件:

package x.x.x;

import java.io.IOException;

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

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
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.preference.PreferenceManager;
import android.util.Log;

public class Db {

    public static final String _ID_column = "_id";
    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;
    private SharedPreferences sp;

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

    public Cursor getAllItemsFri() {
        mDb = mDbHelper.getReadableDatabase();
        sp = PreferenceManager.getDefaultSharedPreferences();
        String select_class = sp.getString("select_class", "");
        //String select_class = "1А";
        String where = "clas = '" + select_class + "' AND day = 'Пятница'";
        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);
            fContext = context;
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            // TODO Auto-generated method stub
            db.execSQL("CREATE TABLE " + TABLE_NAME + " ( "
                    + _ID_column + " INTEGER PRIMARY KEY AUTOINCREMENT, " + 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(1);
                        String number = _xml.getAttributeValue(2);
                        String nazv = _xml.getAttributeValue(3);
                        String day = _xml.getAttributeValue(4);
                        String time = _xml.getAttributeValue(5);
                        String room = _xml.getAttributeValue(6);
                        String teacher = _xml.getAttributeValue(7);

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

以下是我在Fragment s的活动,其中一切正常:

import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

import java.util.ArrayList;
import java.util.List;

import com.smartfon_apps.timetable_sch32.R;
import com.smartfon_apps.timetable_sch32.MondayFragment;
import com.smartfon_apps.timetable_sch32.TuesdayFragment;
import com.smartfon_apps.timetable_sch32.WednesdayFragment;
import com.smartfon_apps.timetable_sch32.ThursdayFragment;
import com.smartfon_apps.timetable_sch32.FridayFragment;

import static com.smartfon_apps.timetable_sch32.Db.*;

public class TimetableActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    SharedPreferences sp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_timetable);

        sp = PreferenceManager.getDefaultSharedPreferences(this);
        String select_class = sp.getString("select_class", "");

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        //getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        setTitle("Расписание " + select_class + " класса");

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new MondayFragment(), "ПН");
        adapter.addFragment(new TuesdayFragment(), "ВТ");
        adapter.addFragment(new WednesdayFragment(), "СР");
        adapter.addFragment(new ThursdayFragment(), "ЧТ");
        adapter.addFragment(new FridayFragment(), "ПТ");
        viewPager.setAdapter(adapter);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }
}

有关如何解决此问题的任何建议?

0 个答案:

没有答案