0

I am getting the following error on logcat when I run my application. I had many errors before which I have managed to resolve after doing some research. However, this one I am unable to figure out:

03-04 02:52:29.475: E/JustDealsUtils(1913): Error parsing to json on getJarrayFromString(); org.json.JSONException: Expected ':' after result at character 8 of {result}

EDIT 1:

The error now is:

Error parsing to json on getJarrayFromString(); org.json.JSONException: Value result of type java.lang.String cannot be converted to JSONArray

Also linked to this is error for fillproductlist()

Here is my Java Code for this:

public void onTaskCompleted(String result) {
                        try {  
                            if(result!=""){
                                // the remote php link 
                                // converting the response into json array
                                Log.i(DEBUG, result);
                                jarray = utils.getJarrayFromString(result);

                                // number of rows in total for a query
                                int mysqlSize = (jarray.getJSONObject(0).getInt("numRows"));

                                Log.i(DEBUG, "From " + from + " to " + mysqlSize);

                                // to check if all the rows are parsed from the mysql
                                if(from <= mysqlSize){
                                    int rows;
                                    // to check if there is 0
                                    if(jarray.length()>0){
                                        Log.i(DEBUG, "From " + from + " to " + Math.floor(mysqlSize/nr)*nr);
                                        if(from+5<=Math.floor(mysqlSize/nr)*nr){
                                            rows = jarray.length();
                                        }else{
                                            rows = mysqlSize%nr+1;
                                            Utils.IS_ENDED_PRODUCT_LIST = true;
                                        }
                                        ArrayList<String> list = new ArrayList<String>();
                                        for(int i=1; i<rows; i++){
                                            JSONObject row = jarray.getJSONObject(i);
                                            bid.add(row.getInt("bid"));
                                            bTitle.add(row.getString("bTitle"));
                                            bCode.add(row.getString("bCode"));
                                            bPrice.add(row.getString("bPrice") + "£");
                                            bDescription.add(row.getString("bDescription"));
                                            bModule.add(row.getString("bModule"));
                                            bImage.add(Utils.PATH + row.getString("bImage"));
                                            list.add(row.getString("bImage"));
                                            // to check if an id already exists in the db or to create one if doesn't exist
                                            if(!db.hasIDBooks(row.getInt("bid"))) db.createRowOnBooks(row.getInt("bid"), row.getString("bTitle"), row.getString("bCode"), row.getString("bPrice"), row.getString("bDescription"), row.getString("bModule"), Utils.PATH + row.getString("bImage"), row.getString("bSpecialOffer"), row.getInt("bSpecialDiscount"), row.getString("bDateAdded"));
                                            Log.i(DEBUG, row.getString("bDescription"));
                                        }
                                        new DownloadImages(list, bAdapter).execute();
                                    }
                                }
                                postParameters.removeAll(postParameters);
                            }else{
                                Utils.IS_ENDED_PRODUCT_LIST = true;
                                if(rlLoading.isShown()){
                                    rlLoading.startAnimation(fadeOut());
                                    rlLoading.setVisibility(View.INVISIBLE);
                                }
                            }
                        } catch (Exception e) {  
                            Log.e(DEBUG, "Error at fillProductList(): " + e.toString());  
                        }
                    }
                });
                task.execute();

        }else{
            // if internet connectio is not available
            // then, rows will be fetched from the local sqllite database stored on the android phone
            if(db.size(justdealsDatabase.TABLE_BOOKS) > 0){
                Cursor cursor = db.getBooksRows(justdealsDatabase.TABLE_BOOKS);
                cursor.moveToFirst();
                while(!cursor.isAfterLast()){
                    bid.add(cursor.getInt(cursor.getColumnIndex(justdealsDatabase.KEY_BID)));
                    bTitle.add(cursor.getString(cursor.getColumnIndex(justdealsDatabase.KEY_BTITLE)));
                    bCode.add(cursor.getString(cursor.getColumnIndex(justdealsDatabase.KEY_BCODE)));
                    bPrice.add(cursor.getString(cursor.getColumnIndex(justdealsDatabase.KEY_BPRICE))+ "£");
                    bDescription.add(cursor.getString(cursor.getColumnIndex(justdealsDatabase.KEY_BDESCRIPTION)));
                    bModule.add(cursor.getString(cursor.getColumnIndex(justdealsDatabase.KEY_BMODULE)));
                    bImage.add(cursor.getString(cursor.getColumnIndex(justdealsDatabase.KEY_BIMAGE)));
                    cursor.moveToNext();
                }
                bAdapter.notifyDataSetChanged();
                Utils.IS_ENDED_PRODUCT_LIST = true;
            }
        }
    }

MY JSON ARRAY CODE ( FULL EDIT 2):

public String getJsonFromUrl(String url){

        // to initialise the objects
        InputStream is = null;
        String result = "";

        //making HTTP POST request
        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
        }catch(Exception e){
            Log.e(DEBUG, "Error getJsonFromUrl: " + e.toString());
        }

        // Converting to String
        try{
            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"), 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(DEBUG, "Error converting the response to string getJsonFromUrl: " + e.toString());
        }

        return result;
    }

    /**
     * To convert the string recieved into json object
     * result refers to the string that will be converted
     * @return will return the json array
     */
    public JSONArray getJarrayFromString(String result){
        // Parsing string to JSON Array
        try{
            jarray = new JSONArray("result");
        }catch(JSONException e){
            Log.e(DEBUG, "Error parsing to json on getJarrayFromString(); " + e.toString());
        }

        return jarray;
    }

And My PHP API (EDIT 1):

    <?php
    include("MysqlConnection.php");
    header('Content-Type: application/json');
    $from = $_POST["from"];
    $nr = $_POST["nr"];
    // those variables are for search
    $title = $_POST["title"];
    $code = $_POST["code"];
    $price = $_POST["price"];
    $module = $_POST["module"];
    $order = $_POST["order"];
    $by = $_POST["by"];


    $sql = "SET CHARACTER SET utf8";
    $db->query($sql);


        // if those 2 var are set then we order the query after them
        if(isset($order) && isset($by)){
            $sql .= " ORDER BY `$order` $by LIMIT $from, $nr";
        }else{
            $sql .= "LIMIT $from, $nr";
        }

        $query = $db->query($sql);
        $rows = array();
        $rows[] = array("numRows"=>$db->numRows($query));

        if($db->numRows($query)!=0){
            while($row = mysql_fetch_assoc($query)) {
                $rows[] =  $row;
            }
            echo(json_encode($rows));
        }
    }

    $db->closeConnection();
?>

I have implemented all the suggestions recommended by you guys, still there is no luck in getting this code work!!!!

I AM NOT SURE WHY VALUE OF 'RESULT' STRING CANNOT BE CONVERTED INTO JSONARRAY????

I have shown you the JSON ARRAY Declaration, RESULT STRING DECLARATION as well as PHP (See Above for edited versions)

5
  • {result}.length == 8, that's whay you get error in character 8. Should be jarray = new JSONArray(result); Commented Mar 4, 2013 at 11:46
  • @user1516873 If I do that. I get 20 more errors and application ends unexpectedly!! Commented Mar 4, 2013 at 22:47
  • Oh, it just mean you have a lot of bugs in your code. For example, echo json_encode($rows); in top of php file. What exactly this line do? I think it shouldn't be here. Commented Mar 5, 2013 at 6:39
  • I have deleted that already and it still doesn't work Commented Mar 5, 2013 at 11:51
  • OK, next thing - why you run query 2 times? Remove first select and move array definition below second $query = $db->query($sql); and $sql .= "LIMIT $from, $nr"; will throw SQL exception, should be $sql .= " LIMIT $from, $nr"; Next: print_r(json_encode($rows)); should be echo json_encode($rows); Commented Mar 5, 2013 at 12:12

3 Answers 3

1

you have to use echo not print_r

echo json_encode($rows);

print_r gives output in array format.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks @Yogesh Suthar But that didn't help. It still gives me the same error in LogCat. Expected ':' after result at character 8 of {result}
@TirathSingh you have to remove echo json_encode($rows); after header()...
My JSON output is 'null' if I test my php API in my web browser. And I am using echo instead print_r and also above steps have been followed but still NO LUCK!! same error!!
@TirathSingh you have to remove echo json_encode($rows); after header()... after that check your json output.
0

You have send the result two times you have to send the result only one time with encoded remove the following code and try

echo json_encode($rows);

5 Comments

@ Thirumalai murugan I have removed that already.. I pasted the wrong version of code above. In my working code, it is already removed after the header.. Still No Luck!!!
@Tirath Singh Can you give new version code so that we can check and try instead of the print_r use echo
The whole code is fine it's just I took off echo statement after header statement and print_r is changed to echo. That's all
I hope you are familiar with firebug, please look the ajax return and then check, give us the return text to check
and you try this too jarray = new JSONArray(result);
0

Maybe you should name your array without "{}" symbols?

jarray = new JSONArray("result");

instead of

jarray = new JSONArray("{result}");

1 Comment

Thanks @Andrey. Tried that. Error remains there. However this time error is slighlty different: Error parsing to json on getJarrayFromString(); org.json.JSONException: Value result of type java.lang.String cannot be converted to JSONArray

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.