我想編寫一個方法,從對象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顯示位圖圖像,因爲代碼結構different.To防止混淆,我不同意我的所有代碼。我只想寫一個從對象的thumbnailurl獲取位圖的方法。後來我會用這個方法。我從http://jsonplaceholder.typicode.com/得到圖像
您無法在主線程上進行網絡調用,以防您想要加載圖像,Android中有幾個圖像加載器庫,例如:Glide https://github.com/bumptech/glide – hakim