简体   繁体   English

在imageView的editText中输入的图像URL

[英]Image URL entered In editText on a imageView

When the user clicks this button the app should retrieve the image from the web. 当用户单击此按钮时,应用程序应从网络检索图像。 It should do this in a separate thread and When the image is downloaded it should be displayed on the same Screen using ImageView.I can't seem to get it to work but I feel like I'm really close can anyone help me out please? 它应该在一个单独的线程中执行此操作,下载图像后应使用ImageView将其显示在同一屏幕上。我似乎无法使其正常工作,但我觉得我真的很亲密,有人可以帮助我吗? Thanks! 谢谢!

My Manifest File 我的清单文件

<?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>

My XML FIle 我的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" />

My Jave File 我的档案

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

} }

Use special android libraries like Glide or Picasso to load images. 使用特殊的Android库(例如GlidePicasso)加载图像。 It's really easy to use it, they have disk/memory cache, you can load image in separate thread without using complex solutions. 它非常容易使用,它们具有磁盘/内存缓存,您可以在不使用复杂解决方案的情况下将图像加载到单独的线程中。

As you mentionned in a comment, your image is at this url 正如您在评论中提到的那样,您的图片位于此网址

http://tny.im/ayy http://tny.im/ayy

This url does not point to an image. 该网址未指向图片。 It points to a redirects, (http status 301). 它指向重定向(http状态301)。

It is possible that your connection is not following redirects. 您的连接可能没有遵循重定向。

You can instruct the connection to follow the redirection by: 您可以通过以下方式指示连接遵循重定向:

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

Ok so here is my thoughts after talking in the comments 好吧,这是我在评论中说过的想法

1) I copied your code and xml EXACTLY as you posted and it WORKS fine for me, with that said I want to add a few things 1)我完全按照您发布的方式复制了您的代码和xml,对我来说效果很好,说我想添加一些内容

EDIT: not sure if this matters but these were my imports 编辑:不确定这是否重要,但这是我的进口

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;

I think it could be a combination of these possibilities 我认为这可能是这些可能性的结合

2) make sure your url is ok, make sure you add the http or https part. 2)确保您的网址正常,请确保添加http或https部分。 make sure your auto correct does not add anything (mine added a period at the end). 确保您的自动更正功能没有添加任何内容(我的操作在末尾添加了一个句号)。 since this is the only part I can't test, I feel like this could be it 因为这是我无法测试的唯一部分,所以我觉得可能就是这样

3) Log everything, log the url right before its passed into your URL object just to be sure it is correct, look for ANY exceptions 3)记录所有内容,在将该URL传递到您的URL对象之前立即对其进行记录,以确保它是正确的,查找任何例外

4) the toast will not show up if url is wrong, if url can't parse a valid URL ( like mentioned earlier), it will be caught in the try catch surrounding the URL object being created and will not call the async task (happen to me when I put fake url in and I got exception, so try keep an eye out) 4)如果url错误,吐司将不会显示,如果url无法解析有效的URL(如前所述),它将被尝试围绕正在创建的URL对象进行捕获,并且不会调用异步任务(当我输入伪造的url并发生异常时发生在我身上,所以请注意一下)

EDIT: for number 4, i got exception for incorrect protocol (left out the http) but if link was wrong then yes, toast showed up 编辑:对于4号,我有不正确的协议的异常(忽略了http),但如果链接错误,那么是的,吐司

5) try another image, you never know :D 5)尝试另一个图像,你永远不知道:D

EDIT: try this with Glide, 编辑:尝试使用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();
        }
    }

no need for async 不需要异步

and one more solution without Glide 还有另一种没有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;
    }

// Add following dependecny for glide //添加以下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);

    }

I couldn't get the code I originally posted to work even with all of you's guys help. 即使在大家的帮助下,我也无法获得最初发布的代码。 Big thanks to anybody that posted with suggestions!!. 非常感谢任何发表了建议的人! Anyway I went back to scratch and finally got it to work with even less code! 无论如何,我回到头开始,终于用更少的代码来工作了! Here's my working code 这是我的工作代码

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

Use library like Glide. 使用像Glide这样的库。 You can simply add Glide dependency in Gradle: compile 'com.github.bumptech.glide:glide:3.7.0' 您可以简单地在Gradle中添加Glide依赖项:compile'c​​om.github.bumptech.glide:glide:3.7.0'

and you can load image simply by writing: Glide.with(context).load("image_url").into(imagevie_name); 您只需编写以下代码即可加载图像:Glide.with(context).load(“ image_url”)。into(imagevie_name);

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

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