2016-11-28 3 views
-1

페이스 북에 로그인 할 수있는 앱을 개발 중입니다. 나는 사용자 정보를 얻으려고 노력하고 내 server.i에 보내 주셔서 sdk 4.i를 사용하고 있습니다. 공유 환경 설정을 사용하여 정보를 저장하려하지만 공유 환경 설정에 대해 전혀 모릅니다. 이것은 내 페이스 북의 로그인 활동입니다. 이것은 런처 활동입니다.facebook 로그인 sdk 공유 환경 설정 및 사용자 정보 얻기

public class LoginActivity extends AbsRuntimePermission { 
private static final int REQUEST_Permission =10; 


    private TextView info; 
    private LoginButton loginButton; 
    private CallbackManager callbackManager; 
    private SparseIntArray mErrorString; 
    private Button facebook_button; 
    ProgressDialog progress; 
    private String facebook_id,f_name,m_name,l_name,gender,profile_image,full_name,email_id; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_login); 
    //for permission in manifest file cause it is launch activity 

    requestAppPermissions(new String[]{ 
      Manifest.permission.ACCESS_FINE_LOCATION, 
      Manifest.permission.ACCESS_COARSE_LOCATION, 
      Manifest.permission.CALL_PHONE, 
      Manifest.permission.INTERNET},R.string.msg,REQUEST_Permission); 

    //facebook 
    info = (TextView) findViewById(R.id.info); 
    loginButton = (LoginButton) findViewById(R.id.login_button); 
    progress = new ProgressDialog(LoginActivity.this); 
    progress.setMessage(getResources().getString(R.string.please_wait_facebooklogin)); 
    progress.setIndeterminate(false); 
    progress.setCancelable(false); 

    facebook_id=f_name=m_name=l_name=gender=profile_image=full_name=email_id=""; 

    //facebook sdk 
    FacebookSdk.sdkInitialize(getApplicationContext()); 
    callbackManager = CallbackManager.Factory.create(); 

    //register callback object for facebook result 

    LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() { 
     @Override 
     public void onSuccess(LoginResult loginResult) { 
      progress.show(); 
      Profile profile = Profile.getCurrentProfile(); 
      if(profile != null){ 
       facebook_id = profile.getId(); 
       f_name=profile.getFirstName(); 
       m_name=profile.getMiddleName(); 
       l_name=profile.getLastName(); 
       profile_image=profile.getProfilePictureUri(400,400).toString(); 
      } 
      //show Toast 
      GraphRequest request =GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(), 
        new GraphRequest.GraphJSONObjectCallback(){ 
         @Override 
         public void onCompleted(JSONObject object, GraphResponse response) { 
          try { 
           email_id = object.getString("email"); 
           gender = object.getString("gender"); 
           String Profile_name = object.getString("name"); 
           long fb_id = object.getLong("id"); //use this for logout 

           //Starting a new activity using this information 
           Intent i = new Intent(LoginActivity.this, MainActivity.class); 
           i.putExtra("type", "facebook"); 
           i.putExtra("Facebook_id", facebook_id); 
           i.putExtra("f_name", f_name); 
           i.putExtra("m_name", m_name); 
           i.putExtra("l_name", l_name); 
           i.putExtra("full_name", full_name); 
           i.putExtra("Profile_image", profile_image); 
           i.putExtra("email_id", email_id); 
           i.putExtra("gender", gender); 

           progress.dismiss(); 
           startActivity(i); 
           finish(); 

          }catch (JSONException e){ 
           e.printStackTrace(); 
          } 
         } 
        }); 
      request.executeAsync(); 
     } 

     @Override 
     public void onCancel() { 
     Toast.makeText(LoginActivity.this,getResources().getString(R.string.login_canceled_facebooklogin),Toast.LENGTH_SHORT).show(); 
     progress.dismiss(); 
     } 

     @Override 

     public void onError(FacebookException error) { 
      Toast.makeText(LoginActivity.this,getResources().getString(R.string.login_failed_facebooklogin),Toast.LENGTH_SHORT).show(); 
      progress.dismiss(); 
     } 
    }); 

    //facebook button click 
    facebook_button.setOnClickListener(new View.OnClickListener(){ 
     @Override 
     public void onClick(View view) { 
      LoginManager.getInstance().logInWithReadPermissions(LoginActivity.this, Arrays.asList("public_profile","user_friends","email")); 

     } 
    }); 
} 

private void logoutFromFacebook(){ 
    try{ 
     if(AccessToken.getCurrentAccessToken()==null){ 
      return; 
     } 

    } 
} 

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

@Override 
public void onPermissionGranted(int requestCode) { 

    //anything after permission Granted 
    Toast.makeText(getApplicationContext(),"Permission granted",Toast.LENGTH_LONG).show(); 

} 



public void goTo(View view) { 
    Intent intent = new Intent(this, MainActivity.class); 
    this.startActivity(intent); 
} 

} 의도에 가기 전에이 코드

+0

오류 로그를 공유하십시오. – Shailesh

+0

@ShaileshLimbadiya 선생님, 이제 오류를 수정했습니다 ... 이제 문제는 로그인이 완료되면 내 다음 활동으로 넘어갈 수 없으며 공유 환경 설정 (http://pastebin.com) 안에 아무 것도 저장하지 않습니다./py23Gtqf 여기 내 전체 코드를 확인하십시오. –

+0

내 대답을 확인하십시오 – Shailesh

답변

1

안드로이드 된 SharedPreferences는 더 상세 this에 따라 pair.For 우리가 키 - 값의 형태로 개인 원시적 응용 프로그램 데이터를 저장할 수 있습니다.

공유 환경 설정에서 읽으려면 다음과 같이하십시오.

String dateFromSharedPreferences=getActivity().getPreferences(Context.MODE_PRIVATE); 
sharedPref.getString("Username"); 

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE); 
    SharedPreferences.Editor editor = sharedPref.edit(); 
    editor.putString("Username", YourUsername); 
    editor.putString("Password", YourPassword); 
    editor.apply(); 

당신은 ANS는 텍스트 뷰에 표시 전달 된 값을 얻기 위해 다음과 같이 onCreate 기능에 MainActivityMainActivity 그래서 코드 LoginActivity에서 값을 전달하는 공유 환경 설정으로 저장합니다.

((TextView)findViewById(R.id.tv1)).setText(getIntent().getExtras().getString("full_name")); 
((TextView)findViewById(R.id.tv2)).setText(getIntent().getExtras().getString("email_id")); 
((TextView)findViewById(R.id.tv3)).setText(getIntent().getExtras().getString("gender")); 
+0

선생님을 확인 나에게 로그를 보내 지금 –

+0

@kuldeepraj 그래서 충돌되는이 선생님 – jafarbtech

+0

http://pastebin.com/VTE4LPQJ @jafarbtech 여기가 선생님 –

0
SharedPreferences sharedPreferences; 
SharedPreferences.Editor editor; 

쓰기.

sharedPreferences = getApplicationContext().getSharedPreferences("pref", MODE_PRIVATE); 
      editor = sharedPreferences.edit(); 
      editor.putString("User_Name", f_name); 
      editor.putString("User_Email", email_id); 
      editor.apply(); 
+1

나는이 자습서를 따라갔습니다. http://www.coders-hub.com/2014/07/how-to-add-facebook-sdk-in-android.html#.WDvxyaJ96DU –

+0

내가 왜 getFacebookId를 얻을 수 없다는 logoutFromFacebook에 나와 ??? –

+0

http://pastebin.com/VTE4LPQJ 지금 응용 프로그램은 –

0

나는이 질문에 대답을 많이하지만 여전히 나는이 질문의 답을 알고있다. 나는 도움을 얻길 바란다. 모든 데이터를 처리 할 메서드를 만드는 것이 쉽습니다. facebook JSON 객체를 받으면 다음과 같이 수행합니다. 당신이 번들에 모든 페이스 북의 데이터 저장소를 얻을 수있다 // 여기에

try { 
     Bundle bFacebookData = getFacebookData(object); 
     progressDialog.dismiss(); 
     progressDialog.cancel(); 
     setSessionData(bFacebookData); 

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

당신이

String userId = "", userEmail = "", userFirstName = "", userLastName = "", 
      userPhone = "", dateOfBirth = "", gender = "", profilePic = ""; 

    private void setSessionData(Bundle bundle) 
    { 
     try 
     { 
      userId = bundle.getString("userId"); 
      userEmail = bundle.getString("email"); 
      userFirstName = bundle.getString("first_name"); 
      userLastName = bundle.getString("last_name"); 
      userPhone = bundle.getString("phone"); 
      dateOfBirth = bundle.getString("birthday"); 
      gender = bundle.getString("gender"); 
      profilePic = bundle.getString("profile_pic"); 

      if (userId !=null) 
      { 

       SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("pref", MODE_PRIVATE); 
       SharedPreferences.Editor editor = sharedPreferences.edit(); 

       editor.putString("userId", userId); 
       editor.putString("email", userEmail); 
       editor.putString("first_name", userFirstName); 
       editor.putString("last_name", userLastName); 
       editor.putString("phone", userPhone); 
       editor.putString("birthday", dateOfBirth); 
       editor.putString("gender", gender); 
       editor.putString("profile_pic", profilePic); 

       editor.apply(); 


       Intent i = new Intent(activity, MainActivity.class); 
       i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
       i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
       activity.startActivity(i); 
      } 
      else 
      { 
       //"Some thing went wrong Please try again" 
      } 
     } 
     catch (Exception e) 
     { 
      e.printStackTrach(); 
     } 
    } 

귀하의 다른 클래스 새로운 활동을 된 SharedPreferences에 데이터를 저장하고 시작할 수 있습니다 // 여기에

private Bundle getFacebookData(JSONObject object) 
    { 
     try { 
      Bundle bundle = new Bundle(); 
      //String id = object.getString("id"); 

      try 
      { 
       URL profile_pic = new URL("https://graph.facebook.com/" + object.getString("id") + "/picture?width=200&height=150"); 
       Log.i("profile_pic", profile_pic + ""); 
       if (profile_pic.toString() != null) 
       { 
        bundle.putString("profile_pic", profile_pic.toString()); 
       } 
       else 
       { 
        bundle.putString("profile_pic", "noProfilePic"); 
       } 

      } catch (MalformedURLException e) { 
       e.printStackTrace(); 
       return null; 
      } 

      if (object.has("id")) 
      { 
       if (object.getString("id") != null) 
       { 
        bundle.putString("userId", object.getString("id")); 
        Log.i(TAG, "Info " + object.getString("id")); 
       } 
       else 
       { 
        bundle.putString("userId", "noUserId"); 
        Log.i(TAG, "Info " + object.getString("id")); 
       } 
      } 
      if (object.has("first_name")) 
      { 
       if (object.getString("first_name") != null) 
       { 
        bundle.putString("first_name", object.getString("first_name")); 
        Log.i(TAG + "Info", object.getString("first_name")); 
       } 
       else 
       { 
        bundle.putString("first_name", "noFirstName"); 
        Log.i(TAG + "Info", object.getString("first_name")); 
       } 
      } 
      if (object.has("last_name")) 
      { 
       if (object.getString("last_name") != null) 
       { 
        bundle.putString("last_name", object.getString("last_name")); 
        Log.i(TAG + "Info", object.getString("last_name")); 
       } 
       else 
       { 
        bundle.putString("last_name", "noLastName"); 
        Log.i(TAG + "Info", object.getString("last_name")); 
       } 
      } 

      if (object.has("email")) 
      { 
       if (object.getString("email") != null) 
       { 
        bundle.putString("email", object.getString("email")); 
        Log.i(TAG + "Info", object.getString("email")); 
       } 
       else 
       { 
        bundle.putString("email", "noEmail"); 
        Log.i(TAG + "Info", object.getString("email")); 
       } 
      } 


      //this is added dynamically 
      bundle.putString("phone", "noPhone"); 

      if (object.has("gender")) 
      { 
       if (object.getString("gender") != null) 
       { 
        bundle.putString("gender", object.getString("gender")); 
        Log.i(TAG + "Info", object.getString("gender")); 
       } 
       else 
       { 
        bundle.putString("gender", "noGender"); 
        Log.i(TAG + "Info", object.getString("gender")); 
       } 
      } 

      if (object.has("birthday")) 
      { 
       if (object.getString("birthday") != null) 
       { 
        bundle.putString("birthday", object.getString("birthday")); 
        Log.i(TAG + "Info", object.getString("birthday")); 
       } 
       else 
       { 
        bundle.putString("birthday", "noDateOfBirth"); 
        Log.i(TAG + "Info", object.getString("birthday")); 
       } 
      } 

      if (object.has("location")) 
      { 
       if (object.getJSONObject("location").getString("name") != null) 
       { 
        bundle.putString("location", object.getJSONObject("location").getString("name")); 
        Log.i(TAG + "Info", object.getJSONObject("location").getString("name")); 
       } 
       else 
       { 
        bundle.putString("location", "noLocation"); 
        Log.i(TAG + "Info", object.getJSONObject("location").getString("name")); 
       } 
      } 

      return bundle; 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } finally { 

     } 
     return null; 
    } 

SharedPreferences에서 데이터를 수신하는 방법

SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("pref", MODE_PRIVATE); 

((TextView)findViewById(R.id.tv1)).setText(sharedPreferences.getString("first_name", "")); 
((TextView)findViewById(R.id.tv2)).setText(sharedPreferences.getString("last_name", ""));