-1

I'm getting the following error on my android logcat when I try to login.

1492-1639/net.azurewebsites.cosy W/System.err﹕ org.json.JSONException: Value The of type java.lang.String cannot be converted to JSONObject

I'm definitely getting requests to my server so I don't know if it's the value it's returning or is it a problem in the app and it can't convert it.

my php is the following:

if( $conn ) {
    $username = $_POST["username"];
    $password = $_POST["password"];
    //echo($username);
    // echo "Connection established.<br />";
    $query = sprintf("SELECT * from Users where username = ? and password = ?");
    $params1 = array( $username, $password);
    $stmt = sqlsrv_query($conn, $query, $params1);
    if ($stmt === false) {
        die(print_r(sqlsrv_errors(), true));
    }
    $Users = array();
    while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
        $username1 = $row['username'];
        $password1= $row['password'];
    }
    $Users["username"] = $username1;
    $Users["password"] = $password1;
    echo json_encode($Users);
    sqlsrv_free_stmt($stmt);
    sqlsrv_close( $conn );
} else {
    echo "Connection could not be established.<br />";
    die( print_r( sqlsrv_errors(), true));
}

And my request consists of the following:

public class ServerRequests {
    ProgressDialog progressDialog;
    public static final int CONNECTION_TIMEOUT = 1000 * 15;
    public static final String SERVER_ADDRESS = "http://cosy.azurewebsites.net/";

    public ServerRequests(Context context) {
        progressDialog = new ProgressDialog(context);
        progressDialog.setCancelable(false);
        progressDialog.setTitle("Processing...");
        progressDialog.setMessage("Please wait...");
    }

    public void fetchUserDataAsyncTask(User user, GetUserCallback userCallBack) {
        progressDialog.show();
        new fetchUserDataAsyncTask(user, userCallBack).execute();
    }

    public class fetchUserDataAsyncTask extends AsyncTask<Void, Void, User> {
        User user;
        GetUserCallback userCallBack;

        public fetchUserDataAsyncTask(User user, GetUserCallback userCallBack) {
            this.user = user;
            this.userCallBack = userCallBack;
        }

        @Override
        protected User doInBackground(Void... params) {
            ArrayList<NameValuePair> dataToSend = new ArrayList<>();
            dataToSend.add(new BasicNameValuePair("username", user.username));
            dataToSend.add(new BasicNameValuePair("password", user.password));

            HttpParams httpRequestParams = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
            HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);

            HttpClient client = new DefaultHttpClient(httpRequestParams);
            HttpPost post = new HttpPost(SERVER_ADDRESS + "FetchUserData.php");

            User returnedUser = null;

            try {
                post.setEntity(new UrlEncodedFormEntity(dataToSend));
                HttpResponse httpResponse = client.execute(post);

                HttpEntity entity = httpResponse.getEntity();
                String result = EntityUtils.toString(entity);
                JSONObject jObject = new JSONObject(result);

                if (jObject.length() != 0) {
                    Log.v("happened", "2");
                    returnedUser = new User(user.username, user.password);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

            return returnedUser;
        }

        @Override
        protected void onPostExecute(User returnedUser) {
            super.onPostExecute(returnedUser);
            progressDialog.dismiss();
            userCallBack.done(returnedUser);
        }
    }
}

I have spent forever on this and I just can't find out where I am going wrong any help at all would be appreciated!!

Peter Pan
  • 23,476
  • 4
  • 25
  • 43
Eoin Ó Cribín
  • 155
  • 1
  • 3
  • 14

1 Answers1

1

It seems to be that the PHP response string contains some special characters or messy codes. So the org.json library in Java can not convert the response string to a JSONObject.

You can try to use the functions urlencode & urldecode in PHP to deal with the string. Please see the codes below.

Modify the codes below.

while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
    $username1 = urlencode($row['username']);
    $password1= urlencode($row['password']);
}

And

echo urldecode(json_encode($Users));

Hope it helps. Any concern, please feel free to let me know.

Peter Pan
  • 23,476
  • 4
  • 25
  • 43
  • Thought that would work since I've been having a few problems with azure needing extra stuff like that but it still seems to give off the same error. No idea the cause of it but thanks for the suggestion really appreciate it!! – Eoin Ó Cribín Jan 27 '16 at 20:03
  • @EoinÓCribín The idea for analysing the issue is that check the response body whether it contains some Unicode characters like `\uffef`. You can try to download it as a txt file and use Hexedit to review the byte codes one by one, then debug your code via change some codes. – Peter Pan Jan 28 '16 at 02:52
  • Fixed it you were right in the end it was just me forgetting to add someting! Thanks so much for your help! – Eoin Ó Cribín Jan 29 '16 at 11:41