When I coded my android project, I need to load a bitmap object with URL. There was an exception thrown when I ran following code:
Bitmap bm = GetLoginUserInfoUtil.getBitmap(object.getString("profile_image_url"));
The exception:
12-30 21:01:14.440: W/System.err(6025): android.os.NetworkOnMainThreadException
12-30 21:01:14.440: W/System.err(6025): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
Here is my method getBitmap:
public static Bitmap getBitmap(String biturl) {
Bitmap bitmap=null;
try {
URL url = new URL(biturl);
URLConnection conn = url.openConnection();
InputStream in = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(new BufferedInputStream(in));
}
catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
I found a similar posted questions regarding android.os.NetworkOnMainThreadException, the most recommended solution is using AsyncTask.
How can I implement AsyncTask in my class GetLoginUserInfoUtil?
Edit: This is the original method I load bitmap file:
public static void reqUserInfo(final Oauth2AccessToken accessToken, long uid) {
user = new LoginUserInfo();
UsersAPI userapi = new UsersAPI(accessToken);
userapi.show(uid, new RequestListener() {
public void onComplete(String arg0) {
JSONObject object;
try {
object = new JSONObject(arg0);
Bitmap bm = GetLoginUserInfoUtil.getBitmap(object.getString("profile_image_url"));
GetLoginUserInfoUtil.user.setUserIcon(bm);
GetLoginUserInfoUtil.user.setIsDefault("0");
GetLoginUserInfoUtil.user.setToken(accessToken.getToken());
GetLoginUserInfoUtil.user.setUserName(object.getString("screen_name"));
}
catch (JSONException e) {
e.printStackTrace();
}
}
now I have added suggested AsyncTask in the class:
private class GetBitmapTask extends AsyncTask<String, Void, Bitmap> {
@Override
protected Bitmap doInBackground(String... params) {
return GetLoginUserInfoUtil.getBitmap(params[0]);
}
@Override
protected void onPostExecute(Bitmap result) {
GetLoginUserInfoUtil.user.setUserIcon(result);
}
}
in onComplete, i have added:
new GetBitmapTask().execute(object.getString("profile_image_url"));
but i got error:
No enclosing instance of type GetLoginUserInfoUtil is accessible. Must qualify the allocation with an enclosing instance of type
GetLoginUserInfoUtil (e.g. x.new A() where x is an instance of GetLoginUserInfoUtil).