error can not be converted String to JSONObject android studio when trying to update

1

PHP PDO Code

   <?php
   require('conexion.php');

  $Code=$_GET['Code'];
  // Consulta de Usuarios en la base de  datos
    $consulta = "SELECT Code,
                        User,
                        Pass,
                        TipoUsuario
                         FROM tb_usuario
                         WHERE Code = ?";
      $comando=$conn->prepare($consulta);
      $comando->execute(array($Code));
      $row=$comando->fetch(PDO::FETCH_ASSOC);
      if($row)
      {
 $User=$_GET['User'];
 $Pass=$_GET['Pass'];
 $TipoUsuario=$_GET['TipoUsuario'];

// Creando consulta UPDATE
    $consulta = "UPDATE tb_usuario" .
        " SET User=?, Pass=?,TipoUsuario=? " .
        "WHERE Code=?";

    // Preparar la sentencia
    $cmd = $conn->prepare($consulta);

    // Relacionar y ejecutar la sentencia
    $cmd->execute(array($User,$Pass,$TipoUsuario,$Code));

    print json_encode(
        array(
            'estado' => '1',
            'mensaje' => 'Se actualizó  correctamente el  Usuario')
    );
}
else
{
 // Código de  error
     print json_encode(
        array(
            'estado' => '2',
            'mensaje' => 'No se actualizó  por que  no hay un Usuario  con este  código')
    );

}

 ?>

My Android Java code

public void ActualizarUser(final View view)
{
    showLoadingDialog("Actualizando.............");

    // obtener  los valores  actuales de  los controles
    final  String Code=et1.getText().toString();
    final  String User=et2.getText().toString();
    final  String Pass=et3.getText().toString();
    final  String TipoUsuario=tipUser.getSelectedItem().toString();

    String newURL = Config.URL_UPDATE_USER;
    HashMap<String, String> map = new HashMap<>();// Mapeo previo

    map.put(Config.KEY_USER_CODE, Code);
    map.put(Config.KEY_USER_USUARIO, User);
    map.put(Config.KEY_USER_PASS,Pass);
    map.put(Config.KEY_USER_TIPOUSER,TipoUsuario);

    // Crear nuevo objeto Json basado en el mapa
    JSONObject jobject = new JSONObject(map);

    // Depurando objeto Json...
    Log.d(TAG, jobject.toString());


    VolleySingleton.getInstance(this).addToRequestQueue(
            new JsonObjectRequest(
                    Request.Method.GET,
                    newURL,
                   jobject ,
                    new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject response) {

                            try {
                                String estado = response.getString("estado");

                                if(estado.equalsIgnoreCase("1")) {
                                    //Actualización  exitosa.
                                    //Procedemos a hacer las operaciones pertinentes
                                    hideLoadingDialog();
                                    Toast.makeText(getApplicationContext(),"Se actualizó el  Usuario  con éxito",Toast.LENGTH_SHORT).show();
                                }
                                else{
                                    // No  existe  registro con ese  código  para  actualizar
                                    hideLoadingDialog();

                                    Snackbar.make(view, "No se actualizó  por que no existe un registro con este  código", Snackbar.LENGTH_LONG)
                                            .setActionTextColor(getResources().getColor(R.color.vd))
                                            .setAction("Aceptar", new View.OnClickListener() {
                                                @Override
                                                public void onClick(View view) {
                                                }
                                            }).show();
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Log.d(TAG, "Error Volley: " + error.getMessage());
                            hideLoadingDialog();

                            Snackbar.make(view, "Por algún  otro motivo no se  pudo actualizar : " + error.getMessage(), Snackbar.LENGTH_LONG)
                                    .setActionTextColor(getResources().getColor(R.color.vd))
                                    .setAction("Aceptar", new View.OnClickListener() {
                                        @Override
                                        public void onClick(View view) {

                                        }
                                    }).show();
                        }
                    }

            ) {
                @Override
                public Map<String, String> getHeaders() {
                    Map<String, String> headers = new HashMap<String, String>();
                    headers.put("Content-Type", "application/json; charset=utf-8");
                    headers.put("Accept", "application/json");
                    return headers;
                }

                @Override
                public String getBodyContentType() {
                    return "application/json; charset=utf-8" + getParamsEncoding();
                }
            }
    );
}

This is the error that the Logcat shows me when trying to update

05-12 13:29:16.587 1532-1547/system_process V/WindowManager: not Base app: Adding window Window{daf92ed u0 com.example.aceraspire.fujitsu_mysql/com.example.aceraspire.fujitsu_mysql.buscarUpdateUser} at 5 of 11
 05-12 13:29:16.590 2964-2964/com.example.aceraspire.fujitsu_mysql D/buscarUpdateUser: {"User":"Mariana","Code":"AB67","TipoUsuario":"Invitado","Pass":"admin"}
  05-12 13:29:16.656 2964-3013/com.example.aceraspire.fujitsu_mysql D/OpenGLRenderer: endAllStagingAnimators on 0x7f7e9e0ff000 (RippleDrawable) with handle 0x7f7ea6951ae0
  05-12 13:29:16.966 2964-2964/com.example.aceraspire.fujitsu_mysql W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
  05-12 13:29:16.968 1763-1763/com.android.inputmethod.latin E/RichInputConnection: Unable to connect to the editor to retrieve text.
  05-12 13:29:16.968 1763-1763/com.android.inputmethod.latin D/RichInputConnection: Will try to retrieve text later.
  05-12 13:29:16.990 1154-1154/? W/SurfaceFlinger: couldn't log to binary event log: overflow.
   05-12 13:29:17.036 2964-2964/com.example.aceraspire.fujitsu_mysql D/buscarUpdateUser: Error Volley: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
   12 13:29:17.072 2964-2964/com.example.aceraspire.fujitsu_mysql W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
    05-12 13:29:17.072 1763-1763/com.android.inputmethod.latin E/RichInputConnection: Unable to connect to the editor to retrieve text.
    
asked by Sofia 12.05.2017 в 20:42
source

2 answers

0

The problem is that the answer does not have a .json format, it is getting an answer that even has html content, therefore it can not be converted to JSONObject :

> buscarUpdateUser: Error Volley: org.json.JSONException: Value <br of
> type java.lang.String cannot be converted to JSONObject

firstly it assures that when consulting your .php in fact it has an answer .json, it could even be an error the text that is obtained as answer and for that reason it can not be converted to JSONObject .

The problem is similar to the one in this question:

ERROR: org.json.JSONException: Value .... of type java.lang.String can not be converted to JSONArray

You have to analyze the answer, which you try to convert to JsonArray :

  JSONArray array = new JSONArray(response);

Review the answer and depending on that remember that the answer .Json can be of two types:

  
  • If the .json starts with {it is considered as Json object.

  •   
  • If the .json starts with [it is considered as Json Arrangement.

  •   

Because of the error apparently obtained, the response (response) is not really a JSONArray .

    
answered by 16.05.2017 в 01:25
0

This happened to me, and the error I had was that I was not sending the values in Java and Php in the same order as it is in the MySQL database.

In the console try to find the Logs to see where it tells you specifically in what line the error is.

Greetings

    
answered by 16.05.2017 в 01:53