英文:
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<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.
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.
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和异步/同步请求方面的内容会有帮助:
- https://stackoverflow.com/questions/31798972/how-to-wait-the-volley-response-to-finish-its-work-inside-intentservice
- https://stackoverflow.com/questions/16904741/can-i-do-a-synchronous-request-with-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:
- https://stackoverflow.com/questions/31798972/how-to-wait-the-volley-response-to-finish-its-work-inside-intentservice
- https://stackoverflow.com/questions/16904741/can-i-do-a-synchronous-request-with-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, ...).
答案2
得分: 1
你的 computerServicesArrayList
是通过 Volley 的回调(new Response.Listener<String>()
)进行填充的。正如你已经验证的那样,这个填充过程是正确的。但是由于网络来回传输需要一些时间,所以它会花一些时间。当你的 MainActivity
对 mySQLConnect.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<String> {
/* --- */
@Override
public void onResponse(String response) {
showJSON(response);
}
void showJSON(String response){
// Do the stuff here
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论