我目前从异步方法(XmlParser.java)中获取Json数据,并将其作为String传递回textview,现在我需要传递回ArrayList,我需要在下面的代码中对此进行更改工作?
BookDetail.java
public class BookDetail extends AppCompatActivity {
public static TextView tvBooks;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_schedule_detail);
tvBooks = (TextView) findViewById(R.id.tvBooks);
XmlParser xmlParser = new XmlParser();
XmlParser.theUrl = "http://pathtoapi.xxxxx/api;
xmlParser.execute();
}
}
XMLParser.java
public class XmlParser extends AsyncTask<Void,Void,Void> {
String data ="";
String dataParsed = "";
String singleParsed ="";
public static String theUrl;
protected Void doInBackground(Void... voids) {
try {
URL url = new URL(theUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while(line != null){
line = bufferedReader.readLine();
data = data + line;
}
list = new ArrayList<Agenda>();
JSONArray JA = new JSONArray(data);
for(int i =0 ;i <JA.length(); i++){
JSONObject JO = (JSONObject) JA.get(i);
singleParsed = "Book: " + JO.get("bookName");
dataParsed = dataParsed + singleParsed +"\n" ;
}
} 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);
// Here a TextView is populated with String
// But I would like to pass an ArrayList instead that can populate a ListView instead
BookDetail.tvBooks.setText(this.dataParsed);
}
}
答案 0 :(得分:1)
如果您想从AsyncTask
返回一个值,那么您的AsyncTask
定义必须是这样的:
public class XmlParser extends AsyncTask<Void,Void,ArrayList<Agenda>> {
protected ArrayList<Agenda> doInBackground(Void... voids) {
// do background
return list;
}
protected void onPostExecute(ArrayList<Agenda> list) {
}
}
在AsyncTask模板中,第一个参数是传递给任务的值的类型,第二个参数是传递给onProgress的值,最后一个参数是doInBackground的返回值的类型
并将get方法添加到execute语句的末尾:
ArrayList<Agenda> list = xmlParser.execute().get();