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

时间:2018-07-30 21:18:03

标签: java android

我试图在对Spinner进行排序后调用函数getData(),但我不断收到错误消息并导致应用崩溃。

这是我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();
    }

这就是我的适配器内部的内容:

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

在我更改微调器之前,该应用程序正常运行,并尝试调用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)

-编辑-

基于Mike M的评论,我不能使用HPC = new homepageActivity();,所以为了继续前进,必须实现我在这里想要执行的操作,要弄清楚我在标题中有一个带有排序微调器的recyclerView,因此当这种更改发生变化时,例如“按日期”,那么我想更新recyclerView内容。

1 个答案:

答案 0 :(得分:1)

听起来您的目标是从onItemSelected()回调内部以某种方式与您的活动进行通信。

执行此操作的一种方法是将parent参数用于回调...所有View实例都具有getContext()方法,除非正在进行非标准操作上下文将是您的活动。因此,您可以执行以下操作:

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

创建适配器时最好将对活动的引用传递给适配器,但是如果没有完整的代码,这很难说。