从 MySQL 获取 URL 图像并显示在 android listView (setImageURI)

Get URL image from MySQL and display on android listView (setImageURI)

我是 Android 和 PHP 的新手。我已成功将图像 URIAndroid 上传到 MySQL,但现在很难取回图像 URI 并显示在 listView Activity A 上。任何帮助将不胜感激。非常感谢。

MySQL

发送至MySQL:

我正在将图像 uri 发送到服务器,并将图像路径存储到 MySQL,图像保存在 PhotoUpload 文件夹中。

@Override
protected String doInBackground(String... params) {
    for (int index = 0; index < jsonArray.length(); index++) {
        try {
            JSONObject jsonObject = jsonArray.getJSONObject(index);
            String strUri = jsonObject.getString("image");
            HashMap<String, String> data = new HashMap<String, String>();
            data.put(Configs.KEY_IMAGE, getStringImage(Uri.parse(strUri)));
            RequestHandler rh = new RequestHandler();
            String result = rh.sendPostRequest(Configs.SEND, data);
            return result;
        } catch (Exception e) {
        }
    }
    return "";
}

@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);
    loading.dismiss();
    Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
}

public String getStringImage(Uri imgUri) {
    try {
        Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imgUri);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] imageBytes = baos.toByteArray();
        String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
        return encodedImage;
    } catch (Exception e) {
    }

    return "";
}

现在我想从MySQL中获取url并将图像显示到listView中,但是图像无法检索出来,只能检索String。

从服务器检索:

      public void BuildEditStaffList(final String id) {
            class GetDataJSON extends AsyncTask<String, Void, String> {

                @Override
                protected String doInBackground(String... params) {
                    DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
                    HttpPost httppost = new HttpPost("http://192.168.107.115/Android/CRUD/staffRetrieve.php?id=" + id);


                    // Depends on your web service
                    httppost.setHeader("Content-type", "application/json");

                    InputStream inputStream = null;
                    String result = null;
                    try {
                        HttpResponse response = httpclient.execute(httppost);
                        HttpEntity entity = response.getEntity();

                        inputStream = entity.getContent();
                        // json is UTF-8 by default
                        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
                        StringBuilder sb = new StringBuilder();

                        String line = null;
                        while ((line = reader.readLine()) != null) {
                            sb.append(line + "\n");
                        }
                        result = sb.toString();
                    } catch (Exception e) {
                        // Oops
                    } finally {
                        try {
                            if (inputStream != null) inputStream.close();
                        } catch (Exception squish) {
                        }
                    }
                    return result;
                }

                @Override
                protected void onPostExecute(String result) {
                    myJSON = result;
                    showList();
                }
            }
            GetDataJSON g = new GetDataJSON();
            g.execute();
        }

 protected void showList() {
        try {
            JSONObject jsonObj = new JSONObject(myJSON);
            details = jsonObj.getJSONArray(Configs.TAG_RESULTS);

            for (int i = 0; i < details.length(); i++) {
                JSONObject c = details.getJSONObject(i);
                String type = c.getString(Configs.TAG_TYPE);
                String description = c.getString(Configs.TAG_DESCRIPTION);
                String amount = c.getString(Configs.TAG_AMOUNT);
                String image = c.getString(Configs.TAG_IMAGE);
                int ID = c.getInt(Configs.TAG_ID);
                Staff staff = new Staff(ID, type, description, amount, image);
                staffs.add(staff);
            }

            CVAdapter adapter = new CVAdapter(getActivity(), staffs);
            listViewEdit.setAdapter(adapter);

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

CV适配器:

public  class CVAdapter extends ArrayAdapter<Staff> {
    Activity context;
    List<Staff> staffs;
    static class ViewHolder {
        public ImageView image;
        public TextView type;
        public TextView amount;
        public TextView description;
    }
    @Override
    public int getCount() {
        return staffs.size();
    }
    public CVAdapter(Activity context, List<Staff> staffs) {
        super(context, R.layout.retrieve_staff, staffs);
        this.context = context;
        this.staffs = staffs;
    }

    @Override
    public Staff getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if(convertView==null){
            ViewHolder v = new ViewHolder();
            LayoutInflater inflater = context.getLayoutInflater();
            convertView = inflater.inflate(R.layout.retrieve_staff, null);
            v.image = (ImageView)convertView.findViewById(R.id.image);
            v.amount = (TextView)convertView.findViewById(R.id.amount);
            v.type = (TextView)convertView.findViewById(R.id.type);
            v.description = (TextView)convertView.findViewById(R.id.description);
            convertView.setTag(v);
        }
        holder = (ViewHolder)convertView.getTag();
        Log.v("TEST", staffs.get(position).getImage());
        holder.image.setImageURI(Uri.parse(staffs.get(position).getImage()));
        holder.amount.setText(staffs.get(position).getAmount());
        holder.type.setText(staffs.get(position).getType());
        holder.description.setText(staffs.get(position).getDescription());
        return convertView;
    }
}

RetrieveImageAndText.php

<?php
  define('HOST','127.0.0.1:3307');
  define('USER','root');
  define('PASS','');
  define('DB','androiddb');

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

  $tws = $_GET['id'];

 $sql = "select * from staff_benefit WHERE ts_id= '". $tws."' ";

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

  $result=array();

  while($row=mysqli_fetch_array($res)){
     array_push($result,array('id'=>$row[0],'type'=>$row[1],'amount'=>$row[2],'description'=>$row[3],'image'=>$row[4],
      'ts_id'=>$row[5]));
  }

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

mysqli_close($con);

?>

输出

使用 Volley、Picasso 等网络库通过网络调用获取图像作为位图响应,然后您可以通过以下方式将其设置到 ImageView:

holder.image.setImageBitmap(bitmapResponse)

这里是使用 Volley 进行图像请求的教程: Image Requests with Volley

所以我用Picasso解决了

只要把holder.image.setImageURI(Uri.parse(staffs.get(position).getImage()));改成Picasso.with(getContext()).load(staffs.get(position).getImage()).into(holder.image);

使用简单的代码获取您的图像

String imageUrl="http://newhabari.000webhostapp.com/db_name/table_name/your_image";

例子

imageUrl="http://newhabari.000webhostapp.com/home_db/nhldb/boeing_787_2.png

        Context context=image.getContext();
        Picasso.with(context)
                .load(imageUrl)
                .placeholder(R.drawable.gazetter2)
                .error(R.drawable.hands)
                .into(image);

        return view;

这将为您提供数据库中的图像