[英]Unable to load photos from URL in Android
我正在開發牆紙應用程序。 我寫了一個AsyncTask來從選定的URL下載照片並將其加載為牆紙(全部在后台)。 現在,AsyncTask有時會起作用。 而且,我本人無法理解無法從URL加載/下載圖像(作為位圖)的原因是什么。 url(好的一個和壞的一個)都可以正常工作,並在瀏覽器中加載正確的圖像。
我的AsyncTask類:
@Override
protected Void doInBackground(String... params) {
Bitmap output = null;
try {
URL url = new URL(params[0]);
Log.d(TAG, "_log: output URL is: "+url.toString());
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream inputStream = connection.getInputStream();
output = BitmapFactory.decodeStream(inputStream);
Log.d(TAG, "_log: output size "+output.getByteCount());
} catch (MalformedURLException e) {
e.printStackTrace();
Log.d(TAG, "_log: output with MalformedURLException "+e.toString());
} catch (IOException e) {
Log.d(TAG, "_log: output with IOException "+e.toString());
e.printStackTrace();
} catch (Exception e) {
Log.d(TAG, "_log: output with Exception "+e.toString());
e.printStackTrace();
} finally {
if (output != null) util.setupWallpaper(context, output);
else Log.d(TAG, "_log: output is null");
}
return null;
}
setupWallpaper函數為:
public void setupWallpaper(Context context, Bitmap image) {
WallpaperManager wallpaperManager = WallpaperManager.getInstance(context);
try {
if (image == null) {
makeToast(context, "Image is null!");
} else {
wallpaperManager.setBitmap(image);
}
} catch (IOException e) {
e.printStackTrace();
}
}
錯誤只是當我嘗試獲取空對象(輸出)的大小時在異常中捕獲的stackTrace。
output with Exception java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getByteCount()' on a null object reference
RetrieveFeed.doInBackground(RetrieveFeed.java:57)
RetrieveFeed.doInBackground(RetrieveFeed.java:27)
權限:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.SET_WALLPAPER"/>
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
<uses-permission android:name="android.permission.CHANGE_CONFIGURATION"/>
我沒有嘗試將此圖像加載到任何imageView中,而是將該圖像發送到WallPaperManager中以作為牆紙加載。
我想指出的是,我使用Glide嘗試了相同的操作,並且出現了相同的結果!
(代表OP張貼) 。
問題是,不良的網址圖片太大,無法處理,因此Bitmap靜默失敗。
D/skia: --- too Large Progressive Image (1, 5184 x 3456)> limit(16777216)
D/skia: --- decoder->decode returned false
如果我是你,我將使用畢加索圖書館來處理所有這些問題
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
這行代碼從您指定的URL下載圖像並將其加載到imageView中。
但是您需要先在build.gradle中對其進行編譯。
有關更多詳細信息,請訪問圖書館網站 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.