简体   繁体   English

如何在 Android 中使用 JSON 从 MySQL 数据库中检索图像

[英]How to retrieve the images from a MySQL database using JSON in Android

I am get the JSON data from PHP.我从 PHP 获取 JSON 数据。 And pass to Android.并传递给Android。

Here is my PHP code:这是我的PHP代码:

<?php
   mysql_connect("localhost","root","MobixMySQL");
   mysql_select_db("cozydine");
   $q=mysql_query("SELECT itemimage from fooditem");
   while($obj=mysql_fetch_object($q)){
       $arr[]=$obj;
   }
   echo '{"names":'.json_encode($arr).'}';
   mysql_close();
?>

And here is how I read the image:这是我阅读图像的方式:

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();
    result = sb.toString();
    jArray = new JSONObject(result);
    JSONArray json = jArray.getJSONArray("names");
    for (int i = 0; i < json.length(); i++) {
        HashMap<String, String> map = new HashMap<String, String>();
        JSONObject e = json.getJSONObject(i);
        Qrimage=e.getString("itemimage");
        System.out.println(Qrimage);

        byte[] qrimage = Base64.decode(Qrimage.getBytes());

        System.out.println(qrimage);
        bmp = BitmapFactory.decodeByteArray(qrimage, 0,qrimage.length);
        ImageView imageview=(ImageView) findViewById(R.id.imageView1);
        imageview.setImageBitmap(bmp);

Here is how I parse the response from the PHP code:以下是我解析来自 PHP 代码的响应的方法:

codeInputStream is = null;
String result = "";
JSONObject jArray = null;
try {
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(serverurl+"showall.php");
    HttpResponse response = httpClient.execute(httpPost);
    HttpEntity entity = response.getEntity();
    is = entity.getContent();
} catch (Exception e) { }

In that way I can view only the last image on my Android mobile... I want display all images from the database into the Android mobile.这样我只能在我的 Android 手机上查看最后一张图片......我想将数据库中的所有图片显示到 Android 手机中。 How can I get all images using JSON data?如何使用 JSON 数据获取所有图像?

Low you've got quite a complex code there.低,你有一个相当复杂的代码。 However, I think your problem is very simple: you actually get all the images, but in those two lines:但是,我认为您的问题非常简单:您实际上获得了所有图像,但是在这两行中:

ImageView imageview=(ImageView) findViewById(R.id.imageView1);
imageview.setImageBitmap(bmp);

You overwrite the prevoius picture with the next one to come.你用下一张来覆盖上一张图片。 Thus only the last one is displayed eventually.因此最终只显示最后一个。 You can easily check that by changing the for cycle to:您可以通过将 for 循环更改为:

for (int i = 0; i < json.length() - 1; i++) {

Then the second to last image should be shown.然后应该显示倒数第二个图像。 If this really is the case you will need to make out a way to display all the images simultanously.如果确实是这种情况,您将需要找到一种同时显示所有图像的方法。

I just couldn't find any other problem in your code, but please if I got it wrong, write back so I can try to help more.我只是在您的代码中找不到任何其他问题,但是如果我弄错了,请回信,以便我可以尝试提供更多帮助。

EDIT As for how you can display the images together: you use image gallery.编辑至于如何一起显示图像:您使用图库。 The image gallery is just another type of android widget (like the image view).图片库只是另一种类型的 android 小部件(如图像视图)。

In your activity do the following few lines (initialize your gallery):在您的活动中执行以下几行(初始化您的画廊):

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();
    result = sb.toString();
    jArray = new JSONObject(result);
    JSONArray json = jArray.getJSONArray("names");
    Gallery g = (Gallery) findViewById(R.id.gallery);
    g.setAdapter(new ImageAdapter(this, json));

Here I use image gallery adapter which I define as follows:在这里,我使用了我定义如下的图片库适配器:

public class ImageAdapter extends BaseAdapter {

    private ImageView[] mImages;

    public ImageAdapter(Context context, JSONArray imageArrayJson) {
        this.mImages = new ImageView[imageArrayJson.length];
        String qrimage;

        for (int i = 0; i < imageArrayJson.length(); i++) {
            JSONObject image = imageArrayJson.getJSONObject(i);
            qrimage = image.getString("itemimage");

            byte[] qrimageBytes = Base64.decode(qrimage.getBytes());

            bmp = BitmapFactory.decodeByteArray(qrimageBytes,
                                                0,
                                                qrimageBytes.length);
            mImages[i] = new ImageView(context);
            mImages[i].setImageBitmap(bmp);
            mImages[i].setLayoutParams(new Gallery.LayoutParams(150, 100));
            mImages[i].setScaleType(ImageView.ScaleType.FIT_XY);
        }
    }

    public int getCount() {
        return mImages.length;
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        return mImages[position];
    }
}

And you need to declare this image gallery in the layout of your activity:并且您需要在您的活动布局中声明此图片库:

<Gallery xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/gallery"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
/>

Hopefully this all will help you, however, I have written it in text editor, without trying, so it might be that I made some error.希望这一切都会对您有所帮助,但是,我没有尝试就用文本编辑器编写了它,所以可能是我犯了一些错误。 If so please write back.如果是这样,请回信。

EDIT2 If you want to stack the images vertically just use ListView instead of the gallery. EDIT2如果您想垂直堆叠图像,只需使用ListView而不是画廊。 You will still need to set the adapter, but you can use the same one I already provided you with.您仍然需要设置适配器,但您可以使用我已经提供给您的同一个适配器。 However, keep in mind that the ListView will not necessarily show the images one by one.但是,请记住, ListView不一定会一张一张地显示图像。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM