Java 片段中的google plus signinbutton显示null pointerexception onclick

Java 片段中的google plus signinbutton显示null pointerexception onclick,java,android,facebook,google-plus,Java,Android,Facebook,Google Plus,我想通过Google Plus和facebook登录我的应用程序。我得到空指针异常。我搜索并尝试了所有可能的方法。 我不知道代码有什么问题。请帮我做这个 这是MainActivity.java import com.facebook.AccessToken; import com.facebook.AccessTokenTracker; import com.facebook.CallbackManager; import com.facebook.FacebookCallback; impor

我想通过Google Plus和facebook登录我的应用程序。我得到空指针异常。我搜索并尝试了所有可能的方法。 我不知道代码有什么问题。请帮我做这个

这是MainActivity.java

import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.Profile;
import com.facebook.ProfileTracker;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.SignInButton;

 import com.google.android.gms.common.api.GoogleApiClient;
 import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.plus.Plus;
import com.google.android.gms.plus.model.people.Person;
import com.saloon.callbacks.LoadProfileImage;

import android.support.v7.app.AppCompatActivity;
import android.support.v4.app.Fragment;
import android.content.Intent;
 import android.content.IntentSender.SendIntentException;
import android.os.Bundle;
 import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new MapFragment()).commit();
    }
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class MapFragment extends Fragment implements    View.OnClickListener,
ConnectionCallbacks, OnConnectionFailedListener
{   private static final int RC_SIGN_IN = 0;

    // Google client to communicate with Google
    private GoogleApiClient mGoogleApiClient;

    private boolean mIntentInProgress;
    private boolean signedInUser;
    private ConnectionResult mConnectionResult;
    private SignInButton signinButton;
    private ImageView image;
    private TextView username, emailLabel;
    private LinearLayout profileFrame, signinFrame;

    private AccessTokenTracker tracker;
    private CallbackManager callbackManager;
    private FacebookCallback<LoginResult> callback;
    private ProfileTracker profileTracker;

    MapFragment(){


    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
        callbackManager = CallbackManager.Factory.create();
            eventListeners();

     }

    private void eventListeners() {

         signinButton.setOnClickListener(this);

        callback = new FacebookCallback<LoginResult>(){

            @Override
            public void onSuccess(LoginResult result) {
            AccessToken access= result.getAccessToken();
                Profile profile = Profile.getCurrentProfile();
                  displayPage(profile); 
            }

            @Override
            public void onCancel() {
                 Toast.makeText(getActivity().getApplicationContext(), "Login Cancel", 
                         Toast.LENGTH_LONG).show();

            }

            @Override
            public void onError(FacebookException error) {
                  Toast.makeText(getActivity().getApplicationContext(),  error.getMessage(), Toast.LENGTH_LONG).show();                 
            }

        };
        tracker = new AccessTokenTracker() {

            @Override
            protected void onCurrentAccessTokenChanged(AccessToken oldone,
                    AccessToken newone) {

            }
        };

        profileTracker = new ProfileTracker() {

            @Override
            protected void onCurrentProfileChanged(Profile oldProfile,
                    Profile newProfile) {

            }
        };

        tracker.startTracking();
        profileTracker.startTracking();

        }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
    //  initializer();
        signinButton = (SignInButton) rootView.findViewById(R.id.signin);
        image = (ImageView) rootView.findViewById(R.id.image);
        username = (TextView) rootView.findViewById(R.id.username);
        emailLabel = (TextView) rootView.findViewById(R.id.email);

        profileFrame = (LinearLayout)  rootView.findViewById(R.id.profileFrame);
        signinFrame = (LinearLayout) rootView.findViewById(R.id.signinFrame);

         mGoogleApiClient=new GoogleApiClient.Builder(rootView.getContext())
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(Plus.API, Plus.PlusOptions.builder().build())
            .addScope(Plus.SCOPE_PLUS_LOGIN).build();
        return rootView;


     }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);
        LoginButton loginButton = (LoginButton) view.findViewById(R.id.login_button);
        loginButton.setReadPermissions("user_friends");
        loginButton.setFragment(this);
        loginButton.registerCallback(callbackManager, callback);
    }

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

        callbackManager.onActivityResult(requestCode, resultCode, data);

    if(requestCode == MapFragment.RC_SIGN_IN){
         if (resultCode != MainActivity.RESULT_OK) {
             signedInUser = false;
            }

        mIntentInProgress = false;
        if (!mGoogleApiClient.isConnecting()) {
            mGoogleApiClient.connect();
        }
    }
        super.onActivityResult(requestCode, resultCode, data);
    }


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

private void displayPage(Profile profile) {

        if(profile!= null){
            Intent intent = new   Intent(getActivity().getApplicationContext(), MapActivity.class);
            startActivity(intent);
        }

    }

public void logout(View v) {
    googlePlusLogout();
}   

private void googlePlusLogout() {
    if (mGoogleApiClient.isConnected()) {
        Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
        mGoogleApiClient.disconnect();
        mGoogleApiClient.connect();
        updateProfile(false);
    }
}

@Override
public void onStart() {
    super.onStart();
    mGoogleApiClient.connect();
}
    @Override
    public void onStop() {
        super.onStop();
        tracker.stopTracking();
        profileTracker.stopTracking();
        if (mGoogleApiClient.isConnected()) {
            mGoogleApiClient.disconnect();
        }
    }

    @Override
    public void onConnectionFailed(ConnectionResult result) {
        if (!result.hasResolution()) {
            GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), getActivity(), 0).show();
            return;
        }

        if (!mIntentInProgress) {
            // store mConnectionResult
            mConnectionResult = result;

            if (signedInUser) {
                resolveSignInError();
            }
        }
    }

    private void resolveSignInError() {
        if (mConnectionResult.hasResolution()) {
            try {
                mIntentInProgress = true;
                mConnectionResult.startResolutionForResult(getActivity(), RC_SIGN_IN);
            } catch (SendIntentException e) {
                mIntentInProgress = false;
                mGoogleApiClient.connect();
            }
        }
    }

    @Override
    public void onConnected(Bundle arg0) {
        signedInUser = false;
        Toast.makeText(getActivity(), "Connected", Toast.LENGTH_LONG).show();
        getProfileInformation();
    }

    private void getProfileInformation() {
        try {
            if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
                Person currentPerson = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
                String personName = currentPerson.getDisplayName();
                String personPhotoUrl = currentPerson.getImage().getUrl();
                String email =  Plus.AccountApi.getAccountName(mGoogleApiClient);

                username.setText(personName);
                emailLabel.setText(email);

                new LoadProfileImage(image).execute(personPhotoUrl);

                // update profile frame with new info about Google Account
                // profile
                updateProfile(true);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void updateProfile(boolean isSignedIn) {
        if (isSignedIn) {
            signinFrame.setVisibility(View.GONE);
            profileFrame.setVisibility(View.VISIBLE);

        } else {
            signinFrame.setVisibility(View.VISIBLE);
            profileFrame.setVisibility(View.GONE);
        }
    }

    @Override
    public void onConnectionSuspended(int arg0) {
        mGoogleApiClient.connect();
        updateProfile(false);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.signin:
            googlePlusLogin();
            break;
        }
    }

    private void googlePlusLogin() {
        if (!mGoogleApiClient.isConnecting()) {
            signedInUser = true;
            resolveSignInError();
        }
    }

    public void signIn(View v) {
        googlePlusLogin();
    }

}
}
你该走了

 signinButton.setOnClickListener(this);
内部
onCreateView(…)
becoz
signinButton=null
at

 signinButton.setOnClickListener(this);
你该走了

 signinButton.setOnClickListener(this);
内部
onCreateView(…)
becoz
signinButton=null
at

 signinButton.setOnClickListener(this);
你该走了

 signinButton.setOnClickListener(this);
内部
onCreateView(…)
becoz
signinButton=null
at

 signinButton.setOnClickListener(this);
你该走了

 signinButton.setOnClickListener(this);
内部
onCreateView(…)
becoz
signinButton=null
at

 signinButton.setOnClickListener(this);

您在
onCreate
中有一个片段

eventListeners();
然后

 private void eventListeners() {

     signinButton.setOnClickListener(this);
在此之前,您的singinButton需要初始化

在这里查看片段生命周期:

它是onAttach、onCreate,然后是onCreateView。。。。。您的按钮已在onCreateView中初始化


如果从xml中引用错误的id,也可能发生NPE。但在您的例子中,您在onCreate中设置了按钮click listener,而在片段的onCreateView中初始化了按钮

eventListeners();
然后

 private void eventListeners() {

     signinButton.setOnClickListener(this);
在此之前,您的singinButton需要初始化

在这里查看片段生命周期:

它是onAttach、onCreate,然后是onCreateView。。。。。您的按钮已在onCreateView中初始化


如果从xml中引用错误的id,也可能发生NPE。但在您的例子中,您在onCreate中设置了按钮click listener,而在片段的onCreateView中初始化了按钮

eventListeners();
然后

 private void eventListeners() {

     signinButton.setOnClickListener(this);
在此之前,您的singinButton需要初始化

在这里查看片段生命周期:

它是onAttach、onCreate,然后是onCreateView。。。。。您的按钮已在onCreateView中初始化


如果从xml中引用错误的id,也可能发生NPE。但在您的例子中,您在onCreate中设置了按钮click listener,而在片段的onCreateView中初始化了按钮

eventListeners();
然后

 private void eventListeners() {

     signinButton.setOnClickListener(this);
在此之前,您的singinButton需要初始化

在这里查看片段生命周期:

它是onAttach、onCreate,然后是onCreateView。。。。。您的按钮已在onCreateView中初始化


如果从xml中引用错误的id,也可能发生NPE。但在您的情况下,您在onCreate中设置了按钮单击侦听器,而在onCreateView中初始化了按钮

@MD where??在
onCreateView
中。之前初始化use@MD哪里在
onCreateView
中。之前初始化use@MD哪里在
onCreateView
中。之前初始化use@MD哪里在
onCreateView
中。使用前初始化