我想从内部类的方法 getDataJSON()
中获取我的数组
这是我代码的一部分
函数 getdatajson
将用返回的数组 dataJSONarray
填充数组列表
内部类 getJsonFromServer
我该怎么做?
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;
}
}
最佳答案
没有必要像这样创建一个单独的类。您可以在现有类中使用 AsyncTask
。 AsyncTask
的工作是执行异步操作。该框架为您提供了一个名为 onPostExecute
的方法。您可以使用它来执行您想要的任何操作。
请看下面的例子。
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");
}
}
此示例代码取自 Android Developer Website .
关于android - 内部类的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48826041/