0
votes

I am working on an android app which uses AsyncTasks in order to get JSON data from an applications API. When I start my app, everything goes well and the app gets the right information out of the API.

I implemented ActionBar pull-to-refresh library so people can drag down my listview to refresh their data. Now my app crashes on this point.

Instead of receiving any text, my BufferedReader.readline returns strings like this.

���ĥS��Zis�8�+(m��L�ޔ�i}�l�V�8��$AI0��(YN�o�lI�,9cO�V͇�    $��F���f~4r֧D4>�?4b�Տ��P#��|xK#h�����`�4@H,+Q�7��L�

Everytime my app wants to receive data, a new AsyncTask will be created so I don't know why my reader returns something like that...

I hope you guys can give me any idea on how to fix this!

EDIT: This is how I get my data.

BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8")); } catch (IOException e1) { e1.printStackTrace(); }

    String s = null;
    String data = "";
    try {
        while ((s = reader.readLine()) != null)
        {
            data += s;
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
2
I would say your server is sending that stuff. There's nothing wrong with this code, unless the server is sending binary data, in which case you shouldn't be using Readers and Strings at all.user207421
I don't think that is the problem. Since the server gives standard JSON data, I can just open it in my browser. When I open the same URL on my computer and when I start my app, it works.Reverb
Are you closing the Reader?user207421
Yes, I do. But it's unnecessary to close the reader because it's a aysnctask, it will be automatically killed.Reverb
It is never unnecessary to close a Reader, unless there is an outer Reader around it or it is around a Socket which you have already closed, or whose output stream you have closed.user207421

2 Answers

1
votes

I just had the same issue. I found out that the returned HTML might be compressed into a GZIP format. Use something like this to check for encoding, and use the appropriate streams to decode the content:

URL urlObj = new URL(url);
URLConnection conn = urlObj.openConnection();

String encoding = conn.getContentEncoding();
InputStream is = conn.getInputStream();
InputStreamReader isr = null;

if (encoding != null && encoding.equals("gzip")) {
    isr = new InputStreamReader(new GZIPInputStream(is));
} else {
    isr = new InputStreamReader(is);
}

reader = new BufferedReader(isr);

And so forth.

0
votes

Have you tested other enconding like BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));

You can check all the avaliable encondings on this web page enconding.doc