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

时间:2016-01-15 03:24:21

标签: android mysql image uri

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

MySQL

enter image description here

发送到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 "";
}

现在我尝试从url获取MySQL并将图像显示为listView,但无法检索图像,只能检索字符串。

从服务器检索:

      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();
        }

    }

CVAdapter:

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);

?>

输出

enter image description here

3 个答案:

答案 0 :(得分:2)

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

holder.image.setImageBitmap(bitmapResponse)

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

答案 1 :(得分:0)

所以我用Picasso解决了它

只需将holder.image.setImageURI(Uri.parse(staffs.get(position).getImage()));更改为Picasso.with(getContext()).load(staffs.get(position).getImage()).into(holder.image);

即可

答案 2 :(得分:0)

只使用简单的代码来获取图片

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;

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