从内部类返回值

时间:2018-02-16 11:42:31

标签: android json inner-classes

我想从内部类中获取方法getDataJSON()中的数组 这是我的代码的一部分 函数getdatajson将使用返回的数组dataJSONarray填充arraylist 内部类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;
    }
}

1 个答案:

答案 0 :(得分:1)

无需像这样创建单独的类。您可以在现有课程中使用AsyncTaskAsyncTask的工作是执行异步操作。该框架为您提供了一个名为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