0

In my Android app, I'm trying to communicate with a web server that holds randomly-generated fake usernames and scores.

{ scores: [
 {
un: "Feltricapulta",
sc: "143"
},
{
un: "Henroid",
sc: "120"
},
{
un: "ieteubmospta",
sc: "70"
},
{
un: "pmbotesteuai",
sc: "67"
},
{
un: "epesomiubtat",
sc: "65"
}
] }

The code in the PHP file looks like this:

<?php 

    include ('connecttomysql.php');


    $command = 'SELECT un, sc FROM xmlscores ORDER BY sc DESC';
    $execute_command = mysql_query($command);

        echo '{ "scores": ';

    while ($table_row = mysql_fetch_assoc($execute_command))
        {
            $jsonArray [] = $table_row;         
        }
        echo json_encode($jsonArray);

        echo '}'

    ?>

I've called this .php URL in Android using the generic HttpGet method. The output of the json data prints to the stacktrace and provides me with the "Cannot convert from Object to Array" error.

Looking at the PHP file and the json output, is there anything noticeably wrong with my codes or the output? I can't figure it out.

1
  • 1
    What's your Android code? You probably have a .getJSONArray() where you need a .getJSONObject(). Commented May 7, 2013 at 8:44

2 Answers 2

3

"Cannot convert from Object to Array"

means you are trying to convert response string to JSONArray. but Current String Contains JSONObject as root element instead of JSONArray. so convert it to JSONObject as:

JSONObject json=new JSONObject(<Server response string here>);

//  get scores JSONArray from json
JSONArray jsonscoresarray=json.getJSONArray("scores");
...
Sign up to request clarification or add additional context in comments.

1 Comment

That was exactly the issue xD I was passing the Entity response String into a new jsonArray. Thanks so much.
0

// Implementation of Json array should go like this.

 @Override
    public void fromJSON(Object json) throws JSONException {
        JSONObject jsonObject = new JSONObject((String) json);

        JSONArray jsonArray = jsonObject.getJSONArray("scores");
        mScores = new ArrayList<Score>();
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObjct = (JSONObject)jsonArray.getJSONObject(i);
            Score object = new Score();
            object.fromJSON(jsonObjct);
            mScores.add(object);
            }
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.