Facebook sdk个人资料信息无法正常使用

时间:2016-01-23 11:56:56

标签: android facebook android-layout facebook-graph-api

我将facebook sdk集成到我的应用程序中,它工作得很好,但我的问题是 当我第一次运行我的项目登录成功但用户数据没有得到它甚至数据显示在吐司但不显示在滑动抽屉。

然后我自动重启app数据集。请帮帮我这是我的代码

首先运行启动画面

Splash.java

public class Splash extends Activity {

//Give your SharedPreferences file a name and save it to a static variable
public static  String PREFS_NAME = "Login";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.splashh);

    final ImageView iv = (ImageView) findViewById(R.id.imageView);
    final Animation an = AnimationUtils.loadAnimation(getBaseContext(),R.anim.rotate);
    final Animation an2 = AnimationUtils.loadAnimation(getBaseContext(),R.anim.abc_fade_out);

    iv.startAnimation(an);
    an.setAnimationListener(new Animation.AnimationListener() {
        @Override
        public void onAnimationStart(Animation animation) {

        }

        @Override
        public void onAnimationEnd(Animation animation) {
            iv.startAnimation(an2);
            finish();
            Intent i = new Intent(getBaseContext(),Login.class);
            startActivity(i);
        }

        @Override
        public void onAnimationRepeat(Animation animation) {

        }
    });
}

然后登录页面

Login.java

public class Login extends AppCompatActivity {
TextView tv_sign_up;
private EditText inputName, inputEmail, input_contact_no, input_address, input_city;
private TextInputLayout inputLayoutName, inputLayoutEmail, input_layout_city, input_layout_contact_no, input_layout_address;
private Button btnSignUp;
private CallbackManager callbackManager;
public static String FEmail;
private AccessTokenTracker accessTokenTracker;
public static ProfileTracker profileTracker;
public static String Name, Email, ImgURL, FbID;

static SharedPreferences settings;

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

    settings = getSharedPreferences(Splash.PREFS_NAME, 0);
    boolean hasLoggedIn = settings.getBoolean("hasLoggedIn", false);


    if (hasLoggedIn) {
        Intent intent = new Intent(getApplicationContext(), MainActivity.class);
        startActivity(intent);
    }

    FacebookCall();

    Loaduielements();

    LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
    loginButton.setReadPermissions(Arrays.asList("public_profile, email, user_birthday, user_friends"));
    loginButton.registerCallback(callbackManager, callback);

    btnSignUp.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            submitForm();
        }
    });
}

private void FacebookCall() {

    FacebookSdk.sdkInitialize(getApplicationContext().getApplicationContext());

    showHashKey(getApplicationContext());
    callbackManager = CallbackManager.Factory.create();

    accessTokenTracker = new AccessTokenTracker() {
        @Override
        protected void onCurrentAccessTokenChanged(AccessToken oldToken, AccessToken newToken) {

        }
    };

    profileTracker = new ProfileTracker() {
        @Override
        protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) {
            displayMessage(newProfile);
        }
    };

    accessTokenTracker.startTracking();
    profileTracker.startTracking();
    setContentView(R.layout.login);

}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    callbackManager.onActivityResult(requestCode, resultCode, data);

}

@Override
public void onStop() {
    super.onStop();
    accessTokenTracker.stopTracking();
    profileTracker.stopTracking();
}

@Override
public void onResume() {
    super.onResume();
    Profile profile = Profile.getCurrentProfile();
    displayMessage(profile);
}

public static void showHashKey(Context context) {
    try {
        PackageInfo info = context.getPackageManager().getPackageInfo(
                "com.example.tryitonjewelry", PackageManager.GET_SIGNATURES); //Your            package name here
        for (Signature signature : info.signatures) {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            Log.i("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
        }
    } catch (PackageManager.NameNotFoundException e) {
    } catch (NoSuchAlgorithmException e) {
    }
}

private void displayMessage(Profile profile) {

    if (profile != null) {

        FbID = profile.getId();

        try {

            Name=profile.getName();
            FbID = profile.getId();
            ImgURL = "https://graph.facebook.com/" + FbID + "/picture?type=large";
            SharedClass.setDefaults("ImgURL", "" + ImgURL, this);

        } catch (NetworkOnMainThreadException e) {

            e.printStackTrace();
        } catch (Exception e) {

            e.printStackTrace();
        }

    }

}

private FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
    @Override
    public void onSuccess(LoginResult loginResult) {
        AccessToken accessToken = loginResult.getAccessToken();
        Profile profile = Profile.getCurrentProfile();

        // Facebook Email address
        GraphRequest request = GraphRequest.newMeRequest(
                loginResult.getAccessToken(),
                new GraphRequest.GraphJSONObjectCallback() {
                    @Override
                    public void onCompleted(
                            JSONObject object,
                            GraphResponse response) {
                        Log.v("LoginActivity Response ", response.toString());

                        try {
                            Name = object.getString("name");
                            SharedClass.setDefaults("Name", "" + Name, getApplicationContext());
                            FEmail = object.getString("email");
                            Log.v("Email = ", " " + FEmail);
                            Toast.makeText(getApplicationContext(), "Name " + Name, Toast.LENGTH_LONG).show();
                            SharedClass.setDefaults("Email", "" + FEmail, getApplicationContext());

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
        Bundle parameters = new Bundle();
        parameters.putString("fields", "id,name,email,gender, birthday");
        request.setParameters(parameters);
        request.executeAsync();

        displayMessage(profile);

        Intent intent = new Intent(getApplicationContext(), MainActivity.class);
        startActivity(intent);
        finish();

        SharedPreferences settings = getSharedPreferences(Splash.PREFS_NAME, 0); // 0 - for private mode
        SharedPreferences.Editor editor = settings.edit();

        editor.putBoolean("hasLoggedIn", true);

        editor.commit();

    }

    @Override
    public void onCancel() {
        LoginManager.getInstance().logOut();

    }

    @Override
    public void onError(FacebookException e) {

    }
};

private void Loaduielements() {

    inputLayoutEmail = (TextInputLayout) findViewById(R.id.input_layout_email);
    input_layout_contact_no = (TextInputLayout) findViewById(R.id.input_layout_contact_no);

    tv_sign_up = (TextView) findViewById(R.id.tv_sign_up);
    inputEmail = (EditText) findViewById(R.id.input_email);
    input_contact_no = (EditText) findViewById(R.id.input_contact_no);

    btnSignUp = (Button) findViewById(R.id.btn_signup);

    inputEmail.addTextChangedListener(new MyTextWatcher(inputEmail));
    input_contact_no.addTextChangedListener(new MyTextWatcher(input_contact_no));

    settings = getSharedPreferences(Splash.PREFS_NAME, 0);
    boolean hasLoggedIn = settings.getBoolean("hasLoggedIn", false);


    if (hasLoggedIn) {
        Intent intent = new Intent(getApplicationContext(), MainActivity.class);
        startActivity(intent);
    }
}

public void Sign_Up_Clicked(View view) {
    Animation fadeout = AnimationUtils.loadAnimation(getApplicationContext(), android.R.anim.fade_out);
    tv_sign_up.startAnimation(fadeout);
    tv_sign_up.setTextColor(Color.parseColor("#F7A305"));
    Intent r = new Intent(getApplicationContext(), Register.class);
    startActivity(r);

}

/**
 * Validating form
 */
private void submitForm() {
    if (!validateEmail()) {
        return;
    }
    /*if (!validateName()) {
        return;
    }*/

    if (!contactnumber()) {
        return;
    }
    /*if (!address()) {
        return;
    }
    if (!city()) {
        return;
    }*/

    Intent i = new Intent(getApplicationContext(), MainActivity.class);
    startActivity(i);
    finish();

    SharedPreferences settings = getSharedPreferences(Splash.PREFS_NAME, 0); // 0 - for private mode
    SharedPreferences.Editor editor = settings.edit();

    editor.putBoolean("hasLoggedIn", true);

    editor.commit();
}

private boolean validateEmail() {
    String email = inputEmail.getText().toString().trim();

    if (email.isEmpty() || !isValidEmail(email)) {
        inputLayoutEmail.setError(getString(R.string.err_msg_email));
        requestFocus(inputEmail);
        return false;
    } else {
        inputLayoutEmail.setErrorEnabled(false);
    }

    return true;
}


private boolean contactnumber() {
    if (input_contact_no.getText().toString().trim().isEmpty()) {
        input_layout_contact_no.setError(getString(R.string.err_msg_contact_no));
        requestFocus(input_contact_no);
        return false;
    } else {
        input_layout_contact_no.setErrorEnabled(false);
    }
    return true;
}


private static boolean isValidEmail(String email) {
    return !TextUtils.isEmpty(email) && android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}

private void requestFocus(View view) {
    if (view.requestFocus()) {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    }
}

private class MyTextWatcher implements TextWatcher {

    private View view;

    private MyTextWatcher(View view) {
        this.view = view;
    }

    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }

    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }

    public void afterTextChanged(Editable editable) {
        switch (view.getId()) {
        /*  case R.id.input_name:
                validateName();
                break;*/
            case R.id.input_email:
                validateEmail();
                break;
            case R.id.input_contact_no:
                contactnumber();
                break;
            /*case R.id.input_address:
                address();
                break;
            case R.id.input_city:
                city();
                break;*/

        }
    }
}

}

如果登录成功,则转到MainActivity(导航抽屉).java

MainActivity.java

public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener {

private static String TAG = MainActivity.class.getSimpleName();

private Toolbar mToolbar;
private FragmentDrawer drawerFragment;
public Button Yes, No;
public Dialog dialog;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mToolbar = (Toolbar) findViewById(R.id.toolbar);

    setSupportActionBar(mToolbar);
    getSupportActionBar().setDisplayShowHomeEnabled(true);

    drawerFragment = (FragmentDrawer)
            getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
    drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
    drawerFragment.setDrawerListener(this);

    displayView(0);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return false;
}

@Override
public void onDrawerItemSelected(View view, int position) {
    displayView(position);
}

private void displayView(int position) {
    Fragment fragment = null;
    String title = getString(R.string.app_name);
    switch (position) {
        case 0:
            fragment = new HomeFragment();

            title = getString(R.string.title_home);
            break;
        case 1:
            fragment = new FriendsFragment();
            title = getString(R.string.title_weekly_order);
            break;
        case 2:

            fragment = new PriceListFrgment();
            title = getString(R.string.title_pricelist);
            break;
        case 3:
            fragment = new MessagesFragment();
            title = getString(R.string.title_support);
            break;
        case 4:
            fragment = new MessagesFragment();
            title = getString(R.string.title_setting);
            break;
        case 5:

            try {
                dialog = new Dialog(MainActivity.this, R.style.PauseDialog);
                dialog.setContentView(R.layout.custom_dialog);
                dialog.setTitle("Quit");

                TextView text = (TextView) dialog.findViewById(R.id.textDialog);
                text.setText("ARE YOU SURE WANT TO LOG OUT?");
                dialog.show();

                Yes = (Button) dialog.findViewById(R.id.btn_dialog_Yes);
                Yes.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        Login.settings.edit().clear().commit();
                        LoginManager.getInstance().logOut();
                        Intent intent = new Intent(getApplicationContext(), Login.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);

                    }
                });

                No = (Button) dialog.findViewById(R.id.btn_dialog_no);
                No.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });

                title = getString(R.string.title_logout);
            } catch (Exception e) {
                e.printStackTrace();
            }

            break;
        default:
            break;
    }

    if (fragment != null) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.container_body, fragment);
        fragmentTransaction.commit();

        getSupportActionBar().setTitle(title);
    }
}

@Override
public void onBackPressed() {
/*    super.onBackPressed();*/
}

}

如果有人帮助我,我会非常高兴。提前谢谢

0 个答案:

没有答案