【问题标题】:Attempting to load the user's Facebook profile pic into a marker results in Nullpointer Exception尝试将用户的 Facebook 个人资料图片加载到标记中会导致 Nullpointer 异常
【发布时间】:2016-06-25 04:58:10
【问题描述】:

我正在尝试将用户的 Facebook 个人资料图片应用为标记中的“图标”属性。但由于某些未知原因,我在执行此操作时收到了 Nullpointer 异常。

语法是正确的,我只是剪掉了一些代码,只是为了向您展示影响它的唯一一点(与标记有关)。

AccessToken accessToken = AccessToken.getCurrentAccessToken();
            MarkerOptions marker = new MarkerOptions().position(
                    new LatLng(point.latitude, point.longitude)).title("New Marker");
            globalMap.addMarker(marker
                    .position(point)
                    .icon(BitmapDescriptorFactory.fromBitmap(getFacebookProfilePicture(accessToken.getUserId())))
                    .anchor(0.5f, 1));
        }
    });
}

public static Bitmap getFacebookProfilePicture(String userID){
    Bitmap bitmap = null;
    try {
        URL imageURL = new URL("https://graph.facebook.com/" + userID + "/picture?type=large");
         bitmap = BitmapFactory.decodeStream(imageURL.openConnection().getInputStream());
    }catch(Exception e){

    }
    return bitmap;
}

我认为是这条线给我带来了问题,但是......

icon(BitmapDescriptorFactory.fromBitmap(getFacebookProfilePicture(accessToken.getUserId())))

...这就是 logcat 的意思:

 java.lang.NullPointerException
                                                                 at maps.f.g.a(Unknown Source)
                                                                 at maps.ag.g$a.<init>(Unknown Source)
                                                                 at maps.ag.g.a(Unknown Source)
                                                                 at maps.ag.R.<init>(Unknown Source)
                                                                 at maps.ag.t.a(Unknown Source)

【问题讨论】:

    标签: android facebook google-maps


    【解决方案1】:

    您的错误是您没有建立实际的网络连接。您应该在加载用户的个人资料图像之前调用 URLConnection.Connect() 方法。

    try {
        URL imageURL = new URL("https://graph.facebook.com/" + userID + "/picture?type=large");
        HttpURLConnection connection = (HttpURLConnection) imageUrl.openConnection();
        connection.setDoInput(true);
        connection.connect();
        bitmap = BitmapFactory.decodeStream(connection.getInputStream());
    catch(IOException ex) {
    
    }
    

    【讨论】:

    • 哦,太好了!对于 url.openConnection();我假设您的意思是 imageURL,而不是 url。另外,我应该把它包起来试试看吗?我有 3 个警告说它应该处理 IOException 和 MalformedURL。
    • 更新我试过了,然后把它包装在 try and catch 中,我仍然遇到同样的问题:/
    • hmm...您确定您使用的是正确的图片网址吗?
    • 这也不行。我想我可能已经找到了更长的方法来做到这一点:stackoverflow.com/questions/13763545/… Gonna sleep 然后试一试。再次感谢
    • 您也可以尝试使用Picassa库下载图片:square.github.io/picasso,这个库非常好用。
    猜你喜欢
    • 2011-07-08
    • 1970-01-01
    • 2011-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多