2017-01-02 42 views
0

我正在創建一個登錄頁面,用戶可以選擇如果他們點擊按鈕(f繼續facebook),他們可以通過Facebook登錄,登錄後,他們可以進入下一頁。 在這裏我已經把登錄代碼與pagebook,它也問我facebook的密碼也。問題是,登錄後,它的遺體仍然在同一頁。如果我登錄一次,然後下一次它不會問我的密碼Facebook並保持在同一頁面上。如何使用android登錄Facebook後轉到下一頁?

這裏是我的Login.java代碼:

public class Login extends AppCompatActivity { 
    private String eml; 
    private String pswrd; 
    private ProfileTracker mProfileTracker; 
    private ProgressDialog pDialog; 
    String status = ""; 
    private Button fbbutton; 
    Profile profile; 
    Button login; 

    // private int serverResponseCode = 0; 
    TextView tac1; 
    EditText email, pass; 
    private static String url_create_book = "http://cloud.....com/broccoli/login.php"; 
    public static CallbackManager callbackmanager; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     FacebookSdk.sdkInitialize(getApplicationContext()); 
     setContentView(R.layout.activity_login); 
     Get_hash_key(); 
     Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
     setSupportActionBar(toolbar); 
     getSupportActionBar().setDisplayHomeAsUpEnabled(true); 
     AppEventsLogger.activateApp(this); 

     fbbutton = (Button) findViewById(R.id.fbtn); 

     fbbutton.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       // Call private method 
       onFblogin(); 
      } 
     }); 

     email = (EditText)findViewById(R.id.email); 
     pass = (EditText) findViewById(R.id.password); 

     tac1 = (TextView)findViewById(R.id.cAcc); 

     tac1.setOnClickListener(new View.OnClickListener() 

           { 

            @Override 
            public void onClick(View v) { 


             startActivity(new Intent(Login.this, RegistrationForm.class)); 


            } 
           } 

     ); 

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


       pDialog = new ProgressDialog(Login.this); 
       pDialog.setMessage("Please wait.."); 
       pDialog.setIndeterminate(false); 
       pDialog.setCancelable(true); 
       pDialog.show(); 
       eml = email.getText().toString(); 
       pswrd = pass.getText().toString(); 


       // new CreateNewProduct().execute(); 
       StringRequest stringRequest = new StringRequest(Request.Method.POST, url_create_book, 
         new Response.Listener<String>() { 
          @Override 
          public void onResponse(String response) { 
           pDialog.dismiss(); 
           if (response.trim().equals("success")) { 
            Toast.makeText(Login.this, "Login Success", Toast.LENGTH_SHORT).show(); 

            //your intent code here 
           } else { 
            Toast.makeText(Login.this, "username/password incorrect", Toast.LENGTH_SHORT).show(); 

           } 
          } 
         }, 
         new Response.ErrorListener() { 
          @Override 
          public void onErrorResponse(VolleyError error) { 
           pDialog.dismiss(); 
           Toast.makeText(Login.this, error.toString(), Toast.LENGTH_LONG).show(); 
          } 
         }) { 
        @Override 
        protected Map<String, String> getParams() { 
         Map<String, String> params = new HashMap<String, String>(); 
         params.put("email", eml); 
         params.put("password", pswrd); 

         return params; 
        } 
       }; 
       RequestQueue requestQueue = Volley.newRequestQueue(Login.this); 
       requestQueue.add(stringRequest); 

      } 

     }); 
    } 


    public void Get_hash_key() { 
     PackageInfo info; 
     try { 
      info = getPackageManager().getPackageInfo("com.example.zeba.broccoli", PackageManager.GET_SIGNATURES); 
      for (Signature signature : info.signatures) { 
       MessageDigest md; 
       md = MessageDigest.getInstance("SHA"); 
       md.update(signature.toByteArray()); 
       String something = new String(Base64.encode(md.digest(), 0)); 
       //String something = new String(Base64.encodeBytes(md.digest())); 
       Log.e("hash key", something); 
      } 
     } catch (PackageManager.NameNotFoundException e1) { 
      Log.e("name not found", e1.toString()); 
     } catch (NoSuchAlgorithmException e) { 
      Log.e("no such an algorithm", e.toString()); 
     } catch (Exception e) { 
      Log.e("exception", e.toString()); 
     } 
    } 




    private void onFblogin() { 
     callbackmanager = CallbackManager.Factory.create(); 

     // Set permissions 
     LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("email", "user_photos", "public_profile")); 

     LoginManager.getInstance().registerCallback(callbackmanager, 
       new FacebookCallback<LoginResult>() { 
        @Override 
        public void onSuccess(LoginResult loginResult) { 
         try { 
          if (Profile.getCurrentProfile() == null) { 
           mProfileTracker = new ProfileTracker() { 
            @Override 
            protected void onCurrentProfileChanged(Profile profile_old, Profile profile_new) { 
             // profile2 is the new profile 
             profile = profile_new; 
             mProfileTracker.stopTracking(); 
            } 
           }; 
           mProfileTracker.startTracking(); 
          } else { 
           profile = Profile.getCurrentProfile(); 
          } 

          GraphRequest request = GraphRequest.newMeRequest(
            loginResult.getAccessToken(), 
            new GraphRequest.GraphJSONObjectCallback() { 
             @Override 
             public void onCompleted(JSONObject object, GraphResponse response) { 
              Log.v("FACEBOOK LOGIN", response.toString()); 
              // Application code 
              try { 
               String fb_id = object.getString("id"); 
               String fb_name = object.getString("name"); 
               String profilePicUrl = "https://graph.facebook.com/" + fb_id + "/picture?width=200&height=200"; 
               String fb_gender = object.getString("gender"); 
               String fb_email = object.getString("email"); 
               String fb_birthday = object.getString("birthday"); 
              } catch (JSONException e) { 
               e.printStackTrace(); 
              } 

              //use shared preferences here 
             } 
            }); 
          Bundle parameters = new Bundle(); 
          parameters.putString("fields", "id,name,email,gender,birthday,picture.type(small)"); 
          request.setParameters(parameters); 
          request.executeAsync(); 

          //go to Home page 
          Intent intent = new Intent(getApplicationContext(), Home.class); 
          intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
          startActivity(intent); 
          finish(); 
         } catch (Exception e) { 
          Log.d("ERROR", e.toString()); 
         } 
        } 

        @Override 
        public void onCancel() { 
         // Log.d(TAG_CANCEL, "On cancel"); 
        } 

        @Override 
        public void onError(FacebookException error) { 
         //Log.d(TAG_ERROR, error.toString()); 
        } 
       }); 
    } 



    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     switch (item.getItemId()) { 
      case android.R.id.home: 
       onBackPressed(); 
       return true; 
      default: 
       return super.onOptionsItemSelected(item); 
     } 
    } 

} 
+0

我想你想添加這一行'startActivity(new Intent(Login.this,Home.class));'在這種情況下'if(response.trim()。equals(「success」)){' –

+0

但是這很好,我可以添加tht,但我需要做的意圖f按鈕...我試圖把意圖thr,但其nt工作 –

+0

是有任何logcat錯誤?? onSuccess()方法調用? – rafsanahmad007

回答

1

有幾個代碼中的問題:你是發起fb_login方法你正常登錄......在onsuccess()方法

你也需要申請permisssion程序來檢索用戶詳細信息...

試試下面的代碼:

聲明變量

private ProfileTracker mProfileTracker; 
Profile profile; 

在你的onCreate()代替:

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    FacebookSdk.sdkInitialize(getApplicationContext()); 
    setContentView(R.layout.activity_login); 
    Get_hash_key(); 
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
    setSupportActionBar(toolbar); 
    getSupportActionBar().setDisplayHomeAsUpEnabled(true); 
    AppEventsLogger.activateApp(this); 

    fbbutton = (Button) findViewById(R.id.fbtn); 

    fbbutton.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      // Call private method 
      onFblogin(); 
     } 
    }); 

    email = (EditText)findViewById(R.id.email); 
    pass = (EditText) findViewById(R.id.password); 

    tac1 = (TextView)findViewById(R.id.cAcc); 

    tac1.setOnClickListener(new View.OnClickListener() 

          { 

           @Override 
           public void onClick(View v) { 


            startActivity(new Intent(Login.this, RegistrationForm.class)); 


           } 
          } 

    ); 

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


      pDialog = new ProgressDialog(Login.this); 
      pDialog.setMessage("Please wait.."); 
      pDialog.setIndeterminate(false); 
      pDialog.setCancelable(true); 
      pDialog.show(); 
      eml = email.getText().toString(); 
      pswrd = pass.getText().toString(); 


      // new CreateNewProduct().execute(); 
      StringRequest stringRequest = new StringRequest(Request.Method.POST, url_create_book, 
        new Response.Listener<String>() { 
         @Override 
         public void onResponse(String response) { 
          pDialog.dismiss(); 
          if (response.trim().equals("success")) { 
           Toast.makeText(Login.this, "Login Success", Toast.LENGTH_SHORT).show(); 

          //your intent code here 
          } else { 
           Toast.makeText(Login.this, "username/password incorrect", Toast.LENGTH_SHORT).show(); 

          } 
         } 
        }, 
        new Response.ErrorListener() { 
         @Override 
         public void onErrorResponse(VolleyError error) { 
          pDialog.dismiss(); 
          Toast.makeText(Login.this, error.toString(), Toast.LENGTH_LONG).show(); 
         } 
        }) { 
       @Override 
       protected Map<String, String> getParams() { 
        Map<String, String> params = new HashMap<String, String>(); 
        params.put("email", eml); 
        params.put("password", pswrd); 

        return params; 
       } 
      }; 
      RequestQueue requestQueue = Volley.newRequestQueue(Login.this); 
      requestQueue.add(stringRequest); 

     } 

    }); 
} 
在fb_login方法

而且替換:

// Private method to handle Facebook login and callback 
private void onFblogin() { 
    callbackmanager = CallbackManager.Factory.create(); 

    // Set permissions 
    LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("email", "user_photos", "public_profile")); 

    LoginManager.getInstance().registerCallback(callbackmanager, 
      new FacebookCallback<LoginResult>() { 
       @Override 
    public void onSuccess(LoginResult loginResult) { 
     try { 
      if (Profile.getCurrentProfile() == null) { 
       mProfileTracker = new ProfileTracker() { 
        @Override 
        protected void onCurrentProfileChanged(Profile profile_old, Profile profile_new) { 
         // profile2 is the new profile 
         profile = profile_new; 
         mProfileTracker.stopTracking(); 
        } 
       }; 
       mProfileTracker.startTracking(); 
      } else { 
       profile = Profile.getCurrentProfile(); 
      } 

      GraphRequest request = GraphRequest.newMeRequest(
        loginResult.getAccessToken(), 
        new GraphRequest.GraphJSONObjectCallback() { 
         @Override 
         public void onCompleted(JSONObject object, GraphResponse response) { 
          Log.v("FACEBOOK LOGIN", response.toString()); 
          // Application code 
          try { 
           String fb_id = object.getString("id"); 
           String fb_name = object.getString("name"); 
           String profilePicUrl = "https://graph.facebook.com/" + fb_id + "/picture?width=200&height=200"; 
           String fb_gender = object.getString("gender"); 
           String fb_email = object.getString("email"); 
           String fb_birthday = object.getString("birthday"); 
          } catch (JSONException e) { 
           e.printStackTrace(); 
          } 

          //use shared preferences here 
         } 
        }); 
      Bundle parameters = new Bundle(); 
      parameters.putString("fields", "id,name,email,gender,birthday,picture.type(small)"); 
      request.setParameters(parameters); 
      request.executeAsync(); 

      //go to Home page 
      Intent intent = new Intent(getApplicationContext(), Home_page.class); 
      intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
      startActivity(intent); 
      finish(); 
     } catch (Exception e) { 
      Log.d("ERROR", e.toString()); 
     } 
    } 

     @Override 
     public void onCancel() { 
     // Log.d(TAG_CANCEL, "On cancel"); 
     } 

     @Override 
     public void onError(FacebookException error) { 
     //Log.d(TAG_ERROR, error.toString()); 
     } 
    }); 
} 
+0

好的,讓我試試這個......但是,什麼ABT共享偏好..它是必要的? –

+0

取決於您的應用程序..如果用戶關閉應用程序,下一次他們不得不再次登錄而不需要sharedpreference ... – rafsanahmad007

+0

我m在配置文件上報錯,它說不能解析配置文件 –

0

在成功保存了所有需要的細節,你共享偏好,之後啓動主要活動。在重新啓動應用程序檢查您的共享首選項值在啓動畫面(第一個屏幕打開時,有人啓動應用程序)如果細節已經存在,然後直接去主要活動而不是登錄屏幕

+0

對不起,沒有...我有主頁,如果我點擊imageview它會去登錄activity..can你告訴我通過編碼 –

+0

你有主頁讓你登錄活動的用戶,然後如果fb登錄成功,你把他帶到其他活動。如果用戶下次打開應用程序,他應該直接進入其他活動? – Spartan

+0

是的,它也可以罰款..但我在哪裏我錯了我的代碼? –

0

大家好我得到了答案,首先我做了錯誤的把FacebookSdk.sdkInitialize(getApplicationContext())的; AFTER setContentView(R.layout.activity_login); 它應該在那之前..我是我的活動沒有回到主頁

相關問題