简体   繁体   English

尝试从其他类调用函数时,应用程序崩溃

[英]app crash when trying to call function from different class

I am trying to call function getData() after they sort spinner change but i keep getting error and app crash. 我尝试在对微调框的变化进行排序后调用函数getData(),但我不断收到错误消息,并导致应用崩溃。

This is the function inside my homepageActivity : 这是我的homepageActivity内部的函数:

private JsonArrayRequest getDataFromServer(int requestCount, int SortType) {
        //Initializing ProgressBar
        final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar1);
        String FINAL_URL = "";
        //Displaying Progressbar
        progressBar.setVisibility(View.VISIBLE);
        setProgressBarIndeterminateVisibility(true);

        //JsonArrayRequest of volley
        if(SortType == 0){
            FINAL_URL = Config.DATA_URL + String.valueOf(requestCount);
        }else if (SortType == 1){
            FINAL_URL = Config.DATA_URL + String.valueOf(requestCount);
        }else{
            Log.d("ERROR:","sort is more than 1");
        }
        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(FINAL_URL,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        //Calling method parseData to parse the json response
                        parseData(response);
                        //Hiding the progressbar
                        progressBar.setVisibility(View.GONE);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        progressBar.setVisibility(View.GONE);
                        //If an error occurs that means end of the list has reached
                        Toast.makeText(homepageActivity.this, "No More Items Available", Toast.LENGTH_SHORT).show();
                    }
                });

        //Returning the request
        return jsonArrayRequest;
    }

    //This method will get data from the web api
    public void getData(int sort) {
        //Adding the method to the queue by calling the method getDataFromServer
        requestQueue.add(getDataFromServer(requestCount, sort));
        //Incrementing the request counter
        requestCount++;
    }

    //This method will parse json data
    private void parseData(JSONArray array) throws RuntimeException {
        for (int i = 0; i < array.length(); i++) {
            //Creating the superhero object
            SuperHero superHero = new SuperHero();
            JSONObject json = null;
            try {
                //Getting json
                json = array.getJSONObject(i);
                //Adding data to the superhero object
                superHero.setImageUrl(json.getString(Config.TAG_IMAGE_URL));
                superHero.setName(json.getString(Config.TAG_NAME));
                superHero.setPublisher(json.getString(Config.TAG_PUBLISHER));
            } catch (JSONException e) {
                e.printStackTrace();

            }
            //Adding the superhero object to the list
            listSuperHeroes.add(superHero);
        }
        //Notifying the adapter that data has been added or changed
        Log.d("ADebugTag", "Value: " + listSuperHeroes);

        adapter.notifyDataSetChanged();
    }

and this is what I have inside my cardadapter : 这就是我的cardadapter内部的内容:

HPC = new homepageActivity();
                Boolean checkFirst = true;
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long l) {
                    if(!checkFirst){
                        Log.d("ERROR:","hello world is clicked" + position);
                        homepageActivity.sortDataOn = false;
                        homepageActivity.listSuperHeroes.clear();
                        homepageActivity.adapter.notifyDataSetChanged();
                        homepageActivity.sortType = position;
                        HPC.getData(homepageActivity.sortType);
                    }

                    checkFirst = false;
                }

The app works okay until I change spinner and it tries to call getData function and then it crash and it gives this error below: 该应用程序可以正常运行,直到我更改了微调框,并尝试调用getData函数,然后崩溃,并在以下显示此错误:

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.yemencar.yemencar, PID: 4714
                  java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
                      at android.support.v7.app.AppCompatDelegateImpl.<init>(AppCompatDelegateImpl.java:247)
                      at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:182)
                      at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:520)
                      at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:191)
                      at com.yemencar.yemencar.homepageActivity.getDataFromServer(homepageActivity.java:91)
                      at com.yemencar.yemencar.homepageActivity.getData(homepageActivity.java:131)
                      at com.yemencar.yemencar.CardAdapter$VHHeader$1.onItemSelected(CardAdapter.java:162)
                      at android.widget.AdapterView.fireOnSelected(AdapterView.java:944)
                      at android.widget.AdapterView.dispatchOnItemSelected(AdapterView.java:933)
                      at android.widget.AdapterView.-wrap1(Unknown Source:0)
                      at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:898)
                      at android.os.Handler.handleCallback(Handler.java:789)
                      at android.os.Handler.dispatchMessage(Handler.java:98)
                      at android.os.Looper.loop(Looper.java:164)
                      at android.app.ActivityThread.main(ActivityThread.java:6541)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

--EDIT-- - 编辑 -

based on Mike M comment I cant use HPC = new homepageActivity(); 基于Mike M的评论,我无法使用HPC = new homepageActivity(); So to move forward what options I have to achieve what I trying to do here , to make it clear I have a recyclerView with a sort spinner in its header, so when this sort is change eg "by date" then I want to update the recyclerView content. 因此,要前进一些选项,我必须实现我在这里想要做的事情,要弄清楚我的标题中有一个带有排序微调器的recyclerView,因此当这种排序更改时,例如“按日期”,那么我想更新recyclerView内容。

It sounds like your goal is to somehow communicate with your Activity from inside your onItemSelected() callback. 听起来您的目标是从onItemSelected()回调内部以某种方式与Activity通信。

One way to do this is to leverage the parent argument to the callback... all View instances have a getContext() method, and unless something non-standard is going on that context will be your activity. 一种实现方法是将parent参数用于回调...所有View实例均具有getContext()方法,除非在该上下文上进行了非标准操作,否则将成为您的活动。 So you could do something like this: 因此,您可以执行以下操作:

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long l) {
    homepageActivity activity = (homepageActivity) parent.getContext();
    // now you can call activity.sortDataOn etc
}

It's also possible that you'd be better off passing a reference to your activity to your adapter whenever you create it, but without your full code it's hard to say. 创建适配器时,最好将对活动的引用传递给适配器,但如果没有完整的代码,这很难说。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM