提问者:小点点

如何在 Android Studio 中修复空对象引用上的“Context.getResources()”


当我在<code>TabLayout</code>片段中“快速”时,“atempt to invoke virtual method”<code>Android.content.res.Resources Android.contet.Context。getResources()处理Null对象引用错误。

我的代码 :

public class MangaMenuPage extends Fragment implements Response.ErrorListener, ConnectionReceiver.ConnectivityReceiverListener, View.OnClickListener {

public String getTitle(){
    return "MENÜ";
}


View v;
LinearLayout lnrlayout;

String URL_getCategory, URL_getProductToCategory, URL_getFiveteenChapters;

ProgressBar progressBar;
List<String> lstheaders;
RecMangaListAdapter recMangaListAdapter;
List<Products> lstProduct;
Category category;
Products products;
int categorySize;

View screen_connectionError;
Chapters chapters;
FrameLayout frm;
MySingleton mySingleton;
RequestQueue requestQeueu;


StringRequest getCategory, getFiveTeenChapter, getProductToCategory;
HashMap<Integer, String> lstCategory = new HashMap<>();
int top = 15;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    v = inflater.inflate(R.layout.fragment_manga_menu_page, container, false);
    initStep1(v);
    return v;
}


void receiverSettings() {

    BroadcastReceiver conn = new ConnectionReceiver();
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(CONNECTIVITY_ACTION);
    getContext().registerReceiver(conn, intentFilter);

}

private void initStep1(View v) {
    progressBar = v.findViewById(R.id.fragment_menuPage_progressBar);
    screen_connectionError = v.findViewById(R.id.lnr);

    FloatingActionButton fab = v.findViewById(R.id.fab_checkInternet);
    fab.setOnClickListener(this);
    ConnectionReceiver.connectionInfo = this;

    lnrlayout = v.findViewById(R.id.lnrlyt_manga_menu_page);
    lnrlayout.setOrientation(LinearLayout.VERTICAL);

    lstProduct = new ArrayList<>();
    lstheaders = new ArrayList<>();

    requestQeueu = Volley.newRequestQueue(getContext());
    receiverSettings();
}


void requestAdd(StringRequest request, String _tag) {
    request.setTag(_tag);
    requestQeueu.add(request);
}



void ApiPull() {
    lstProduct.clear();
    lnrlayout.removeAllViews();
    lstheaders.add(getString(R.string.oneSegmentName));

    URL_getFiveteenChapters = getString(R.string.URL_getChapters);
    getFiveTeenChapter = new StringRequest(Request.Method.GET, URL_getFiveteenChapters, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            GsonBuilder gsonBuilder = new GsonBuilder();
            Gson gson = gsonBuilder.create();
            chapters = gson.fromJson(response, Chapters.class);

            List<Chapters> lstChapters = new ArrayList<>();
            lstChapters.add(chapters);

            useApi(lstChapters, lstheaders.get(0));
            categoryApiPull();

        }
    }, this);
    requestAdd(getFiveTeenChapter, "getFiveTeenChapter");
}

void categoryApiPull() {
    URL_getCategory = getString(R.string.URL_getCategory);
    getCategory = new StringRequest(Request.Method.GET, URL_getCategory, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {

            GsonBuilder gsonBuilder = new GsonBuilder();
            Gson gson = gsonBuilder.create();

            category = gson.fromJson(response, Category.class);
            categorySize = category.getGetCategoryListResult().size();

            int id;
            for (int i = 0; categorySize > i; i++) {
                id = category.getGetCategoryListResult().get(i).getCategoryID();

                lstheaders.add(category.getGetCategoryListResult().get(i).getCategoryName());

                lstCategory.put(category.getGetCategoryListResult().get(i).getCategoryID(),
                        category.getGetCategoryListResult().get(i).getCategoryName());

                URL_getProductToCategory = getString(R.string.URL_getProductToCategory) + id;

                getProductToCategory = new StringRequest(Request.Method.GET, URL_getProductToCategory, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        GsonBuilder gsonBuilder = new GsonBuilder();
                        Gson gson = gsonBuilder.create();
                        products = gson.fromJson(response, Products.class);

                        if (products.getGetProductListResult().size() != 0) {
                            useApiOther(lstCategory.get(products.getGetProductListResult().get(0).getCategoryID()), products);
                        }

                        new CountDownTimer(1000, 1000) {
                            @Override
                            public void onTick(long l) {

                            }

                            @Override
                            public void onFinish() {
                                progressState(View.INVISIBLE);

                                if (lnrlayout.getVisibility() == View.INVISIBLE) {
                                    lnrlayout.setVisibility(View.VISIBLE);
                                }
                            }
                        }.start();

                    }
                }, MangaMenuPage.this);

                requestAdd(getProductToCategory, "getProductToCategory");
            }

        }
    }, MangaMenuPage.this);


    requestAdd(getCategory, "getCategory");

}

void progressState(int state) {
    progressBar.setVisibility(state);
}

@Override
public void onErrorResponse(VolleyError error) {
    progressState(View.INVISIBLE);

    if (error.networkResponse == null) {
        if (error.getClass().equals(TimeoutError.class)) {
            // Show timeout error message
            Toast.makeText(getContext(),
                    "Oops. Timeout error!",
                    Toast.LENGTH_LONG).show();
        } else if (error.getClass().equals(NoConnectionError.class)) {
            // Show timeout error message
            Toast.makeText(getContext(),
                    "Oops. Connection error!",
                    Toast.LENGTH_LONG).show();
        }
    } else {
        Toast.makeText(getContext(), "Hata => " + MessagePackage.getErrorMessage(error, getContext()), Toast.LENGTH_SHORT).show();
    }

}

private void useApiOther(String categoryName, Products _lstProduct) {
    recMangaListAdapter = new RecMangaListAdapter(_lstProduct, getContext());
    CardOlustur(categoryName);
}

private void useApi(List<Chapters> lstChapters, String categoryName) {
    recMangaListAdapter = new RecMangaListAdapter(getContext(), lstChapters);
    CardOlustur(categoryName);
}

private TextView TxtOlustur(String text) {
    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    layoutParams.setMargins(15, 10, 0, 10);

    TextView txtView = new TextView(getContext());
    txtView.setText(text);
    txtView.setTextSize(18.0f);
    txtView.setGravity(Gravity.LEFT);
    txtView.setTextColor(getResources().getColor(R.color.colorText));
    txtView.setText(text);
    txtView.setLayoutParams(layoutParams);
    return txtView;
}

private RecyclerView RecOlustur() {
    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
    linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);

    RecyclerView recyclerView = new RecyclerView(getContext());
    recyclerView.setLayoutParams(layoutParams);
    recyclerView.setLayoutManager(linearLayoutManager);
    recyclerView.setAdapter(recMangaListAdapter);
    return recyclerView;
}

private void CardOlustur(String txt) {
    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

    layoutParams.setMargins(15, top, 15, 15);
    top = 0;
    CardView cardView = new CardView(getContext());
    cardView.setLayoutParams(layoutParams);
    cardView.setRadius(5f);
    cardView.setMaxCardElevation(5);

    cardView.addView(LinearLayoutOlustur(TxtOlustur(txt), RecOlustur()));
    lnrlayout.addView(cardView);

}

private LinearLayout LinearLayoutOlustur(TextView txt, RecyclerView recyclerView) {
    LinearLayout linearLayout = new LinearLayout(getContext());
    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    linearLayout.setLayoutParams(layoutParams);
    linearLayout.setOrientation(LinearLayout.VERTICAL);



    linearLayout.addView(txt);
    linearLayout.addView(recyclerView);

    return linearLayout;
}

@Override
public void onNetworkConnectionChangedd(boolean isConnected) {
    if (!isConnected) {
        screen_connectionError.setVisibility(View.VISIBLE);
        Toast.makeText(getContext(), "İnternet Bağlantınızı Kontrol Ediniz.", Toast.LENGTH_SHORT).show();
    } else if (isConnected) {
        lnrlayout.removeView(screen_connectionError);
        ApiPull();
    }
}


@Override
public void onClick(View v) {
    ConnectivityManager conManager = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = conManager.getActiveNetworkInfo();

    boolean isConnection = networkInfo != null && networkInfo.isConnected();
    onNetworkConnectionChangedd(isConnection);
   }
}

错误:

2019-05-10 15:15:44.806 1314-1314/com.yuhdeveloper.manga E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.yuhdeveloper.manga, PID: 1314
    java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
        at android.view.ViewConfiguration.get(ViewConfiguration.java:469)
        at android.view.View.<init>(View.java:4867)
        at android.view.View.<init>(View.java:5054)
        at android.view.ViewGroup.<init>(ViewGroup.java:597)
        at android.widget.FrameLayout.<init>(FrameLayout.java:92)
        at android.widget.FrameLayout.<init>(FrameLayout.java:87)
        at android.support.v7.widget.CardView.<init>(CardView.java:121)
        at android.support.v7.widget.CardView.<init>(CardView.java:117)
        at android.support.v7.widget.CardView.<init>(CardView.java:113)
        at com.yuhdeveloper.mangaship.Fragments.MangaMenuPage.CardOlustur(MangaMenuPage.java:289)
        at com.yuhdeveloper.mangaship.Fragments.MangaMenuPage.useApiOther(MangaMenuPage.java:247)
        at com.yuhdeveloper.mangaship.Fragments.MangaMenuPage.access$100(MangaMenuPage.java:50)
        at com.yuhdeveloper.mangaship.Fragments.MangaMenuPage$2$1.onResponse(MangaMenuPage.java:186)
        at com.yuhdeveloper.mangaship.Fragments.MangaMenuPage$2$1.onResponse(MangaMenuPage.java:178)
        at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:78)
        at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
        at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:106)
        at android.os.Handler.handleCallback(Handler.java:790)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:7000)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:441)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)

共1个答案

匿名用户

避免获取空上下文实例的常见做法,它可能会内存泄漏。其他使用静态应用程序实例,如MyApplication.getInstance()