当我尝试运行我的应用程序时,我收到一个错误(java.lang.NullPointerException)

时间:2017-09-30 01:20:16

标签: java android android-fragments android-asynctask nullpointerexception

我正在学习如何为Android编写和开发应用程序,而我正在尝试使用新闻应用程序。 但是当我尝试运行应用程序时,我得到了这个错误:java.lang.NullPointerException:尝试在null上调用虚方法'java.lang.Object android.content.Context.getSystemService(java.lang.String)'对象参考。

应用程序一开始工作正常,只有一个活动。但后来我试图用浏览器对它进行打包,我修复了一堆错误,但是这个我无法找出发生了什么。我读了一些关于如何修复NullPointerException的内容,但我仍然无法修复它。

以下是代码:

请不要忘记葡萄牙语中的评论和文件,我只是错了 任何方式,无组织。 (我计划在完成代码后关注它)。

 package com.example.android.news;

import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.content.Context;
import android.content.Intent;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.support.annotation.Nullable;
import android.os.Bundle;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

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

public class NewsFragment extends Fragment implements android.support.v4.app.LoaderManager.LoaderCallbacks<List<News>> {

    public NewsFragment(){
        // Required empty public constructor
    }

    //Contexto do app
    private Context mContext = getContext();

    public static final String LOG_TAG = NewsFragment.class.getName();

    /** Adapter da lista de news */
    private NewsAdapters mAdapter;

    /** URL para o dado da notícia (news) do dataset do The Gardian */
    private static final String THE_GARDIAN_DATASET =
            "https://content.guardianapis.com/search?api-key=4a8dba55-ace9-40bf-8a3c-05a1d2eebd65";

    /**
     * Valor constante para o ID do loader de news. Podemos escolher qualquer inteiro.
     * Isto só importa realmente se você estiver usando múltiplos loaders.
     */
    private static final int NEWS_LOADER_ID = 1;

    /** TextView que é mostrada quando a lista é vazia */
    private TextView mEmptyStateTextView;

    /** ProgressBar que é mostrada enquanto o app busca dados do servidor */
    private ProgressBar mLoadingSpinner;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_news , container, false);

        final ArrayList<News> newses = new ArrayList<News>();

        // Acha uma referência para a {@link ListView} no layout
        ListView newsListView = (ListView) rootView.findViewById(R.id.list);

        if (getTag() != null){
            // Cria um novo adapter que pega uma lista vazia de news como entrada
            mAdapter = new NewsAdapters(mContext, newses);

            // Seta o adapter na {@link ListView}
            // para que a lista pode ser populada na interface do usuário
            newsListView.setAdapter(mAdapter);
        }

        //Acha uma referencia para a {@link TextView}
        mEmptyStateTextView = (TextView) rootView.findViewById(R.id.empty_state_text_view);

        //Acha uma referencia para a {@link ProgressBar}
        mLoadingSpinner = (ProgressBar) rootView.findViewById(R.id.loading_spinner);

        //Seta um emptyState {@ link emptyView} na ListView {@ link earthquakeListView}
        newsListView.setEmptyView(mEmptyStateTextView);

        newsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                // Acha a news atual que foi clicado
                News currentNews = mAdapter.getItem(position);

                //Converte a URL da String em um objeto URI (para passar no construtor da Intent)
                Uri newsUri = Uri.parse(currentNews.getmWebUrl());

                // Cria um novo intent para visualizar o URI
                Intent webIntent = new Intent(Intent.ACTION_VIEW, newsUri);

                // Envia a intent para lançar uma nova activity
                startActivity(webIntent);
            }
        });

        //Cria um objeto da classe para monitorar a conexão com a internet
        ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);

        //Verifica o estado da conexão
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();

        if (isConnected){
            // Obtém uma referência ao LoaderManager, a fim de interagir com loaders.
            LoaderManager loaderManager = getLoaderManager();

            // Inicializa o loader. Passa um ID constante int definido acima e passa nulo para
            // o bundle. Passa esta activity para o parâmetro LoaderCallbacks (que é válido
            // porque esta activity implementa a interface LoaderCallbacks.
            loaderManager.initLoader(NEWS_LOADER_ID, null, this);
        } else {
            mLoadingSpinner.setVisibility(View.GONE);
            mEmptyStateTextView.setText(R.string.no_internet);
        }

        return rootView;
    }

    @Override
    public Loader<List<News>> onCreateLoader(int id, Bundle args) {

        Uri baseUri = Uri.parse(THE_GARDIAN_DATASET);
        Uri.Builder uriBuilder = baseUri.buildUpon();

        // Criar um novo loader para a dada URL
        return new NewsLoader(getContext(), uriBuilder.toString());
    }

    @Override
    public void onLoadFinished(Loader<List<News>> loader, List<News> news) {
        //Hide the LoadingSpinner when the loading is finished
        mLoadingSpinner.setVisibility(View.GONE);

        //Seta o texto a ser mostrado caso não haja news a serem mostrados
        mEmptyStateTextView.setText(R.string.empty_state);

        // Limpa o adapter de dados de news anteriores
        mAdapter.clear();

        // Se há uma lista válida de {@link News}s, então os adiciona ao data set do adapter.
        // Isto ativará a atualização da ListView.
        if (news != null && !news.isEmpty()) {
            mAdapter.addAll(news);
        }
    }

    @Override
    public void onLoaderReset(Loader<List<News>> loader) {
        // Reseta o Loader, então podemos limpar nossos dados existentes.
        mAdapter.clear();
    }
}

和logcat:

    09-29 16:17:44.553 26644-26644/com.example.android.news E/AndroidRuntime: FATAL EXCEPTION: main
                                                                          Process: com.example.android.news, PID: 26644
                                                                          java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference
                                                                              at android.view.LayoutInflater.from(LayoutInflater.java:233)
                                                                              at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:181)
                                                                              at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:166)
                                                                              at com.example.android.news.NewsAdapters.<init>(NewsAdapters.java:0)
                                                                              at com.example.android.news.NewsFragment.onCreateView(NewsFragment.java:69)
                                                                              at android.support.v4.app.Fragment.performCreateView(Fragment.java:2192)
                                                                              at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1299)
                                                                              at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
                                                                              at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
                                                                              at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:758)
                                                                              at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2363)
                                                                              at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2149)
                                                                              at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2103)
                                                                              at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:1984)
                                                                              at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:626)
                                                                              at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:143)
                                                                              at android.support.v4.view.ViewPager.populate(ViewPager.java:1268)
                                                                              at android.support.v4.view.ViewPager.populate(ViewPager.java:1116)
                                                                              at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1642)
                                                                              at android.view.View.measure(View.java:21051)
                                                                              at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6459)
                                                                              at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
                                                                              at android.widget.LinearLayout.measureVertical(LinearLayout.java:758)
                                                                              at android.widget.LinearLayout.onMeasure(LinearLayout.java:640)
                                                                              at android.view.View.measure(View.java:21051)
                                                                              at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6459)
                                                                              at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                                              at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
                                                                              at android.view.View.measure(View.java:21051)
                                                                              at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6459)
                                                                              at android.support.v7.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:393)
                                                                              at android.view.View.measure(View.java:21051)
                                                                              at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6459)
                                                                              at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                                              at android.view.View.measure(View.java:21051)
                                                                              at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6459)
                                                                              at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
                                                                              at android.widget.LinearLayout.measureVertical(LinearLayout.java:758)
                                                                              at android.widget.LinearLayout.onMeasure(LinearLayout.java:640)
                                                                              at android.view.View.measure(View.java:21051)
                                                                              at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6459)
                                                                              at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                                              at com.android.internal.policy.DecorView.onMeasure(DecorView.java:849)
                                                                              at android.view.View.measure(View.java:21051)
                                                                              at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2583)
                                                                              at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1642)
                                                                              at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1893)
                                                                              at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1522)
                                                                              at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7098)
                                                                              at android.view.Choreographer$CallbackRecord.run(Choreographer.java:927)
                                                                              at android.view.Choreographer.doCallbacks(Choreographer.java:702)
                                                                              at android.view.Choreographer.doFrame(Choreographer.java:638)
09-29 16:17:44.553 26644-26644/com.example.android.news E/AndroidRuntime:     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:913)
                                                                              at android.os.Handler.handleCallback(Handler.java:751)
                                                                              at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                              at android.os.Looper.loop(Looper.java:154)
                                                                              at android.app.ActivityThread.main(ActivityThread.java:6682)
                                                                              at java.lang.reflect.Method.invoke(Native Method)
                                                                              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)

我无法弄清楚出了什么问题。 如果有人可以帮助我,我会感到沮丧!

3 个答案:

答案 0 :(得分:1)

改变这个:

class SuperType {

}

class SubType: SuperType {

}

class GenericType<TypeParameter> {
    func someGenericFunction() {
        print(TypeParameter.self)
    }
}

let instance = GenericType<SuperType>()
let subInstance = GenericType<SubType>()

instance.someGenericFunction() // prints "SuperType"
subInstance.someGenericFunction() // prints "SubType"

let array: [GenericType<SuperType>] = [instance, subInstance] // throws error: cannot convert value of type 'SomeGenericClass<SubType>' to expected element type 'SomeGenericClass<SuperType>'

为:

//Cria um objeto da classe para monitorar a conexão com a internet
    ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);

答案 1 :(得分:1)

onCreateView()方法中将其置于顶部:

this.mContext = getActivity();

你的问题将得到解决。片段没有依赖于它们所处活动的上下文。

答案 2 :(得分:-1)

在Fragment附加到Activity之前,上下文为null。

您需要此功能

//Contexto do app
private Context mContext;

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    this.mContext = context;
}