0

i have a problem with get the json data, i have follow the youtube or some tutorial regarding the fetch the json data from url. I'm want write fetch data to the String data and display to the TextView at MainActivity like "onPostExecute()". I think, there some problem with my code, and can you help to check my code?


{  "zone":"SGR01",
   "start":"14-01-2020",
  "end":"14-01-2020",
   "locations":[
    "Gombak","Hulu Selangor","Rawang","Hulu Langat","Sepang","Petaling","Shah Alam"],
   "prayer_times":{
        "date":"14-01-2020",
        "datestamp":1578931200,
        "imsak":"6:02 am",
        "subuh":"6:12 am",
        "syuruk":"7:22 am",
        "zohor":"1:25 pm",
        "asar":"4:47 pm",
        "maghrib":"7:22 pm",
        "isyak":"8:36 pm"
        } 
}
//---------

public class fetchData extends AsyncTask<Void, Void, Void> {
String data ="";

 @Override
    protected Void doInBackground(Void... voids) {
 try {
            URL url = new URL("url");

            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;
    }
    } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
  @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        Log.d("DisplayData--",data);
        MainActivity.data.setText(data);
    }
Markus Kauppinen
  • 3,025
  • 4
  • 20
  • 30
jumper
  • 105
  • 10
  • Define your class as `FetchData extends AsyncTask`. Do not declare `data` variable in that class. Read content in `String doInBackground(String... voids)` method and return it instead of `null`. After that in `void onPostExecute(String data)` method print it as you doing it right now. – Michał Ziober Jan 16 '20 at 22:09

1 Answers1

2

I observed one mistake and i modified code like below. And use StringBuffer to improve performance.

     StringBuffer sb = new StringBuffer();
     String line = "";
     while(( line = bufferedReader.readLine()) != null ) 
     { 
         sb.append(line);
     }
     data = sb.toString();
Ranjith Bokkala
  • 379
  • 1
  • 10