Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/390.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/210.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在imageView的editText中输入的图像URL_Java_Android - Fatal编程技术网

Java 在imageView的editText中输入的图像URL

Java 在imageView的editText中输入的图像URL,java,android,Java,Android,当用户单击此按钮时,应用程序应从web检索图像。它应该在一个单独的线程中完成这项工作,当图像被下载时,它应该使用ImageView显示在同一屏幕上。我似乎无法让它工作,但我觉得我真的很接近。有人能帮我吗?谢谢 我的清单文件 <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.

当用户单击此按钮时,应用程序应从web检索图像。它应该在一个单独的线程中完成这项工作,当图像被下载时,它应该使用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" />
我的Jave文件

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库(如或)加载图像。使用起来非常简单,它们有磁盘/内存缓存,您可以在单独的线程中加载映像,而无需使用复杂的解决方案。

使用像Glide这样的库。您只需在Gradle中添加滑动依赖项: 编译'com.github.bumptech.glide:glide:3.7.0'

您可以通过以下方式加载图像:
Glide.withcontext.loadimage\u url.intoimagevie\u name

好的,下面是我在评论中发言后的想法

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确保url正常,确保添加了http或https部分。确保您的自动更正不会在结尾添加任何我添加的句点。因为这是我唯一不能测试的部分,我觉得这可能就是它

3记录所有内容,在url传递到url对象之前记录url以确保其正确性,查找任何异常

4如果url错误,toast将不会显示,如果url不能像前面提到的那样解析有效的url,它将被捕获在正在创建的url对象周围的try-catch中,并且不会调用异步任务。当我放入假url时,我遇到异常,所以请注意

编辑:对于第4个,我得到了一个异常,因为错误的协议遗漏了http,但如果链接错误,那么是的,toast出现了

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();
        }
    }
不需要异步

还有一个没有滑动的解决方案

  @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;
    }

正如您在评论中提到的,您的图像位于此url

此url不指向图像。它指向一个重定向,http状态301

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

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

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

//为滑动添加以下依赖项

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

    }

即使在你们的帮助下,我也无法获得我最初发布的代码。非常感谢所有发表建议的人!!。无论如何,我回到了scratch,最终用更少的代码让它工作! 这是我的工作代码

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


你能描述一下错误吗?没有结果?没有来自流的数据?有关于这个问题的更多信息吗?@TannerSummers我的Toast消息不起作用,它告诉我,它尝试检索图像失败,但也无法获取图像。我所有的代码都运行了,但我似乎无法找到问题的原因。我将您的代码放入我的pc中。除了没有使用st.getText.to字符串外,它工作正常。所以你可能想看看这是否有价值。还有,如果我可以问,你为什么要从文本视图中阅读?@TannerSummers所以我的代码下载了一个图像?我的代码不包含文本视图?是否有按钮、编辑文本和图像视图?是。我放了一个编辑文本按钮和图像视图。我只是把你的代码,因为你有它和工程罚款。所以我不确定。您的控制台android监视器是否显示任何错误?传递到url对象的url是否正确?谢谢。这对我想要达到的目标有用吗?事实上我没有达到你想要达到的目标。但它将在工作线程中加载图像,这是这个库可以做的最简单的事情。对于这种情况,它是一个很棒的库,我认为它不需要。但是如果你真的想要它,在你的应用程序中加入它并不难,但我们仍然需要首先解决你的问题。虽然这是一个好建议,但它并不能回答问题。另外请注意,还有版本4的发布版。我认为它很有帮助,我一直在尝试解决它,使用它可能会更容易,但我不确定。OP的代码对我来说很好,虽然我不知道OP示例中的图像有多大,谢谢你,先生,感谢你花时间帮助完成这项任务,我很感激。我最终会弄清楚的!让我知道,我对这个问题很好奇。如果我们可以在这个网站上聊天,给我留言或者我想帮忙的东西。我的吐司留言现在显示出来,就像你提到的尝试一个新的url。但是它是一个有效的图像URL,所以我不确定这是怎么回事。当我按下带有URL的按钮时,控制台中会显示这个URL-10-07 04:47:28.424 23415-23988/com.example.stephen.asyncdownloadimageurl D/skia:-SkImageDecoder::Factory返回空。您是否在控制台中注销了该URL?我会注销url,复制并粘贴到浏览器中,看看是否有任何更改和工作。谢谢你的建议,但不幸的是,这并没有起作用。很好地了解
在重定向方法!好的,只要它能工作,对我来说它看起来是一样的,所以不确定为什么,但只要它能正常工作?总之,请注意ProgressDialog已被弃用,仅供参考: