- Get a remote picture cause NetworkOnMainThreadException in android
- public class SocialApp2Activity extends Activity {
- private Handler handler;
- private Facebook facebook;
- private AsyncFacebookRunner asyncRunner;
- private TextView text;
- private ImageView imgUserPic;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- handler = new Handler();
- text = (TextView) findViewById(R.id.txt);
- imgUserPic = (ImageView) findViewById(R.id.user_pic);
- facebook = new Facebook("MY_FB_APP_ID");
- asyncRunner = new AsyncFacebookRunner(facebook);
- facebook.authorize(this, new DialogListener() {
- @Override
- public void onComplete(Bundle values) {
- Bundle params = new Bundle();
- params.putString("fields", "name, picture");
- asyncRunner.request("me", params, new UserRequestListener());
- }
- ...
- });
- }
- @Override
- public void onActivityResult(int requestCode, int resultCode, Intent data) {
- super.onActivityResult(requestCode, resultCode, data);
- facebook.authorizeCallback(requestCode, resultCode, data);
- }
- /* Callback for fetching username and profile picture */
- public class UserRequestListener implements RequestListener {
- @Override
- public void onComplete(final String response, final Object state) {
- JSONObject jsonObject;
- try {
- jsonObject = new JSONObject(response);
- final String picURL = jsonObject.getString("picture");
- final String name = jsonObject.getString("name");
- handler.post(new Runnable() {
- @Override
- public void run() {
- text.setText(name);
- /********************************
- *** This line cause an error ***
- ********************************/
- imgUserPic.setImageBitmap(Utility.getBitmap(picURL));
- }
- });
- } catch (JSONException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- ...
- }
- }
- 05-04 14:37:28.898: W/System.err(1117): android.os.NetworkOnMainThreadException
- 05-04 14:37:28.905: W/System.err(1117): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1084)
- 05-04 14:37:28.905: W/System.err(1117): at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
- ...
- 05-04 14:37:29.005: W/System.err(1117): at libcore.net.http.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:164)
- 05-04 14:37:29.005: W/System.err(1117): at promlert.socialapp2.Utility.getBitmap(Utility.java:26)
- 05-04 14:37:29.016: W/System.err(1117): at promlert.socialapp2.SocialApp2Activity$UserRequestListener$1.run(SocialApp2Activity.java:95)
- ...
- new Thread(new Runnable() {
- @Override
- public void run() {
- //this line must be called not from the UI thread
- final Bitmap bitmap = Utility.getBitmap(picURL)
- handler.post(new Runnable() {
- @Override
- public void run() {
- text.setText(name);
- imgUserPic.setImageBitmap(bitmap );
- }
- });
- }
- }).start();