0

The app I am writing requires user data from Facebook. I was using GraphRequest when I can upon the problem of retrieving a photo from facebook. I solved it by finding how to use URL and HttpURLConnection to extract a bitmap. Then when I implented it, I got the error NetworkOnMainThreadException.

I wanted to make a data extraction from Facebook to my app UI. I requested informtaion Using the Graph request method. I recieved data until I needed a bitmap from facebook. I found a solution using HttpURLConnection but the NetworkOnMainThreadException came up. I looked up multiple solutions that say that I need to make an ASYNC task. I assumed that the graphrequest was an ASYNC task so I don't know what step to take next.

protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.front_page);
    android.support.v7.widget.Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    drawer = findViewById(R.id.drawer_front_page);
    NavigationView nV = findViewById(R.id.drawer_view);
    View header = nV.getHeaderView(0);
    nV.setNavigationItemSelectedListener(this);
    callbackManager = CallbackManager.Factory.create();
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
            R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();
    getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
            new VenueList()).commit();
    nV.setCheckedItem(R.id.list_venue);

    ImageView drawerProfilePicture = header.findViewById(R.id.drawer_pic_profile);
    TextView drawerUserName = header.findViewById(R.id.drawer_profile_username);
    TextView drawerUserEmail = header.findViewById(R.id.drawer_profile_email);

    drawerUserName.setText("Hello My Baby");
    drawerUserEmail.setText("myemail@gmail.com");

    if (AccessToken.getCurrentAccessToken() != null && !AccessToken.getCurrentAccessToken().isExpired()) {
        GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(), (object, response) -> {
            try {

                userFullName = object.getString("name");
              //  userFullName = object.getString("first_name") + " " + object.getString("last_name");
                //userEmail = object.getString("email");
                drawerUserName.setText(userFullName);
                //drawerUserEmail.setText(userEmail);
                String id = object.getString("id");


              /*  URL imageURL = new URL("https://graph.facebook.com/" + id + "/picture?type=large");

                Bitmap bitmap = BitmapFactory.decodeStream(imageURL.openConnection().getInputStream());*/

                URL url = new URL("https://graph.facebook.com/" + id + "/picture?type=large");
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoInput(true);
                connection.connect();
                InputStream input = connection.getInputStream();
                Bitmap myBitmap = BitmapFactory.decodeStream(input);

                drawerProfilePicture.setImageBitmap(myBitmap);

               /* userProfilePicURL = "https://graph.facebook.com/" + id + "/pictures?type=normal";

                Glide.with(FrontPageClass.this).load(userProfilePicURL).into(drawerProfilePicture);*/

                Log.i(TAG, "name from Success: " + userFullName);
                Log.i(TAG, "email from Sucess: " + userEmail);

            } catch (JSONException e) {
                e.printStackTrace();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        });
        Bundle parameters = new Bundle();
        request.setParameters(parameters);
        request.executeAsync();

    }


    Log.i(TAG, "onCreate: " + userFullName);
}



E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.vitaliy.changethename, PID: 14279
android.os.NetworkOnMainThreadException
    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1513)
    at com.android.org.conscrypt.Platform.blockGuardOnNetwork(Platform.java:415)
    at com.android.org.conscrypt.ConscryptFileDescriptorSocket.shutdownAndFreeSslNative(ConscryptFileDescriptorSocket.java:1005)
    at com.android.org.conscrypt.ConscryptFileDescriptorSocket.close(ConscryptFileDescriptorSocket.java:1000)
    at com.android.okhttp.internal.Util.closeQuietly(Util.java:86)
    at com.android.okhttp.internal.http.StreamAllocation.deallocate(StreamAllocation.java:256)
    at com.android.okhttp.internal.http.StreamAllocation.connectionFailed(StreamAllocation.java:293)
    at com.android.okhttp.internal.http.HttpEngine.close(HttpEngine.java:445)
    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:509)
    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:407)
    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:244)
    at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
    at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:26)
    at com.example.vitaliy.changethename.FrontPageClass.lambda$onCreate$0$FrontPageClass(FrontPageClass.java:94)
    at com.example.vitaliy.changethename.-$$Lambda$FrontPageClass$TF1liEC2dHjoBVyqHtUi2sJJ-4A.onCompleted(Unknown Source:6)
    at com.facebook.GraphRequest$1.onCompleted(GraphRequest.java:316)
    at com.facebook.GraphRequest$5.run(GraphRequest.java:1395)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:193)
    at android.app.ActivityThread.main(ActivityThread.java:6669)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

I want to dsiplay a bitmap I get from the URL I wrote in. I'm getting a NetworkOnMainThreadException but I assumed, unwisely that the GraphRequest is an Async process. I do not know the next step I should take to fix the code.

DJ. Aduvanchik
  • 332
  • 5
  • 17
  • Move the logic from your `try`/`catch` block to another method. In that method, use one of the **many** threading options available to Android developers, such as those listed in the duplicate question. – CommonsWare May 19 '19 at 10:57
  • @CommonsWare is it a bad question if I ask for an answer that is specific to my situation? I want to understand why the async task is not working if that's what's required for the Network to work. I was hoping to get a an answer that would give me a direct case where I can get this to work that can get more information on this site about specifics of facebook SDK – DJ. Aduvanchik May 20 '19 at 04:40
  • 1
    "I want to understand why the async task is not working if that's what's required for the Network to work" -- you do not have an `AsyncTask` in your code. "I assumed that the graphrequest was an ASYNC task" -- it does not matter what the underlying implementation is. Based on your stack trace, the lambda expression that you are providing to `GraphRequest.newMeRequest()` is being executed on the main application thread. So, you need to move the work in that lambda expression to a background thread yourself. – CommonsWare May 20 '19 at 10:53
  • @CommonsWare thank you – DJ. Aduvanchik May 20 '19 at 16:00

0 Answers0