Issue
I currently fetch Json data from a async method (XmlParser.java) and pass that as a String back to a textview, I now need to pass back an ArrayList instead, what do I need to change in the below code for that to work?
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);
}
}
Solution
if you want to return a value from AsyncTask
then your AsyncTask
definition be must like this:
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) {
}
}
in AsyncTask template, the first argument is type of passed value to task, the second argument is value that pass to onProgress , and the last argument is for type of return value of doInBackground
and add get method to end of execute statement:
ArrayList<Agenda> list = xmlParser.execute().get();
Answered By - nariman amani
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.