从Facebook会话获取用户日期? - Android

时间:2015-01-26 12:57:30

标签: android facebook android-facebook

我正在尝试从facebook会话中获取姓名和电子邮件。我想在EditText中添加这些信息。当我尝试获取这些信息时,Facebook会打开以输入我的登录名和密码,以便在此不返回信息后进行访问。

我该怎么做?

我正在尝试这个。

 public class CadUsuarioFrag extends Fragment implements View.OnClickListener, RadioGroup.OnCheckedChangeListener{

    private EditText etNome, etEmail, etSenha;
    private ImageButton ibImage;
    private Button btnSingUp;
    private String pathImage;
    private static final int RESULT_LOAD_IMAGE = 1;
    private ProgressDialog progress;
    private final String TAG = getClass().getSimpleName() + "->";

    //radiogroup
    private RadioGroup rgTipoCad;

    //
    private String nome = "";
    private String email = "";
    private String senha = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ((CustomDrawerLayout)getActivity()).getSupportActionBar().hide();
    }

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

        if (requestCode == RESULT_LOAD_IMAGE &&  resultCode == getActivity().RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            Cursor cursor = getActivity().getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            pathImage = cursor.getString(columnIndex);
            cursor.close();
        }

        Session.getActiveSession().onActivityResult(getActivity(), requestCode, resultCode, data);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.form_cadusuario, container, false);

        etNome = (EditText)view.findViewById(R.id.etNome);
        etEmail = (EditText)view.findViewById(R.id.etEmail);
        etSenha = (EditText)view.findViewById(R.id.etSenha);
        ibImage = (ImageButton)view.findViewById(R.id.ibImage);
        btnSingUp = (Button)view.findViewById(R.id.btnSingUp);
        rgTipoCad = (RadioGroup)view.findViewById(R.id.rgTipoCad);


        //listeners
        rgTipoCad.setOnCheckedChangeListener(this);
        ibImage.setOnClickListener(this);
        btnSingUp.setOnClickListener(this);
        etNome.requestFocus();


        return  view;
    }

    @Override
    public void onClick(View v) {
        if(v == ibImage){
            Intent i = new Intent(
                    Intent.ACTION_PICK,
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(i, RESULT_LOAD_IMAGE);
        }else if(v == btnSingUp){
            if(checkFields()){
                addUsuario();
            }
        }
    }

    /** verifica se todos os campos foram informados para o insert */
    private boolean checkFields(){
        nome = etNome.getText().toString().trim();
        email = etEmail.getText().toString().trim();
        senha = etSenha.getText().toString().trim();
        int selected = rgTipoCad.getCheckedRadioButtonId();
        if(nome.length() == 0 || email.length() == 0 || senha.length() == 0){
            Toast.makeText(getView().getContext(), "Informe todos os campos", Toast.LENGTH_SHORT).show();
            etNome.requestFocus();
            etNome.selectAll();
            return false;
        }else{
            return true;
        }
    }

    private void addUsuario(){
        progress = new CustomProgressDialog().getCustomProgress(null, getView().getContext());
        progress.show();
        Usuario u = new Usuario(nome, email, senha, "1");
        JsonObjectRequest app = new UsuarioDAO().addUsuario(u, new UsuarioAdapter(){
            @Override
            public void onUsuarioCadastrado(Boolean value) {
                if(!value){
                    Toast.makeText(getView().getContext(), "Usuário não cadastrado", Toast.LENGTH_SHORT).show();
                }else{
                    sucesso();
                }
                progress.dismiss();
            }
        });
        CustomVolleySingleton.getInstance(getView().getContext()).addToRequestQueue(app);
    }


    private void sucesso(){
        AlertDialog.Builder alert = new AlertDialog.Builder(getView().getContext());
        alert.setTitle("Guia Store");
        alert.setMessage("Obrigado por se cadastrar\nEfetue agora seu login para acesso");
        alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                FragmentTransaction ft;
                Fragment frag;
                frag = new LoginFrag();
                ft = getFragmentManager().beginTransaction();
                ft.replace(R.id.fl, frag, "InicioFrag");
                ft.commit();
                removeFrag();
            }
        });
        AlertDialog dialog = alert.create();
        dialog.show();
    }





    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        if(checkedId == R.id.rbGuiaStore){
            //Log.i(TAG, "rbGuiaStore selecionado");
            etNome.setHint("Nome");
            etEmail.setHint("Email");
            etSenha.setHint("Senha");
            etNome.requestFocus();
        }else{
            //Log.i(TAG, "rbFacebook selecionado");
            etNome.setHint("Nome");
            etEmail.setHint("Email facebook");
            etSenha.setHint("Senha facebook");
            etNome.requestFocus();
            checkFacebookSession();
        }
    }



    private void checkFacebookSession(){
        // start Facebook Login
        Session.openActiveSession(getActivity(), true, new Session.StatusCallback() {

            // callback when session changes state
            @Override
            public void call(Session session, SessionState state, Exception exception) {
                if (session.isOpened()) {
                    // make request to the /me API
                    Request.newMeRequest(session, new Request.GraphUserCallback() {

                        // callback after Graph API response with user object
                        @Override
                        public void onCompleted(GraphUser user, Response response) {
                            if (user != null) {
                                Toast.makeText(getView().getContext(), user.getName(), Toast.LENGTH_SHORT).show();
                                etNome.setText(user.getName());
                                Log.i("usuario", user.getName());
                            }
                        }
                    }).executeAsync();
                }
            }
        });
    }






    /** remove o fragment da fila */
    private void removeFrag(){
        getActivity().getSupportFragmentManager().popBackStack();
        //getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onStop() {
        super.onStop();
        CustomVolleySingleton.getInstance(getView().getContext()).cancelPendingRequests(CustomVolleySingleton.TAG);
    }


}

1 个答案:

答案 0 :(得分:1)

您可以执行以下操作。

 Request.newMeRequest(session, new Request.GraphUserCallback()
        {
            @Override
            public void onCompleted(GraphUser user, Response response)
            {
                if (response != null)
                {
                    try
                    {
                        String name = user.getName();
                        String email = (String) user.getProperty("email");
                        Log.e(LOG_TAG, "Name: " + name + " Email: " + email);
                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                    }

                }
            }
        }).executeAsync();

P.S。应在运行此请求之前打开会话。您可以通过sessionState方法检查isOpened()