FacebookConnect代号为api

时间:2017-03-09 13:36:25

标签: java android codenameone hybrid-mobile-app

我正在尝试从Facebook获取数据,在执行时应用程序可以从Facebook获取数据,但是当我试图动态地将Facebook个人资料图片设置为用户图片时,它会抛出错误,我不知道是什么我的代码错了.. 以下是我的代码

        Form facebook = new Form("Facebook", new BoxLayout(BoxLayout.Y_AXIS));
        Toolbar tb = new Toolbar();
        facebook.setToolbar(tb);

       user = theme.getImage("user.png");
        Label userLabel = new Label(user);
        username = new Label("Visitor");
        Button login = new Button("Login");

        login.addActionListener((evt) -> {
             String clientId = "158093724691158";
            String redirectURI = "http://www.codenameone.com/";
            String clientSecret = "eca942518c753053dd0adeff93ad78c3";
            fb = FacebookConnect.getInstance();
            fb.setClientId(clientId);
            fb.setRedirectURI(redirectURI);
            fb.setClientSecret(clientSecret);
            Log.p("login event triggered");
            doLogin(fb, new FacebookData(), false);
        });

        facebook.show();

    }

  void processFacebookLogin(UserData data){
       Log.p("First NAme : " + data.getFirstName());
                Log.p("Last Name : " + data.getLastName());
       Log.p("Email : " + data.getEmail());
        Log.p("Full Name : " + data.getFullName());
          Log.p("Gender : " + data.getGender());
           Log.p("Id : " + data.getId());
            Log.p("Link : " +data.getLink());
             Log.p("Locale : " +data.getLocale());
             Log.p("Time-Zone : " +data.getTimezone());
             Log.p("Pcture : " +data.getImage());
             Log.p("Updated Time : " + data.getUpdatedTime());
             Log.p("Story" + data.getStory());
             username.setText(data.getFullName());
  user = (EncodedImage)  Image. createImage(data. getImage()) ;  //here i am trying to set facebook user profile picture 

           }

    void doLogin(Login lg, UserData data, boolean forceLogin) {
    if (!forceLogin) {
        if (lg.isUserLoggedIn()) {
            processFacebookLogin(data);
            new FacebookData();
            return;
        }

        // if the user already logged in previously and we have a token
        String token = Preferences.get(tokenPrefix + "token", (String) null);
     /*   if (getToolbar() != null) {
            // we check the expiration of the token which we previously stored as System time
            long tokenExpires = Preferences.get(tokenPrefix + "tokenExpires", (long) -1);
            if (tokenExpires < 0 || tokenExpires > System.currentTimeMillis()) {

                data.fetchData(token, () -> {
                    processFacebookLogin(data);
                });
                return;
            }
        } */
    }

    lg.setCallback(new LoginCallback() {
                @Override
        public void loginFailed(String errorMessage) {
            Dialog.show("Error Logging In", "There was an error logging in with Facebook: " + errorMessage, "Ok", null);
        }

        @Override
        public void loginSuccessful() {
            data.fetchData(lg.getAccessToken().getToken(), () -> {
                Preferences.set(tokenPrefix + "token", lg.getAccessToken().getToken());
                Preferences.set(tokenPrefix + "tokenExpires", tokenExpirationInMillis(lg.getAccessToken()));
                processFacebookLogin(data);
            });
        }
});
    lg.doLogin();
}

long tokenExpirationInMillis(AccessToken token) {
    String expires = token.getExpires();
    if (expires != null && expires.length() > 0) {
        try {
            // when it will expire in seconds
            long l = (long) (Float.parseFloat(expires) * 1000);
            return System.currentTimeMillis() + l;
        } catch (NumberFormatException err) {
            // ignore invalid input
        }
    }
    return -1;
}

static interface UserData{
    public String getId();
     public String getEmail();
      public String getFullName();
       public String getFirstName();
        public String getLastName();
         public String getGender();
          public String getLink();
           public String getLocale();
            public Double getTimezone();
            public String getUpdatedTime();
            public String getImage();
            public String getStory();
                public void fetchData(String token, Runnable callback);
    }


class FacebookData implements UserData {

    String id;
    String email;
    String name;
    String first_name;
    String last_name;
    String image;
    String link;
    String gender;
    String locale;
    Double timezone;
    String updated_time;
    String verified;
    String story;

    @Override
    public String getId() {
        return id;
    }

    @Override
    public String getEmail() {
        return email;
    }

    @Override
    public String getFullName() {
        return name;
    }

    @Override
    public String getFirstName() {
        return first_name;
    }

    @Override
    public String getLastName() {
        return last_name;
    }

    @Override
    public String getGender() {
        return gender;
    }

    @Override
    public String getLink() {
        return link;
    }

    @Override
    public String getLocale() {
        return locale;
    }

    @Override
    public Double getTimezone() {
        return timezone;
    }

    @Override
    public String getUpdatedTime() {
        return updated_time;
    }

    @Override
    public String getImage() {
        return image;
    }

    @Override
    public String getStory() {
        return story;
    }

    @Override
    public void fetchData(String token, Runnable callback) {
        ConnectionRequest req = new ConnectionRequest() {
            @Override
            protected void readResponse(InputStream input) throws IOException {
                JSONParser parser = new JSONParser();
                Map<String, Object> parsed = parser.parseJSON(new InputStreamReader(input, "UTF-8"));
                id = (String) parsed.get("id");
                email = (String) parsed.get("email");
                name = (String) parsed.get("name");
                first_name = (String) parsed.get("first_name");
                last_name = (String) parsed.get("last_name");
                link = (String) parsed.get("link");
                gender = (String) parsed.get("gender");
                locale = (String) parsed.get("locale");
                timezone = (Double) parsed.get("timezone");
                updated_time = (String) parsed.get("updated_time;");
                verified = (String) parsed.get("verified");
                image = (String) ((Map) ((Map) parsed.get("picture")).get("data")).get("url").toString();
                story = (String) ((Map) ((Map)parsed.get("posts")).get("data")).get("story").toString();
            }

            @Override
            protected void postResponse() {
                callback.run();
            }

            @Override
            protected void handleErrorResponseCode(int code, String message) {
                //access token not valid anymore
                if (code >= 400 && code <= 410) {
                    doLogin(FacebookConnect.getInstance(), FacebookData.this, true);
                    return;
                }
                super.handleErrorResponseCode(code, message);
            }
        };
        req.setPost(false);
        req.setUrl("https://graph.facebook.com/v2.8/me");
        req.addArgumentNoEncoding("access_token", token); //this statement is used to patch access token with url
        req.addArgumentNoEncoding("fields", "id,email,name,first_name,last_name,gender,age_range,picture.width(512).height(512),locale,link,timezone,updated_time,posts.limit(10)");
        //above statement is used to provide permission through url so server send data with respect ot permissions.
        NetworkManager.getInstance().addToQueue(req);
    }
}

    public void stop() {
        current = Display.getInstance().getCurrent();
        if(current instanceof Dialog) {
            ((Dialog)current).dispose();
            current = Display.getInstance().getCurrent();
        }
    }

    public void destroy() {
    }

}

1 个答案:

答案 0 :(得分:2)

您必须使用URLImage来解决这个问题:

更改此行:

user = (EncodedImage)  Image. createImage(data. getImage()) ;

if (data.getImage() != null) {
    EncodedImage encImage = EncodedImage.createFromImage(user.getIcon(), true);
    Display.getInstance().callSerially(() -> {
        user.setIcon(URLImage.createToStorage(encImage, data.getImage(), data.getImage(), null));
        user.getComponentForm().repaint();
    });
}