当用户点击此按钮时,应用应该从网络上检索图像。它应该在一个单独的线程中执行此操作,并且当下载图像时,它应该使用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();
}
}
}
}
答案 0 :(得分:2)
答案 1 :(得分:2)
正如您在评论中提到的,您的图片位于此网址
此网址未指向图片。它指向重定向,(http状态301)。
您的连接可能没有遵循重定向。
您可以通过以下方式指示连接遵循重定向:
((HttpURLConnection) connection).setInstanceFollowRedirects(true);
答案 2 :(得分:1)
好的,这是我在评论中谈到后的想法
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错误,toast将不会显示,如果url无法解析有效的URL(如前所述),它将被捕获到围绕正在创建的URL对象的try catch中,并且不会调用异步任务(当我把假网址放进去时发生在我身上并且我得到例外,所以请一定注意)
编辑:对于数字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;
}
答案 3 :(得分:0)
//为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);
}
答案 4 :(得分:0)
即使你们所有人都帮忙,我也无法获得我最初发布的代码。非常感谢任何发布建议的人!!无论如何,我回到了划痕,终于让它与更少的代码一起工作! 这是我的工作代码
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();
}
}
}
}
答案 5 :(得分:-1)
使用像Glide这样的库。您可以在Gradle中简单地添加Glide依赖项: 编译&#39; com.github.bumptech.glide:滑翔:3.7.0&#39;
您只需编写以下内容即可加载图片: Glide.with(上下文).load(&#34; IMAGE_URL&#34)代入式(imagevie_name);