如何在不单击按钮的情况下在 onCreate() 中使用 运行 方法

How to run methods in onCreate() without button click

现在,我必须在我的应用程序启动时单击按钮两次才能显示数据。我想要 打开显示数据的应用程序。如果不使用 onclick 方法,来自 volley api 请求的数据不会加载。我正在使用 recyclerviw 将数据绑定到视图。我什至尝试创建一个单独的 class 来获取数据,但仅适用于按钮点击。

    private ArrayList<Stocks_data_model> exampleList;
    private RequestQueue mQueue;
    static String t;
    static String n;
    static String p;
    static String c;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mQueue = MySingleton.getInstance(this).getRequestQueue();
        exampleList = new ArrayList<>();


        findViewById(R.id._button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                     my_func(exampleList);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        //real data
    }


    public  void my_func(ArrayList mAr){
//         exampleList = new ArrayList<>();

        String _url = "";
        // TODO: Handle error
        //                    Toast.makeText(getApplicationContext(), "[NETWORK ERROR]\nCheck Data Connection...", Toast.LENGTH_SHORT).show();
        JsonObjectRequest req_Gainers2 = new JsonObjectRequest
                (Request.Method.GET, _url, null, response -> {
                    try {
                        Log.d("tag", "working");

                        for(int i=0; i<5; i++){
                        JSONArray gainers = response.getJSONArray("mostGainerStock");
                        JSONObject myData = gainers.getJSONObject(i);
                        String _name = myData.getString("companyName");
                        String _ticker = myData.getString("ticker");
                        String _price = myData.getString("price");
                        double _changes = myData.getDouble("changes");
                        String _change_percent = myData.getString("changesPercentage");

                        mAr.add(new Stocks_data_model(_ticker, _name, _price, _change_percent));
//                         exampleList.add(new Stocks_data_model(_ticker, "name", ".99", _change_percent));

                            t = _ticker;
                            n=_name;
                            p=_price;
                            c=_change_percent;


                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }, Throwable::printStackTrace);
//         mQueue.add(req_Gainers2);
        mQueue.add(req_Gainers2);

        buildRecyclerView();

    }
}

经过一些反馈,这是我尝试过的新 onCreate 方法,它仍然存在同样的问题。

protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
         mQueue = MySingleton.getInstance(this).getRequestQueue();
         exampleList = new ArrayList<>();


         findViewById(R.id._button).setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {
                 try {
                      my_func(exampleList);
                      buildRecyclerView();

                 } catch (Exception e) {
                     e.printStackTrace();
                 }
             }
         });

您提到您希望在不单击按钮的情况下加载数据,并且您将所有负责检索和显示数据的代码放在按钮的 OnClickListener 中。 如果要在应用加载时显示数据,请将所有代码从 OnClickListener 中取出。

您在双击之前看不到数据是因为,一旦您单击,数据检索就会异步开始,并且代码保持 运行 并达到设置 recyclerview 的目的。但数据尚未检索。这就是 recyclerview 什么都不显示的原因。

在您随后点击按钮时,数据检索完成,recyclerview 可以显示数据。

要修复它,我们需要等到数据被检索到。这可以通过多种方式实现。 快速修复可以在 my_func().

内的 try 块的最后一行调用 buildRecyclerView() 函数

要在不点击的情况下获取数据,请在点击侦听器外部调用方法。

    my_func(exampleList);

在 my_fun() 方法之前 运行 你的 buildRecyclerView(); oncreate 中的方法。

然后在try块的最后一行通知recyclerView的adapter更新其中的数据

只需在 onCreate 中调用您的方法即可。例如:

protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     mQueue = MySingleton.getInstance(this).getRequestQueue();
     exampleList = new ArrayList<>();
     
     thisIsMyFunction();
     }


public void thisIsMyFunction() {
     try {
          my_func(exampleList);
          buildRecyclerView();

     } catch (Exception e) {
          e.printStackTrace();
     }
     //you can add all the code you want to execute here
}