【问题标题】:How can i display images that i am receiving from (server) in a string ? Here is the code:如何在字符串中显示从(服务器)接收的图像?这是代码:
【发布时间】:2017-12-30 21:25:53
【问题描述】:

如何在字符串中显示我从(服务器)接收的图像? 我正在使用AsyncTask

代码如下:

异步任务

public class sendRequest extends AsyncTask<String, Void,String> {

    String response="";
    Context context;


    sendRequest(Context context)
    {
        this.context=context;
       // this.list=list;
    }


    @Override
    protected void onPreExecute() {
        super.onPreExecute();


    }

    @Override
    protected String doInBackground(String... params)
    {



    URL url;
    BufferedReader reader = null;


    String link =<i> "example.com/example.php";</i>


    try {
        url = new URL(link);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setConnectTimeout(5 * 1000);
        connection.setReadTimeout(5 * 1000);
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestMethod("POST");

        connection.connect();

        String inputToFile = URLEncoder.encode("mName", "UTF-8") + "=" + URLEncoder.encode("name", "UTF-8");



        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
        writer.write(inputToFile);
        writer.flush();

        reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

        String line = null;

        while ((line = reader.readLine()) != null) {

//Here i have add data to string how to display images 

//The result of Toast in onpostexecute is

//{"images":[{"image":"http:\/\/example.com\/example.jpg"},{"image":"http:\/\/example.com\/example.jpg"}]}

            response += line;


        }

        //Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
        //Toast.makeText(context,bmp.toString(),Toast.LENGTH_SHORT).show();


    } catch (MalformedURLException e) {
        //   DonorList.setText("Url Error");
        e.printStackTrace();
        response = "Exception: " + e.getMessage();
    } catch (IOException e) {
        //   DonorList.setText("Connection could not be opened");
        e.printStackTrace();
        response += "Exception: " + e.getMessage();
    }

        return response;

    }// DO IN BACKGROUND



    @Override
    protected void onPostExecute(String response) {

        super.onPostExecute(response);

        Toast.makeText(context, "Recieved: "+response, Toast.LENGTH_LONG).show();

【问题讨论】:

  • 图像是二进制的 - 你希望如何显示为文本?
  • 请简要告诉我们您的问题。只有代码没有帮助?你想达到什么目标?
  • 我想在从服务器接收到的图像视图中显示图像。
  • 您的代码显示您有一个 json 数据作为响应,并且您想从 url 中取出位图?是这样吗?如果是,问题出在哪里?

标签: java android android-asynctask


【解决方案1】:

使用 Glide 库在 ImageView 中加载图像

Glide.with(context).load(image_url).into(imageView);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-25
    • 2022-01-13
    相关资源
    最近更新 更多