Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I want to receive from an MySQL-Server all my data from a table. So, I wrote a PHP script that fetches the complete table and encode it to JSON format.

PHP-Code:

<?php
include ("connect.php"); 

mysql_query("SET NAMES 'utf8'");

$query = mysql_query('SELECT * FROM MyTable);

while ($row = mysql_fetch_assoc($query))
{
$buffer[] = $row;
}

print json_encode( $buffer );
mysql_close($dbconnect);
?>

So, when I run the script, all the JSON String looks fine, no corupted characters etc.

In Android App:

When I run the following codes and receive the JSON String throught the HTTP, I get a strange String in the Debugger...

Screenshot: http://goo.gl/gTssQ

Java Code:

String result = "";
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

        // HTTP Verbindung
        try
        {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://mywebsite.com");
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
        }
        catch(Exception e)
        {
            Log.e("log_tag", "Fehler bei der http Verbindung "+e.toString());
        }



        try
        {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),8);
            StringBuilder sb = new StringBuilder();
            String line = null;

        while ((line = reader.readLine()) != null) 
        {
            sb.append(line + "\n");
        }

            is.close();
            result=sb.toString();

        }
        catch(Exception e)
        {
            Log.e("log_tag", "Error converting result "+e.toString());
        }



        try
        {
            JSONArray jArray = new JSONArray(result);

            for(int i=0;i<jArray.length();i++)
            {
                json_data = jArray.getJSONObject(i);


                    );
            }
        }
        catch(JSONException e)
        {
            Log.e("log_tag", "Error parsing data "+e.toString());
        }

I cant understand the Problem, because my Database is full UTF-8 and my script too. I hope someone can help me! :-) Greets, andr3w

share|improve this question
 
What is strange with that, looks like JSON to me?! What is the error you get. Pleas post your error message. –  Knickedi Oct 9 '11 at 17:57
 
You're missing a ' in this line: $query = mysql_query('SELECT * FROM MyTable);. Strange if it is a typo (you didn't cut/paste the code?) but even stranger if it isn't :) –  Nanne Oct 9 '11 at 18:03
 
Hi! Sorry, yes I forget during copy/paste the ' –  andr3w Oct 9 '11 at 18:57
add comment

1 Answer

every entry of your json array is an jsonobject. So

 try
    {
        JSONArray jArray = new JSONArray(result);

        for(int i=0;i<jArray.length();i++)
        {
            json_data = jArray.getJSONObject(i);
            articleId = json_data.optInt("ID");
            title = json_data.optString("NAME");


        }
    }
    catch(JSONException e)
    {
        Log.e("log_tag", "Error parsing data "+e.toString());
    }

and you do this for every entry of your json object. Please refer to documentation

JSONObject

Edit: I use the following method to convert the inputstream into the json string:

int len = 32768; byte[] buffer = new buffer[len];

    public static String copyInStringBuilder(InputStream is) throws IOException {
    int read = 0;
    StringBuilder s = new StringBuilder();
    while ( (read = is.read(buffer, 0, len)) >= 0) {
        s.append(new String(buffer, 0, read));
    }

    return s.toString();
}

I can not really understand why you append a "\n" after every line you read.

share|improve this answer
 
Yes, thats true, but I can't even convert the String to a JSONArray. I tested my code with a other JSON PHP File with other entrys and there was no error, only with this code and I dont know why. The program reaches only the line "JSONArray jArray = new JSONArray(result);" and then it aborts in the for and catches this error: Here is the error code from LogCat: Error parsing data org.json.JSONException: Value of type java.lang.String cannot be converted to JSONArray. I hope you understand my problem! :-) –  andr3w Oct 9 '11 at 19:01
 
Hi! It's a bit strange, I got a simple JSONArray and when I set a breakpoint in the function for the JSON data, my program dont get in the for() and it goes directly in the catch() function. But the "result" var containts the right JSON String. –  andr3w Oct 11 '11 at 9:54
 
my best guess? The error is how you read the InputStream in order to "create" the String result you pass to the JSONArray jArray = new JSONArray(result);. Just for the purpose of trying use the method copyInStringBuilder() that I ve added in the post edit and report me some feedback –  blackbelt Oct 11 '11 at 10:25
 
Hi! Thanks for reply! I check your functin "copyInStringBuilder", but how do you use the "buffer" var? –  andr3w Oct 11 '11 at 19:21
 
See my edit ...... –  blackbelt Oct 11 '11 at 20:27
show 1 more comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.