当前位置: 首页 > 知识库问答 >
问题:

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

梁晋鹏
2023-03-14

当我在<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个答案

符俊材
2023-03-14

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

 类似资料:
  • 我正在尝试使用适配器运行我的应用程序,但在执行此操作时,我遇到了以下错误: ReviewActivity StandupPlayerMain.java

  • 我在使用recycler视图启动活动时出错,因此我有3个文件java类、一个适配器和要执行的活动。 java类只是一个具有3个变量的简单对象 回收器视图的适配器 以及活动 我得到的错误是: 我在一个空项目上做了同样的配置,一切看起来都是正确的,

  • 几个小时后,我发现问题与有关。我得出这个结论是因为尽管调用了该方法,但的值没有改变。 java.lang.NullPointerException:尝试对teamtreehouse . com . my application . weather . forecast . geticoid(forecast . Java:39)处teamtreehouse . com . my applicati

  • 我在运行时得到这个nullPointerException: 原因:java.lang.NullPointerException:试图对空对象引用调用虚拟方法“void android.app.actionbar.SetDisplayHomeasUpenabled(boolean)” 来自MainActivity的代码: 出现问题的代码行是: 我使用:style name=“AppTheme”pa

  • 我正在使用Facebook登录我使用firebase的应用程序。当用户登录时,该应用程序应该从Facebook上获取诸如姓名、电子邮件、性别、位置、简历等信息。在我升级到AndroidStudio 2.2之前,它工作得很好。现在在更新之后,我得到了错误 尝试调用虚拟方法“java”。字符串组织。json。JSONObject。空对象引用上的getString(java.lang.String)”。

  • 因此,我试图从firebase向recyclerview显示图像,但它抛出了一个错误。错误提示E/nite competitive:[qarth _ debug:]get patch store::createDisableExceptionQarthFile方法失败。E/AndroidRuntime:致命异常:主进程:com . example . fortnite competitive,PI

  • 问题内容: 我从joomla安装中收到以下错误。 如何解决此错误? 问题答案: 事实证明,作者错过了一个非常简单的修复程序和一般的良好实践,即您在尝试设置属性之前应始终初始化对象。对此的非常简单的解决方法是,在错误尝试添加的变量之前添加一个调用。 第一行将阻止警告显示。 这也可以通过以下修复来解决该问题。

  • 可能重复: 对象文字声明中的自引用 我在JS中有一些像这个例子这样的简单对象: 这个简单的东西不起作用;john和paul在wholename中未定义,因此我尝试使用“this”运算符,该运算符仅在执行函数时才起作用。但是如果我要用一个变量,而不是函数,我该怎么做呢?我还尝试了,但没有效果。