2016-10-07 1 views
0

개체 URL에서 비트 맵 이미지를 반환하는 메서드를 작성하고 싶습니다. 그러나 NetworkOnMainThreadException 오류가 발생합니다.개체 URL에서 비트 맵 반환

Image.java :

package gc.x.models; 

import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.os.AsyncTask; 
import android.util.Log; 
import android.widget.ImageView; 

import com.google.gson.annotations.SerializedName; 

import java.io.IOException; 
import java.io.InputStream; 
import java.net.HttpURLConnection; 
import java.net.URL; 

import gc.x.R; 


/** 
* Created by ASUS on 4.10.2016. 
*/ 
public class Image { 


    public String albumId; 
    public String id; 
    public String title; 
    public String url; 
    public String thumbnailUrl; 


    public Bitmap getBitmapFromURL() {//get bitmap of thumbnail from thumbnailurl 
     try { 
      URL url = new URL(this.thumbnailUrl); 
      HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
      connection.setDoInput(true); 
      connection.connect(); 
      InputStream input = connection.getInputStream(); 
      Bitmap myBitmap = BitmapFactory.decodeStream(input); 
      return myBitmap; 
     } catch (IOException e) { 
      // Log exception 
      return null; 
     } 
    } 


} 

내가, 코드 구조가 혼란을 방지 달랐어 때문에 단순히 URL에서 비트 맵 이미지를 표시하고 싶지 않아 내 모든 코드를 공유하지 않았다. 객체의 thumbnailurl에서 비트 맵을 가져 오는 메소드를 작성하려고합니다. 나중에이 방법을 사용하겠습니다. 이미지를 얻습니다 http://jsonplaceholder.typicode.com/

+1

이미지를로드하려는 경우 메인 이미지에서 네트워크 호출을 수행 할 수 없기 때문에 안드로이드에 여러 이미지 로더 라이브러리가 있습니다 (예 : Glide https://github.com/bumptech)./glide – hakim

답변

2

메인 스레드에서이 네트워크 작업을 수행 할 수 없습니다.이 작업은 비동기 작업에 작성해야합니다.

쓰기는 클래스 내부 코드

private class AsyncClass extends AsyncTask<String, Void, String> { 
    @Override 
    protected String doInBackground(String... params) { 
     getBitmapFromURL(); 
    } 

    @Override 
    protected void onPostExecute(String result) { 
    } 

    @Override 
    protected void onPreExecute() { 
    } 

    @Override 
    protected void onProgressUpdate(Void... values) { 
    } 
} 

new AsyncClass().execute(""); 
+0

비트 맵을 반환해야합니다, 가능합니까? 비트 맵을 반환하려면 어떻게해야합니까? 클래스 내부에 쓸 때 일반적으로 imcompatible 유형 오류가 발생하기 때문입니다. –

+0

비동기 작업에서 값을 직접 반환 할 수는 없으며 값만 할당 할 수 있습니다. onPostExecute 함수의 기본 스레드에 액세스 할 수 있습니다. –

0

문제처럼 전화는 또한 I가 좋을 것 ... 네트워크 작업을 위해 메인 스레드를 사용하는 것입니다 이미지로드 프레임 워크를 사용하여 그 목표를 달성하십시오. 즉, 글라이드를 사용하십시오. 한 줄로 그 비트 맵을가집니다. 글라이드가 당신을 대신해서 mainThread를 해결할 필요가 없습니다. 코드에 집중하십시오.

Bitmap theBitmap = Glide.with(this). 
       load("http://...."). // or url 
       asBitmap(). 
       into(100, 100). // Width and height 
       get(); 

글라이드 : https://github.com/bumptech/glide