Que tal, estoy tratando de mostrar imágenes en un ImageView desde una base de datos mysql en Android.
Me muestra lo siguiente:
org.json.JSONException: Value <html><body><script of type java.lang.String cannot be converted to JSONObject
Código
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();
}
}
}
Al parecer no está recibiendo en lel formato que debe y me señala el error en la parte en la que lo extrae:
JSONObject jsonObject = new JSONObject(imagesJSON);
Otro dato es que quizá esté mal en la parte donde armo el JSON, en otras ocasiones he tenido este error pero era debido a espacios extras en la consulta y cosas así. :
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);
?>
Eso me muestra lo siguiente:
{"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"}]}
Si alguien fuera tan amable de indicarme cual sería la posible causa de este error le estaría muy agradecido.