我想从MySQL数据库下载图像并在Android ImageView
中显示图像,但它没有显示。下面我已经包含了我的java文件和php文件的代码。没有错误,但在我的logcat中我得到工厂返回null。我无法找到我错的地方。提前致谢。
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Created by GIOVANI on 10/19/2016.
*/
public class GetAllImages {
public static String[] imageURLs;
public static Bitmap[] bitmaps;
public static final String JSON_ARRAY="result";
public static final String IMAGE_URL = "url";
private String json;
private JSONArray urls;
public GetAllImages(String json){
this.json = json;
try {
JSONObject jsonObject = new JSONObject(json);
urls = jsonObject.getJSONArray(JSON_ARRAY);
} catch (JSONException e) {
e.printStackTrace();
}
}
private Bitmap getImage(JSONObject jo){
URL url = null;
Bitmap image = null;
try {
url = new URL(jo.getString(IMAGE_URL));
image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return image;
}
public void getAllImages() throws JSONException {
bitmaps = new Bitmap[urls.length()];
imageURLs = new String[urls.length()];
for(int i=0;i<urls.length();i++){
imageURLs[i] = urls.getJSONObject(i).getString(IMAGE_URL);
JSONObject jsonObject = urls.getJSONObject(i);
bitmaps[i]=getImage(jsonObject);
}
}
}
这是我的PHP代码:
<?php
//Importing database
require_once('dbConnect.php');
$sql = "SELECT * FROM foto ";
//result
$r = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($r)){
array_push($result,array( "id"=>$row['id'],
"image"=>$row['image'],
"judul"=>$row['judul']
));
}
//Tampilkan dalam format json
echo json_encode(array('result'=>$result));
mysqli_close($con);
?>
答案 0 :(得分:1)
用于从服务器加载图像。 您可以使用任何图像加载API。喜欢 Glide或Picasso或Universal Image Loader。
Google建议使用Glide。 source
您可以轻松集成并避免一些内存和缓慢加载问题。
就像:
Picasso.with(this)
.load("http://nuuneoi.com/uploads/source/playstore/cover.jpg")
.fit()
.centerCrop()
.into(ivImgPicasso);
所以尽情享受吧。
Happy Coading。