简体   繁体   English

Java Android Studio 无法将 ArrayList 从另一个 class 发送到 MainActivity

[英]Java Android Studio cannot send ArrayList from another class to MainActivity

I try to add data from my object to ArrayList but it's not work.我尝试将数据从我的 object 添加到 ArrayList 但它不起作用。

This code read data from JSON and add to ArrayList in MySQLConnect.java like this.此代码从 JSON 读取数据,并像这样添加到 MySQLConnect.java 中的 ArrayList 中。

    private ComputerService computerservice;
    public static ArrayList<ComputerService> computerServicesArrayList = new ArrayList<>();
    private String URL = "http://10.200.100.10/", GET_URL = "android/get_data.php";

    public MySQLConnect(){
        main = null;

    }

    public MySQLConnect(Activity mainA){
        main = mainA;
    }

    public List<ComputerService> getData(){
        String url = URL + GET_URL;
        StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                showJSON(response);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(main, error.getMessage().toString(), LENGTH_LONG).show();
            }
        }

        );

        RequestQueue requestQueue = Volley.newRequestQueue(main.getApplicationContext());
        requestQueue.add(stringRequest);

        return computerServicesArrayList;
    }

    public void showJSON(String response){
        String data_mysql = "";
        computerServicesArrayList.clear();
        try{
            JSONObject jsonObject = new JSONObject(response);
            JSONArray result = jsonObject.getJSONArray("data");

            for(int i=0; i < result.length(); i++){
                JSONObject collectData = result.getJSONObject(i);
                String id = collectData.getString("id");
                String type = collectData.getString("type");
                String address = collectData.getString("address");

                computerservice = new ComputerService(id, type, address);
                computerServicesArrayList.add(computerservice);

            }

        System.out.println("Size in class MySQLConnect");
        System.out.println(computerServicesArrayList.size());

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

The MainActivity.java I show computerServicesArrayList.size() like this. MainActivity.java 我这样展示了 computerServicesArrayList.size()。

 public static List<ComputerService> computerServicesArrayList;

 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mySQLConnect = new MySQLConnect(MainActivity.this);

        update();
    }


    public void update(){
        computerServicesArrayList =  mySQLConnect.getData();
        System.out.println("Size in MainActivity");
        System.out.println(computerServicesArrayList.size());
}

The output show like this. output 显示如下。

Size in MainActivity
    0

Size in class MySQLConnect
83

From the code I can print computerServicesArrayList.size() the result is 83 but when I print from MainActivity why it show result 0. How to fix it?从代码中我可以打印 computerServicesArrayList.size() 结果是 83 但是当我从 MainActivity 打印时为什么它显示结果 0。如何解决它?

I don't know the Volley framework/classes in detail.我不详细了解Volley框架/类。 But it looks like you are creating an asynchronous request.但看起来您正在创建一个异步请求。 So your rest-request gets send and when the response comes in your showJSON() method is called.因此,您的休息请求会被发送,并且当您的showJSON()方法收到响应时会被调用。

But you immediatley return the computerServicesArrayList result, which is empty because you don't have your response yet.但是您立即返回了computerServicesArrayList结果,该结果为空,因为您还没有回复。 This is also the reason why the print statement from your MainActivity is executed before the print from your showJSON method.这也是MainActivity的 print 语句在showJSON方法的 print 之前执行的原因。

If you want to wait for the rest-response you have to do synchronous requests.如果你想等待休息响应,你必须做同步请求。

Maybe this can help you more about Volley and asyn/sync requests:也许这可以帮助您更多地了解 Volley 和异步/同步请求:

But normally you would send an async-request and when you get the response you do your logic (update fields, store something in database, ...).但通常你会发送一个异步请求,当你得到响应时你会执行你的逻辑(更新字段,在数据库中存储一些东西,......)。

Your computerServicesArrayList is populated by callback from Volley (new Response.Listener()).您的 computerServicesArrayList 由 Volley 的回调填充(新的 Response.Listener())。 This population happens correctly as you have verified.正如您已验证的那样,此人口正确地发生。 But it does take some time, for the network up/down travel.但是网络上/下旅行确实需要一些时间。 When your MainActivity's call to mySQLConnect.getData() returns this round trip is not complete yet;当您的 MainActivity 对 mySQLConnect.getData() 的调用返回时,此往返行程尚未完成; so you get an empty list in MainActivity.所以你在 MainActivity 中得到一个空列表。

The usual solution to this problem is to make the listener call methods in MainActivity.通常解决这个问题的方法是让监听器调用 MainActivity 中的方法。 This can be done by making这可以通过使

class MainActivity implements Response.Listener<String> {

/* --- */
@Override
public void onResponse(String response) {
    showJSON(response);
}

void showJSON(String response){
    // Do the stuff here
}

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

相关问题 Android Studio:从另一个 class 调用 MainActivity 的 Function(如 checkSelfPermission) - Android Studio: Calling Function (like checkSelfPermission) of MainActivity from another class 无法从 Java Android Studio 中的另一个 class 调用变量 - Cannot called a variable from another class in Java Android Studio 从android中的另一个类调用MainActivity方法 - Call MainActivity method from another class in android 将MainActivity中的逻辑移动到Android中的另一个类 - Moving logic from MainActivity to another class in Android 来自Android中另一个类的mainactivity中的调用方法 - calling method in mainactivity from another class in android Android Studio MainActivity 类无法连接到本地 Mysql Workbench - Android Studio MainActivity Class cannot connect to local Mysql Workbench Android Studio - 如何将数据从 MainActivity.xml 发送到服务? - Android Studio - How to send data from MainActivity.xml to Service? Android工作室如何在MainActivity.kt中调用java class? - Android studio how to call java class in MainActivity.kt? 如何从Android Java中的另一个类访问ArrayList? - How to access ArrayList from another class in Android Java? 通过创建实例android从MainActivity类调用方法到另一个类 - Calling method from MainActivity class to another class by creating instance android
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM