因此,在我的 Android 应用程序中,我尝试将 Json 链接转换为 ListView ,但是当我发送 ArrayList 时,我得到一个空列表。
我的代码:
类 fetchData
public class fetchData extends AsyncTask<Void,Void,Void> {
ArrayList<Person> persons = new ArrayList<Person>();
String data="";
String dataParsed="";
String singleParsed="";
@Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL("https://jsonplaceholder.typicode.com/users");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bf = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while ( line != null){
line = bf.readLine();
data = data + line;
}
JSONArray array = new JSONArray(data);
for (int i=0;i<array.length();i++){
JSONObject jo = (JSONObject) array.get(i);
Person p = new Person(jo.getString("id"),jo.getString("name"),jo.getString("username"),jo.getString("email"));
this.persons.add(p);
singleParsed =p.toString();
dataParsed = dataParsed + singleParsed;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
MainActivity.informations= this.dataParsed;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
Button moreInfos;
public static ArrayList<Person> persons = new ArrayList<Person>();
public static String informations;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
moreInfos = (Button) findViewById(R.id.goInfos);
fetchData process = new fetchData();
process.execute();
moreInfos.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, Informations.class);
String message = informations;
intent.putExtra("msg", message);
startActivity(intent);
// normally we need to pass the arraylist that contains the list of our persons
}
});
}
}
现在在我的 MainActivity 中,如果我检查 ArrayList 人员的大小,我得到 0,任何人都可以帮助我或指导我,以便我可以解决这个问题吗?
最佳答案
您的 Activity 中的列表是空的,因为您实际上从未在其中放入任何内容。请记住,异步任务中的列表与 Activity 中的列表不同,因此您必须实际复制它。
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
MainActivity.informations = this.dataParsed;
// defensively copy
MainActivity.persons = new ArrayList<>(this.persons);
}
您还可以在代码中改进一些其他内容(例如,当您应该使用回调时,在 Activity 中使用静态字段),但这应该可以解决眼前的问题。
关于java - 空数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53153628/