繁体   English   中英

在imageView的editText中输入的图像URL

[英]Image URL entered In editText on a imageView

当用户单击此按钮时,应用程序应从网络检索图像。 它应该在一个单独的线程中执行此操作,下载图像后应使用ImageView将其显示在同一屏幕上。我似乎无法使其正常工作,但我觉得我真的很亲密,有人可以帮助我吗? 谢谢!

我的清单文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.stephen.asyncdownloadimageurl">
<uses-permission android:name="android.permission.INTERNET">
</uses-permission>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

我的XML文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<ImageView
    android:id="@+id/imageView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:srcCompat="@android:drawable/alert_light_frame"
    android:layout_marginBottom="146dp"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true" />

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/imageView"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="91dp" />

<EditText
    android:id="@+id/editText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/button"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="51dp"
    android:ems="10" />

我的档案

public class MainActivity extends AppCompatActivity {
Button btn;
EditText et;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btn = (Button) findViewById(R.id.button);
    et = (EditText) findViewById(R.id.editText);

    btn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            try {
                URL url = new URL(et.getText().toString());
                new MyDownloadTask().execute(url);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

private class MyDownloadTask extends AsyncTask<URL, Integer, Bitmap> {
    @Override
    protected Bitmap doInBackground(URL... params) {
        URL url = params[0];
        Bitmap bitmap = null;
        try {
            URLConnection connection = url.openConnection();
            connection.connect();
            InputStream is = connection.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            bitmap = BitmapFactory.decodeStream(bis);
            bis.close();
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        return bitmap;
    }

    @Override
    protected void onPostExecute(Bitmap bitmap) {
        if (bitmap != null) {
            ImageView myImage = (ImageView) findViewById(R.id.imageView);
            myImage.setImageBitmap(bitmap);
        } else {
            Toast.makeText(getApplicationContext(), "Failed to Download Image", Toast.LENGTH_LONG).show();
        }
    }
}

}

使用特殊的Android库(例如GlidePicasso)加载图像。 它非常容易使用,它们具有磁盘/内存缓存,您可以在不使用复杂解决方案的情况下将图像加载到单独的线程中。

正如您在评论中提到的那样,您的图片位于此网址

http://tny.im/ayy

该网址未指向图片。 它指向重定向(http状态301)。

您的连接可能没有遵循重定向。

您可以通过以下方式指示连接遵循重定向:

((HttpURLConnection) connection).setInstanceFollowRedirects(true);

好吧,这是我在评论中说过的想法

1)我完全按照您发布的方式复制了您的代码和xml,对我来说效果很好,说我想添加一些内容

编辑:不确定这是否重要,但这是我的进口

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

我认为这可能是这些可能性的结合

2)确保您的网址正常,请确保添加http或https部分。 确保您的自动更正功能没有添加任何内容(我的操作在末尾添加了一个句号)。 因为这是我无法测试的唯一部分,所以我觉得可能就是这样

3)记录所有内容,在将该URL传递到您的URL对象之前立即对其进行记录,以确保它是正确的,查找任何例外

4)如果url错误,吐司将不会显示,如果url无法解析有效的URL(如前所述),它将被尝试围绕正在创建的URL对象进行捕获,并且不会调用异步任务(当我输入伪造的url并发生异常时发生在我身上,所以请注意一下)

编辑:对于4号,我有不正确的协议的异常(忽略了http),但如果链接错误,那么是的,吐司

5)尝试另一个图像,你永远不知道:D

编辑:尝试使用Glide,

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

btn = (Button) findViewById(R.id.button);
et = (EditText) findViewById(R.id.editText);

btn.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        try {
            Glide.with(MainActivity.this)
                    .load(et.getText().toString())
                    .into((ImageView) findViewById(R.id.imageView));

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

不需要异步

还有另一种没有Glide的解决方案

  @Override
        protected Bitmap doInBackground(URL... params) {
            URL url = params[0];
            HttpURLConnection connection = null;
            Bitmap bitmap = null;


            try {
                connection = (HttpURLConnection) url.openConnection();
                connection.setDoInput(true);
                connection.connect();
                InputStream input = connection.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(input);
                bitmap = BitmapFactory.decodeStream(bis);
                bis.close();
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }



  return bitmap;
    }

//添加以下Dependecny进行滑行

compile 'com.github.bumptech.glide:glide:3.7.0'



new LoadImageFromUrlTask().execute(imageURL);




public class LoadImageFromUrlTask extends AsyncTask<String, Void, Bitmap> {
        String downloadPath = "";
        String sdCardBasePath = Environment.getExternalStorageDirectory().toString();
        @Override
        protected Bitmap doInBackground(String... args) {
            try {
                downloadPath = args[0];
                return BitmapFactory.decodeStream((InputStream) new URL(downloadPath).getContent());

            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            if (bitmap != null) {
                String photoFileName = downloadPath.substring(downloadPath.lastIndexOf('/') + 1);
                String saveImagePath = "";

                int dotposition = photoFileName.lastIndexOf(".");
                String filename_Without_Ext = photoFileName.substring(0, dotposition);
                String Ext = photoFileName.substring(dotposition + 1, photoFileName.length());
                String newFileName = filename_Without_Ext + "." + Ext;
                saveImagePath = sdCardBasePath + "/" + newFileName;
                saveBitmapToJPEGFile(MainActivity.this, bitmap, new File(saveImagePath), 900);
                saveBitmapToFile(MainActivity.this, myImageViewImage, saveImagePath);
            } else {
                myImageViewImage.setImageResource(R.drawable.default_photo);
            }
        }
    }

    public Boolean saveBitmapToFile(Context ctx, Bitmap tempBitmap, File targetFile, int i) {
        Boolean result = true;
        if (tempBitmap != null) {
            FileOutputStream out = null;
            try {
                out = new FileOutputStream(targetFile);
                tempBitmap.compress(Bitmap.CompressFormat.JPEG, CommonUtils.JPEG_COMPRESION_RATIO_DEFAULT, out);  

            } catch (FileNotFoundException e) {
                result = false;
                e.printStackTrace();
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else {
            result = false;
        }
        return result;
    }

    public void loadImageWithGlide(Context theCtx, ImageView theImageView, String theUrl) {
        Glide.with(theCtx)
                .load(theUrl)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .skipMemoryCache(true)
                .into(theImageView);

    }

即使在大家的帮助下,我也无法获得最初发布的代码。 非常感谢任何发表了建议的人! 无论如何,我回到头开始,终于用更少的代码来工作了! 这是我的工作代码

public class MainActivity extends AppCompatActivity {
    EditText editText;
    Bitmap bitmap;
    ImageView view;
    Button btn;
    ProgressDialog pd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editText = (EditText) findViewById(R.id.inputFileUrl);
        view = (ImageView) findViewById(R.id.imageView);
        btn = (Button) findViewById(R.id.retrieveFileUrl);
    }

    public void buttonClicked(View view) {

        String stringUrl = editText.getText().toString();
        new DownloadTask().execute(stringUrl);
    }


    // Uses AsyncTask to create a task away from the main UI thread. This task takes
    // URL string and uses it to create an HttpUrlConnection. Once the connection
    // has been established, the AsyncTask downloads the contents of the webpage as
    // an InputStream. Finally, the InputStream is converted into a string, which is
    // displayed in the UI by the AsyncTask's onPostExecute method.
    public class DownloadTask extends AsyncTask<String, Void, Bitmap> {

        @Override
        protected void onPreExecute() {
            //Create PD, SET Properties
            pd = new ProgressDialog(MainActivity.this);
            pd.setTitle("Image Downloader");
            pd.setMessage("Downloading....");
            pd.setIndeterminate(false);
            pd.show();
        }

        @Override
        protected Bitmap doInBackground(String... urls) {

            String url = urls[0];

            try {
                bitmap = BitmapFactory.decodeStream(new URL(url).openConnection().getInputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
            return bitmap;
        }
        // onPostExecute displays the results of the AsyncTask.

        @Override
        protected void onPostExecute(Bitmap url) {
            if (bitmap != null) {
                super.onPostExecute(url);
                view.setImageBitmap(url);
                //Dismiss
                pd.dismiss();
            } else {
                Toast.makeText(getApplicationContext(), "Failed to Download Image", Toast.LENGTH_LONG).show();
                //Dismiss
                pd.dismiss();
            }
        }
    }
}

使用像Glide这样的库。 您可以简单地在Gradle中添加Glide依赖项:compile'c​​om.github.bumptech.glide:glide:3.7.0'

您只需编写以下代码即可加载图像:Glide.with(context).load(“ image_url”)。into(imagevie_name);

暂无
暂无

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

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