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

huangapple go评论83阅读模式
英文:

Java Android Studio cannot send ArrayList from another class to MainActivity

问题

我试图将对象的数据添加到ArrayList中,但无法正常工作。

这段代码从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();
    }
}

在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());
}

输出结果如下:

Size in MainActivity
0
Size in class MySQLConnect
83

从代码中我可以打印computerServicesArrayList.size(),结果为83,但当我从MainActivity中打印时,为什么显示为0。如何修复这个问题?

英文:

I try to add data from my object to ArrayList but it's not work.

This code read data from JSON and add to ArrayList in MySQLConnect.java like this.

    private ComputerService computerservice;
public static ArrayList&lt;ComputerService&gt; computerServicesArrayList = new ArrayList&lt;&gt;();
private String URL = &quot;http://10.200.100.10/&quot;, GET_URL = &quot;android/get_data.php&quot;;
public MySQLConnect(){
main = null;
}
public MySQLConnect(Activity mainA){
main = mainA;
}
public List&lt;ComputerService&gt; getData(){
String url = URL + GET_URL;
StringRequest stringRequest = new StringRequest(url, new Response.Listener&lt;String&gt;() {
@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 = &quot;&quot;;
computerServicesArrayList.clear();
try{
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(&quot;data&quot;);
for(int i=0; i &lt; result.length(); i++){
JSONObject collectData = result.getJSONObject(i);
String id = collectData.getString(&quot;id&quot;);
String type = collectData.getString(&quot;type&quot;);
String address = collectData.getString(&quot;address&quot;);
computerservice = new ComputerService(id, type, address);
computerServicesArrayList.add(computerservice);
}
System.out.println(&quot;Size in class MySQLConnect&quot;);
System.out.println(computerServicesArrayList.size());
} catch (JSONException e) {
e.printStackTrace();
}
}

The MainActivity.java I show computerServicesArrayList.size() like this.

 public static List&lt;ComputerService&gt; 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(&quot;Size in MainActivity&quot;);
System.out.println(computerServicesArrayList.size());
}

The output show like this.

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?

答案1

得分: 2

我不详细了解Volley框架/类。但是看起来你正在创建一个异步请求。因此,在发送rest请求后,当响应到达时会调用你的showJSON()方法。

但是你立即返回了computerServicesArrayList结果,该结果是空的,因为你还没有收到响应。这也是为什么你的MainActivity中的打印语句在showJSON方法的打印之前被执行的原因。

如果你想等待rest响应,你需要进行同步请求。

也许这些链接对你了解更多关于Volley和异步/同步请求方面的内容会有帮助:

但通常情况下,你会发送异步请求,当你收到响应后再进行逻辑处理(更新字段,将某些内容存储在数据库中,...)。

英文:

I don't know the Volley framework/classes in detail. 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.

But you immediatley return the computerServicesArrayList result, which is empty because you don't have your response yet. This is also the reason why the print statement from your MainActivity is executed before the print from your showJSON method.

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:

But normally you would send an async-request and when you get the response you do your logic (update fields, store something in database, ...).

答案2

得分: 1

你的 computerServicesArrayList 是通过 Volley 的回调(new Response.Listener<String>())进行填充的。正如你已经验证的那样,这个填充过程是正确的。但是由于网络来回传输需要一些时间,所以它会花一些时间。当你的 MainActivitymySQLConnect.getData() 进行调用时,这个往返行程还没有完成;因此你会在 MainActivity 中得到一个空的列表。

解决这个问题的常见方法是让监听器调用 MainActivity 中的方法。可以通过以下方式实现:

class MainActivity implements Response.Listener<String> {

    /* --- */
    @Override
    public void onResponse(String response) {
        showJSON(response);
    }
    
    void showJSON(String response){
        // 在这里进行操作
    }
}
英文:

Your computerServicesArrayList is populated by callback from Volley (new Response.Listener<String>()). 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; so you get an empty list in MainActivity.

The usual solution to this problem is to make the listener call methods in MainActivity. This can be done by making

class MainActivity implements Response.Listener&lt;String&gt; {
/* --- */
@Override
public void onResponse(String response) {
showJSON(response);
}
void showJSON(String response){
// Do the stuff here
}

huangapple
  • 本文由 发表于 2020年7月23日 16:47:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/63050353.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定