尝试调用虚方法' java.io.FileOutputStream android.content.Context.openFileOutput(java.lang.String,int)'在null对象引用上

时间:2016-01-30 22:35:20

标签: java android fileoutputstream

由于某些原因在我的应用程序中,当我尝试调用openFileOutput()时,它会抛出NullPointerException,我不确定是什么导致它。我确保该方法的所有参数都不为null,但由于某种原因,我的应用程序仍然会抛出NullPointerException。有什么建议吗?

Here I am checking to see if any of the parameters of the method are null

我的MainActivity类

    public class MainActivity extends AppCompatActivity {

    private static final String TAG_NEWS_FRAGMENT = "news_fragment";
    private static final String TAG_SPORTS_FRAGMENT = "sports_fragment";

    Context context = MainActivity.this;
    private final String[] CATEGORY_NAMES = {"news", "sports"};
    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private ProgressBar mProgressBar;
    private CoordinatorLayout coordinatorLayout;
    private PUNewsFragment mPUNewsFragement;
    private PUSportsFragment mPUSportsFragement;
    private List<NewspaperMetaObject> newsItems;
    private List<List<NewspaperMetaObject>> categories;
    private boolean doesFileExist;
    private boolean isWebsiteOnline;
    private FragmentManager fm;
    private ProgressBar pb;
    private boolean doRefresh;


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

        doRefresh = false;

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        tabLayout = (TabLayout) findViewById(R.id.tabs);
        Toast.makeText(this, "Loading...", Toast.LENGTH_SHORT).show();
        pb = (ProgressBar) findViewById(R.id.progressBar);

        try {
            isWebsiteOnline = new checkWebsiteStatus().execute().get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        doesFileExist = new File(context.getFilesDir() + "/news").exists();

        new RetrieveNewspaperMeta().execute(CATEGORY_NAMES);
    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new PUNewsFragment(), "News");
        adapter.addFragment(new PUSportsFragment(), "Sports");

        viewPager.setAdapter(adapter);
    }

    public void refresh(String[] str) {
        doRefresh = true;
        new RetrieveNewspaperMeta().execute(str);
    }


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

    private class RetrieveNewspaperMeta extends AsyncTask<String, Integer, Wrapper> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Wrapper doInBackground(String... params) {

            Document doc = null;


            categories = new ArrayList<>();

            if (!doesFileExist && doRefresh) {
                for (int i = 0; i < params.length; i++) {
                    newsItems = new ArrayList<>();
                    try {
                        Log.i("DEBUG", params[i]);
                        URL url = new URL("http://www.dailyprincetonian.com/category/" + params[i] + "/");
                        doc = Jsoup.connect(url.toString()).get();
                        Elements content = doc.select("article.tease-post");
                        System.out.println();
                        System.out.println(content);
                        int count = 0;
                        NewspaperMetaObject parser;
                        while (!content.eq(count).isEmpty()) {
                            parser = new NewspaperMetaObject(content.eq(count));
                            newsItems.add(parser);
                            count++;
                        }
                        categories.add(newsItems);
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    for (NewspaperMetaObject o : newsItems) {
                        try {
                            Elements text = Jsoup.connect(o.getDoc().select("h3.h2 a").attr("href")).get().select("section.article-content").select("div.article-bd").select("p");
                            o.setArticleText(text.toString());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }

                return new Wrapper(categories, params);
            } else {
                for (int i = 0; i < params.length; i++) {
                    newsItems = new ArrayList<>();
                    try {
                        FileInputStream fis = openFileInput(params[i]);
                        ObjectInputStream is = new ObjectInputStream(fis);
                        newsItems = (List<NewspaperMetaObject>) is.readObject();
                        is.close();
                        fis.close();
                        categories.add(newsItems);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (StreamCorruptedException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                return new Wrapper(categories, params);
            }
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
        }

        @Override
        protected void onPostExecute(final Wrapper wrapper) {
            super.onPostExecute(wrapper);
            android.os.Handler mHandler = new android.os.Handler();
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (!doRefresh) {
                        PUNewsFragment.newsItems = categories.get(0);
                        PUSportsFragment.newsItems = categories.get(1);

                        setupViewPager(viewPager);

                        tabLayout.setupWithViewPager(viewPager);

                        fm = getSupportFragmentManager();
                        mPUNewsFragement = (PUNewsFragment) fm.findFragmentByTag(TAG_NEWS_FRAGMENT);
                        mPUSportsFragement = (PUSportsFragment) fm.findFragmentByTag(TAG_SPORTS_FRAGMENT);


                        if (mPUNewsFragement == null && mPUSportsFragement == null) {
                            mPUNewsFragement = new PUNewsFragment();

                            mPUSportsFragement = new PUSportsFragment();

                            fm.beginTransaction().add(mPUNewsFragement, TAG_NEWS_FRAGMENT).commit();
                            fm.beginTransaction().add(mPUSportsFragement, TAG_SPORTS_FRAGMENT).commit();
                        }
                    } else {
                        for (int i = 0; i < wrapper.params.length; i++) {
                            switch (wrapper.params[i]) {
                                case "news":
                                    PUNewsFragment.newsItems = categories.get(0);
                                    PUNewsFragment.adapter.notifyDataSetChanged();
                                    break;
                                case "sports":
                                    PUSportsFragment.newsItems = categories.get(1);
                                    PUSportsFragment.adapter.notifyDataSetChanged();
                                    break;
                            }
                        }
                    }

                    if (pb != null) {
                        pb.setVisibility(View.GONE);
                    }
                    Log.i("DEBUG", "DONE!");

                    if (doRefresh) {
                        context = MainActivity.this;
                        for (int i = 0; i < wrapper.params.length; i++) {
                            try {
                                FileOutputStream fos = context.openFileOutput(wrapper.params[i], 0);
                                ObjectOutputStream os = new ObjectOutputStream(fos);
                                os.writeObject(newsItems);
                                os.close();
                                fos.close();
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    doRefresh = false;
                }
            }, 1000);


        }
    }


    private class checkWebsiteStatus extends AsyncTask<Void, Void, Boolean> {

        @Override
        protected Boolean doInBackground(Void... params) {
            try {
                URL url = new URL("http://www.dailyprincetonian.com/");
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.connect();
                urlConnection.disconnect();
                return true;
            } catch (IOException e) {
            }
            return false;
        }
    }

    private class Wrapper {
        List<List<NewspaperMetaObject>> categories;
        String[] params;

        public Wrapper(List<List<NewspaperMetaObject>> categories, String[] params){
            this.categories = categories;
            this.params = params;
        }
    }
}

抛出异常的片段

            if (doRefresh) {
                context = MainActivity.this;
                for (int i = 0; i < wrapper.params.length; i++) {
                    try {
                        FileOutputStream fos = context.openFileOutput(wrapper.params[i], 0);
                        ObjectOutputStream os = new ObjectOutputStream(fos);
                        os.writeObject(newsItems);
                        //os.flush();
                        os.close();
                        fos.close();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

1 个答案:

答案 0 :(得分:0)

看起来wrapper变量已声明(因此您可以执行

for (int i = 0; i < wrapper.params.length; i++)

没有任何问题)但是数组中的所有项都可以为空引用,这是NPE的原因。