2017-10-08 44 views
1

我嘗試解碼從輸入流的URL bipmap的Android異步獲取圖像

公共類演示實現MVPmain.presenter {

String LOG_TAG = "Presenter: "; 

private final MVPmain.view view; 
String url = "https://jsonplaceholder.typicode.com/"; 

public Presenter(MVPmain.view view) { 
    this.view = view; 
} 


void photosUrl() { 
     String photoUrl = "http://placehold.it/600/92c952"; 
     AsyncLoadImage asyncLoadImage = new AsyncLoadImage(); 
     asyncLoadImage.execute(photoUrl); 
    } 
} 

@Override 
public void button_photos_clicked() { 
    photosUrl(); 
} 

Bitmap loadImage(String url) { 
    Bitmap bitmapImage = null; 
    URL imageUrl = null; 
    HttpURLConnection httpURLConnection = null; 
    try { 
     imageUrl = new URL(url.replaceAll("\\r|\\n", "")); 
     httpURLConnection = (HttpURLConnection) imageUrl.openConnection(); 
     bitmapImage = BitmapFactory.decodeStream(httpURLConnection.getInputStream()); 
     Log.d(LOG_TAG, "Runneble: " + "OK"); 
    } catch (MalformedURLException e) { 
     Log.e(LOG_TAG, "image url error: " + e); 
     e.printStackTrace(); 
    } catch (IOException e) { 
    e.printStackTrace(); 
    } 
    return bitmapImage; 
} 


class AsyncLoadImage extends AsyncTask<String, Void, Bitmap> { 
    String LOG_TAG = "AsyncLoadImage: "; 
    Bitmap bitmapImage; 

    @Override 
    protected Bitmap doInBackground(String... strings) { 
     String request = ""; 
     final URL imageUrl = null; 
     JSONObject jsonObject = null; 
     for (final String address : strings) { 
      Log.d(LOG_TAG, "img url: " + address); 
      bitmapImage = loadImage(address); 

     } 
     return bitmapImage; 
    } 

    @Override 
    protected void onPostExecute(Bitmap bitmapImg) { 
      view.setPhotos(bitmapImg); 
    } 

} 

}

它的代碼的一部分,在那裏我得到異常:httpURLConnection.getInputStream()中的連接被拒絕。我嘗試.getContent並得到這個錯誤。 請告訴我,我該如何做到這一點。

解決 此錯誤的情況下AdWay!)

+0

您是否在Manifest中添加

+0

是的。起初,我從這裏獲取照片的地址:https://jsonplaceholder.typicode.com/photos/3,asynctask使用此網址,但不能與圖片網址一起使用:http://placehold.it/600/92c952 。 例如,這個網址:https://image.flaticon.com/teams/slug/freepik.jpg工作... –

回答

0

你的代碼是在我的設備可以正常使用。

確保您的互聯網連接正常工作,並直接從Android設備的瀏覽器打開圖像URL,以驗證您是否有權訪問該URL。

+0

從手機上的鉻我可以打開這張圖片。但從我的應用程序沒有。錯誤截圖: https://i.stack.imgur.com/3vwlK.png –

+0

在其他設備上測試。它可能是設備特定的問題。 –

+0

你對!在虛擬設備上的代碼是工作...我嘗試之前在我的nexus 5 7.1.2 –