Error showing an image with JSON on Android

2

How about, I'm trying to show images in a ImageView from a database on Android.

It shows me the following:

org.json.JSONException: Value <html><body><script of type java.lang.String cannot be converted to JSONObject

Code

import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class ShowImage extends AppCompatActivity implements View.OnClickListener {
    private String imagesJSON;

    private static final String JSON_ARRAY ="result";
    private static final String IMAGE_URL = "url";

    private JSONArray arrayImages= null;

    private int TRACK = 0;

    private static final String IMAGES_URL = "http://misitio.com/showimage.php";

    private Button buttonFetchImages;
    private Button buttonMoveNext;
    private Button buttonMovePrevious;
    private ImageView imageView;
    private String TAG="ShowImage";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_image);

        imageView = (ImageView) findViewById(R.id.imageView);
        buttonFetchImages = (Button) findViewById(R.id.buttonFetchImages);
        buttonMoveNext = (Button) findViewById(R.id.buttonNext);
        buttonMovePrevious = (Button) findViewById(R.id.buttonPrev);
        buttonFetchImages.setOnClickListener(this);
        buttonMoveNext.setOnClickListener(this);
        buttonMovePrevious.setOnClickListener(this);
    }


    private void extractJSON(){
        try {
              //Aquí marca el error
            JSONObject jsonObject = new JSONObject(imagesJSON);
            arrayImages = jsonObject.getJSONArray(JSON_ARRAY);
            Log.e(TAG,"====:  "+arrayImages);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void showImage(){
        try {
            JSONObject jsonObject = arrayImages.getJSONObject(TRACK);
            getImage(jsonObject.getString(IMAGE_URL));
        } catch (JSONException e) {
            e.printStackTrace();

        }
    }

    private void moveNext(){
        if(TRACK < arrayImages.length()){
            TRACK++;
            showImage();
        }
    }

    private void movePrevious(){
        if(TRACK>0){
            TRACK--;
            showImage();
        }
    }



    private void getAllImages() {
        class GetAllImages extends AsyncTask<String,Void,String>{
            ProgressDialog loading;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                loading = ProgressDialog.show(ShowImage.this, "Fetching Data...","Please Wait...",true,true);
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                loading.dismiss();
                imagesJSON = s;
                extractJSON();
                showImage();
            }

            @Override
            protected String doInBackground(String... params) {
                String uri = params[0];
                BufferedReader bufferedReader = null;
                try {
                    URL url = new URL(uri);
                    HttpURLConnection con = (HttpURLConnection) url.openConnection();
                    StringBuilder sb = new StringBuilder();

                    bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));

                    String json;
                    while((json = bufferedReader.readLine())!= null){
                        sb.append(json+"\n");
                    }

                    return sb.toString().trim();

                }catch(Exception e){
                    return null;
                }
            }
        }
        GetAllImages gai = new GetAllImages();
        gai.execute(IMAGES_URL);
    }

    private void getImage(String urlToImage){
        class GetImage extends AsyncTask<String,Void,Bitmap>{
            ProgressDialog loading;
            @Override
            protected Bitmap doInBackground(String... params) {
                URL url = null;
                Bitmap image = null;

                String urlToImage = params[0];
                try {
                    url = new URL(urlToImage);
                    image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return image;
            }

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                loading = ProgressDialog.show(ShowImage.this,"cargando imagen...","Espere...",true,true);
            }

            @Override
            protected void onPostExecute(Bitmap bitmap) {
                super.onPostExecute(bitmap);
                loading.dismiss();
                imageView.setImageBitmap(bitmap);
            }
        }
        GetImage gi = new GetImage();
        gi.execute(urlToImage);
    }

    @Override
    public void onClick(View v) {
        if(v == buttonFetchImages) {
            getAllImages();
        }
        if(v == buttonMoveNext){
            moveNext();
        }
        if(v== buttonMovePrevious){
            movePrevious();
        }
    }
}

Apparently he is not receiving in the format he should and he points out the error in the part where he extracts it:

 JSONObject jsonObject = new JSONObject(imagesJSON);

Another fact is that maybe it is wrong in the part where I set the JSON , at other times I had this error but it was due to extra spaces in the query and things like that. :

showimage.php

    <?php
 define('HOST','misitio.com');
 define('USER','usuario');
 define('PASS','pass');
 define('DB','test');

 $con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');

 $sql = "select id from imagenes";

 $res = mysqli_query($con,$sql);


 $result = array();

 $url = "http://misitio.com/showimage.php?id=";
 while($row = mysqli_fetch_array($res)){
 array_push($result,array('url'=>$url.$row['id']));
 }

 echo json_encode(array("result"=>$result));

 mysqli_close($con);


?> 

This shows me the following, I see very suspicious the \/ :

{"result":[{"url":"http:\/\/misitio.com\/showimage.php?id=1"},{"url":"http:\/\/misitio.comr\/showimage.php?id=2"},{"url":"http:\/\/misitio.com\/showimage.php?id=3"}]}

Thanks

    
asked by x4mp73r 10.05.2016 в 19:05
source

1 answer

1

If you are receiving this error:

> org.json.JSONException: Value <html><body><script of type
> java.lang.String cannot be converted to JSONObject

It means that you try to create an object from an html entity, which is incorrect, as you mention it, it is not receiving the correct .json format.

Ensure you receive the correct .json format.

Regarding the \/ you should not worry, they are not a problem, it is a way of coding or "escaping" special characters:

link

    
answered by 10.05.2016 в 19:44