0

I'm trying to grab some JSON from a url, but I'm having trouble opening the stream even though I'm running the code on a different thread using AsyncTask. I never make it to the "stream successfully opened" print statement. Other similar examples of this issue I could find on stack overflow are here, here, and here, but I still can't figure it out. Any help would be appreciated!

Credit Here for the JSON Grabbing & Processing code.

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.InputStream;
import java.io.Reader;



public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button button = (Button) findViewById(R.id.button);
    System.out.println("Set Bustton");

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            System.out.println("Made it to On click");
            new JSONGod().doInBackground();
        }

    });
}


private class JSONGod extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... params) {
        try {

            System.out.println("Made it to doInBackground");

            URL url = new URL("Url Here");
            InputStream is = url.openStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));

            System.out.println("Stream Successfully Opened");
            try {
                String jsonText = readAll(rd);
                System.out.println("Made it past read all");
                JSONObject json = new JSONObject(jsonText);
                //Do things with JSON here
            } finally {
                is.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    private String readAll(Reader rd) throws IOException {
        System.out.println("Made it to read all");
        StringBuilder sb = new StringBuilder();
        int cp;
        while ((cp = rd.read()) != -1) {
            sb.append((char) cp);
        }
        return sb.toString();
    }
}
}
Community
  • 1
  • 1
Michael Eliot
  • 831
  • 8
  • 18

0 Answers0