B
B
Boldy2015-08-11 11:03:07
Android
Boldy, 2015-08-11 11:03:07

How to get json via async task in android?

Bottom line: you need to get json from url. Android Studio complains that .execute() does not return a String but an AsyncTask. I don't understand what I'm doing wrong.

public class DataReceiver {
    public static String readUrl(String urlString) throws IOException {
        String result = (new RetrieveJsonTask()).execute(urlString);
    }


    class RetrieveJsonTask extends AsyncTask<String, Void, String> {

        protected String doInBackground(String... urls) {
            try {
                BufferedReader reader;
                URL url = new URL(urls[0]);

                reader = new BufferedReader(new InputStreamReader(url.openStream()));
                StringBuilder buffer = new StringBuilder();
                int read;
                char[] chars = new char[1024];
                while ((read = reader.read(chars)) != -1) {
                    buffer.append(chars, 0, read);
                }
                return buffer.toString();
            } catch (Exception e) { e.printStackTrace(); }
            return null;
        }
    }
}

Answer the question

In order to leave comments, you need to log in

4 answer(s)
K
Konstantin Berkov, 2015-08-11
@Boldy

Well, because execute actually returns an AsyncTask and not a String. Pass some object to the constructor of your AsyncTask, which you can put the result in the onPostExecute method, well, make the task class static, why does it need an implicit reference to the DataReceiver?

E
Emin, 2015-08-11
@Ewintory

According to the profile, it seems to be not a beginner, but you ask such questions. You can see for yourself what it returns execute(). In general, drop this idea and connect Retrofit

V
Vladimir Yakushev, 2015-08-11
@VYakushev

The essence of AsyncTask is that you start some process in the background and do not wait for a response. This means that execute() does not delay the execution of your code and continues to run in a separate thread. After the task in AsyncTask is completed, the result, as mentioned above, is passed to the onPostExecute() method. It is there that you should get the result and decide what to do with it.
And do not rush to use third-party libraries, you will still have time. Try to understand how the basic features of Android work.

B
belozerow, 2015-08-11
@belozerow

asynctask has onPostExecute, json will be returned there
In general, I will save you a lot of time - look towards retrofit

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question