Reputation: 21
i want to get my array in method getDataJSON()
from inner class
this is a part from my code
the function getdatajson
will fill the arraylist with the returned array dataJSONarray
from
the inner class getJsonFromServer
how can i do it?
public ArrayList<note> getdatajson() {
ArrayList<note> list = new ArrayList<note>();//to verify
new getJsonFromServer().execute();
return list;
}
private class getJsonFromServer extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... strings) {
try {
//make connexion with web server
URL url= new URL("http://192.168.1.18/pfe/");
URLConnection urlConnection= url.openConnection();
InputStreamReader inputStreamReader= new InputStreamReader(urlConnection.getInputStream());
BufferedReader bufferedReader= new BufferedReader(inputStreamReader);
String ligne;
while ((ligne = bufferedReader.readLine()) != null){
jsonArray= new JSONArray(ligne);
}
//convert data from json array to java object
Gson gson= new Gson();
dataJSONarray= gson.fromJson(jsonArray.toString(), dataJSON[].class);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
Upvotes: 1
Views: 71
Reputation: 1338
There is no need to create a separate class like this. You can use AsyncTask
in your existing class. The job of AsyncTask
is to perform asynchronous operations. The framework provides you a method called onPostExecute
. You can use it to do any operations that you want.
Please see the example below.
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
This sample code is taken from Android Developer Website.
Upvotes: 1