0

Hola estoy intentando insertar 2 registros en una bbdd y la verdad me sale un error que no llego a entender ya que soy un poco principiante en esto , agradecería que alguien me pudiese echar un cable indicándome si algo de mi código pudiera estar mal.

public class JSONparser {
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    public JSONparser() {
    }

    public JSONObject makeHttpRequest(String url, String method,
                                      List<NameValuePair> params) {

        try {

            if(method == "POST"){

                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }else if(method == "GET"){
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        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();
            json = sb.toString();
        }
        catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }







class CrearAviso extends AsyncTask<String,String,String> {

        String url_crear_control = "http://192.168.2.19/android/control/insert.php";
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dialogo = new ProgressDialog(Main2Activity.this);
            dialogo.setMessage("Creating Product..");
            dialogo.setIndeterminate(false);
            dialogo.setCancelable(true);
            dialogo.show();

        }

        @Override
        protected String doInBackground(String... strings) {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            String position=posicion.getText().toString();
            String acidente="accidente";
            String control="control";
            String radar="radar";

            if (radio.getCheckedRadioButtonId()== R.id.radioButton_accidente){
                params.add(new BasicNameValuePair("imagen",acidente));
            }else if(radio.getCheckedRadioButtonId()== R.id.radioButton_control){
                params.add(new BasicNameValuePair("imagen",control));
            }else if(radio.getCheckedRadioButtonId()== R.id.radioButton_radar){
                params.add(new BasicNameValuePair("imagen",radar));
            }

            params.add(new BasicNameValuePair("posicion", position));

            JSONObject json = jsonParser.makeHttpRequest(url_crear_control,
                    "POST", params);
            Log.d("Create Response", json.toString());

            try {
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // successfully created product
                    Intent i = new Intent(getApplicationContext(), MainActivity.class);
                    startActivity(i);

                    // closing this screen
                    finish();
                } else {
                    // failed to create product
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }


        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
        }

    }

Error:

Value null of type org.json.JSONObject$1 cannot be converted to JSONObject

3
  • 1
    puedes decir dónde te da el fallo? el 25 abr. 2018 a las 11:46
  • Puedes imprimir lo que obtienes aquí: json = sb.toString(); en realidad no es un objeto json, ese es el problema. @adrianruizpicazo
    – Jorgesys
    el 25 abr. 2018 a las 14:10
  • hola, me indica que el error esta en el asyntask el 2 may. 2018 a las 12:14

1 respuesta 1

-1

Adrian, el mensaje de error especifica el problema:

Value null of type org.json.JSONObject$1 cannot be converted to JSONObject

El valor que obtienes en la petición y deseas convertir a JSONObject no es un objeto json.

El valor de la variable json no es Objeto JSON.

  public JSONObject makeHttpRequest(String url, String method,
                                      List<NameValuePair> params) {
        ...
        ...
        ...
        try {
            jObj = new JSONObject(json); //*El valor de json no es Objeto JSON.
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }

Recuerda que si el .json inicia con { se considera como objeto Json, asegura que la respuesta sea un objeto JSON.

1
  • CP Cuando se califique con -1, es bueno para el sitio se indique la razón, esto para mejorar la pregunta, eliminarla o si existen argumentos platicar sobre el tema.
    – Jorgesys
    el 25 abr. 2018 a las 15:22

Tu Respuesta

Al pulsar en “Publica tu respuesta”, muestras tu consentimiento a nuestros términos de servicio, política de privacidad y política de cookies

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.