0

I'm trying to get a daily quote from

http://quotesondesign.com/api/3.0/api-3.0.json?callback=json

I call this method in my onCreate But when i try to execute the httpclient.execute(); it escapes to the catch statement...

What am I doing wrong?

I did include the <uses-permission android:name="android.permission.INTERNET" /> in my manifest file.

public String getJson(){
        String quoteUrl = "http://quotesondesign.com/api/3.0/api-3.0.json?callback=?";
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(quoteUrl);

        httpget.setHeader("Content-type", "application/json");

        InputStream inputStream = null;
        String result = null;
        String aJsonString = null;
        try {
            HttpResponse response = httpclient.execute(httpget);
            Toast.makeText(this, "It works", Toast.LENGTH_LONG).show();
            HttpEntity entity = response.getEntity();

            inputStream = entity.getContent();
            // json is UTF-8 by default
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
            StringBuilder sb = new StringBuilder();

            String line = null;
            while ((line = reader.readLine()) != null)
            {
                sb.append(line + "\n");
            }
            result = sb.toString();
            JSONObject jObject = new JSONObject(result);
            aJsonString = jObject.getString("quote");

        } catch (Exception e) {
            //Toast.makeText(this, "can't execute http request", Toast.LENGTH_LONG).show();
        }
        finally {
            try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
        }

        return aJsonString;
    }

EDIT: here is the onCreate()

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //verbergt notificatiebalk
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
    WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.splash);

    jsonstring = getJson();
    Log.d(jsonstring, "The jsonstring contains: " + jsonstring);
    //Toast.makeText(this, jsonstring, Toast.LENGTH_LONG).show();
    //tot hier testen
    new Handler().postDelayed(new Runnable() {

        @Override
        public void run() {
            Intent i = new Intent(SplashScreen.this, MainActivity.class);
            startActivity(i);

            finish();
        }
    }, SPLASH_TIME_OUT);
}

Thank you in advance!

Arno Turelinckx
  • 123
  • 1
  • 1
  • 12

3 Answers3

0

In your code you have

String quoteUrl = "http://quotesondesign.com/api/3.0/api-3.0.json?callback=?";

While the URL you want to fetch is

http://quotesondesign.com/api/3.0/api-3.0.json?callback=json

Notice how in your code you have callback=? while the URL has callback=json.

justhecuke
  • 765
  • 4
  • 8
  • Since you have a query, I'd suggest building a URI. – justhecuke May 01 '15 at 10:48
  • since i'm pretty new to android coding, tell me, what is this URI and what do I use it for? – Arno Turelinckx May 01 '15 at 10:49
  • Well, it's common in networking libraries for the handling of URI encoding to be rather insane. You never know which method is handling an encoded string or the "raw" string. In order to make sure that the Android Framework isn't messing with your string, you can build your URI manually. A URI is simply a way of addressing things using the common http://blahblah.com:8080/mypage?k=v#anchor format. It's a bit more complicated than that, but you don't need to worry. Refer to http://stackoverflow.com/questions/2959316/how-to-add-parameters-to-a-http-get-request-in-android for help doing it. – justhecuke May 01 '15 at 10:55
  • I have to admit, messing around with URIs like this is typically a nightmare to get right. Think of it as a learning experience where you don't learn anything except for pain and frustration. – justhecuke May 01 '15 at 10:59
0

After Android 4.2, you can't make Http Request on the UI-Thread (the "main" thread). You need to do it in a seperate thread.

You can find an example on this website or in this stackoverflow post: HttpClient.execute(HttpPost) on Android 4.2 error

Community
  • 1
  • 1
Manuel Allenspach
  • 12,467
  • 14
  • 54
  • 76
0

Update: Actual answer with code now vailable:

private class AsyncQuoteDownload extends AsyncTask<Void, Void, String>{

    @Override
    protected String doInBackground(Void... params) {
        String jsonData = getJson(); //or, if the jsonData var is available from everywhere, just put myR.run(); here, return null, and append the data directly in onPostExecute
        return jsonData;
    }

    @Override
    protected void onPostExecute(String result) {
        (TextView)findViewById(R.id.Quote).append(result).append("\"");
    } //  \" makes it put an actual " inside a string
}

Old answer:

I bet your stacktrace (which isn't as an error because oyu catch it, but it's in the log) reads something like "Network on Main Thread"?

Because that's something you're trying to do, and that's something you aren't allowed to do. Instead, put it in an AsyncTask:

onCreate(){ //beware pseudo code because it doesn't matter
    //do stuff
    setContentView(...); //Above here, everything stays as is.
    //below here, only that:
    new GetQuoteTask.execute();
}

class GetQuoteTask extends AsyncTask<Void, Void, String>{
    String doInBackground(...){ //<- pseudo code, code completion is your friend
        String result = getJson();
        Log.d(jsonstring, "The jsonstring contains: " + jsonstring);
        return result;
    }
    onPostExecute(String result){
        maybePutYourStringSomewhereAKAUpdateUI();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent i = new Intent(SplashScreen.this, MainActivity.class);
                startActivity(i);
                finish();
            }
        }, SPLASH_TIME_OUT);
    }
}
Squirrelkiller
  • 2,575
  • 1
  • 22
  • 41