Reverb
Reverb

Reputation: 53

Android: BufferedReader returns wrong data after second time

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();
    }

Upvotes: 0

Views: 396

Answers (2)

ZimZim
ZimZim

Reputation: 3381

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.

Upvotes: 1

esoyitaque
esoyitaque

Reputation: 61

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

Upvotes: 0

Related Questions