我正在创建一个包含图片库的Android应用程序。但是我在尝试从我的数据库中获取图像时遇到了困难。我保存了我的图像的路径,并试图将其保存到json然后解析它到我的机器人。 这是我的代码:
photo.php
photo.php
<?php
define('HOST','');
define('USER','');
define('PASS','');
define('DB','');
$con = mysqli_connect(HOST,USER,PASS,DB);
// query the application data
$sql = "SELECT image FROM photos";
$result = mysqli_query($con, $sql);
// an array to save the application data
$rows = array();
// iterate to query result and add every rows into array
while($row = mysqli_fetch_array($result)) {
$rows[]=$row;
}
// close the database connection
mysqli_close($con);
// echo the application data in json format
echo json_encode($rows);
?>
FetchImage.java
public class FetchImage extends Activity {
Button load_img;
ImageView img;
Bitmap bitmap;
ProgressDialog pDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fecth_image);
load_img = (Button)findViewById(R.id.load);
img = (ImageView)findViewById(R.id.img);
load_img.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new LoadImage().execute("http://iguideph-001-site1.btempurl.com/PhotoUpload/uploads/vigan1.jpg");
}
});
}
private class LoadImage extends AsyncTask<String, String, Bitmap> {
@Override
protected void onPreExecute() {
super.onPreExecute();
//pDialog = new ProgressDialog(FetchImage.this);
// pDialog.setMessage("Loading Image ....");
// pDialog.show();
}
protected Bitmap doInBackground(String... args) {
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if(image != null){
img.setImageBitmap(image);
pDialog.dismiss();
}else{
pDialog.dismiss();
Toast.makeText(FetchImage.this, "Image Does Not exist or Network Error", Toast.LENGTH_SHORT).show();
}
}
}
}
activity_fetch_image.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:id="@+id/load"
android:text="Load Image" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:id="@+id/img"/>
</LinearLayout>