0

MainActivity.java

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

    setContentView(R.layout.activity_main);
    initializeControls();
    loginWithFB();

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


    viewPager = (ViewPager) findViewById(R.id.viewpager);
    setupViewPager(viewPager);

    tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);


    View inflatedView = getLayoutInflater().inflate(R.layout.fragment_login_social, null);
    SignInButton sign = inflatedView.findViewById(R.id.sign_in_button);
    sign.setOnClickListener(this);

    GoogleSignInOptions signInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().build();
    googleApiClient = new GoogleApiClient.Builder(this).enableAutoManage(this, this).addApi(Auth.GOOGLE_SIGN_IN_API, signInOptions).build();
}

public void onClick(View view) {
        switch (view.getId()){
            case R.id.sign_in_button:
                sign();
                break;
        }
    }
    private void sign() {
    Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient);
    startActivityForResult(signInIntent, RC_SIGN_IN);
}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}

private void handleResult(GoogleSignInResult result) {
    Log.d(TAG, "handleSignInResult:" + result.isSuccess());
    if (result.isSuccess()) {
        // Signed in successfully, show authenticated UI.
        GoogleSignInAccount acct = result.getSignInAccount();
        updateUI(true);
    } else {
        // Signed out, show unauthenticated UI.
        updateUI(false);
    }
}

private void updateUI(boolean b) {
}


private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFragment(new LoginSocial(), "ONE");
    adapter.addFragment(new Updates(), "TWO");
    viewPager.setAdapter(adapter);
}

@Override
public void onFragmentInteraction(Uri uri) {

}

class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFragment(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }
}

TextView txtStatus;
LoginButton fb_login;
CallbackManager callbackManager;

private void initializeControls() {
    callbackManager = CallbackManager.Factory.create();
    txtStatus = (TextView) findViewById(R.id.txtStatus);
    fb_login = (LoginButton) findViewById(R.id.fb_login);
}

private void loginWithFB() {
    LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            txtStatus.setText("Login Success");
        }

        @Override
        public void onCancel() {
            txtStatus.setText("Login Cancelled.");
        }

        @Override
        public void onError(FacebookException error) {
            txtStatus.setText("Login Error:" + error.getMessage());
        }
    });
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (FacebookSdk.isFacebookRequestCode(requestCode)) {
        // Facebook
        callbackManager.onActivityResult(requestCode, resultCode, data);
    } else if (requestCode == RC_SIGN_IN) {
        // Google
        GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
        handleResult(result);
    }
}

Logcat

7-09 15:04:17.723 3231-3231/com.example.pranavgopal.myapplication E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.pranavgopal.myapplication, PID: 3231 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.pranavgopal.myapplication/com.example.pranavgopal.myapplication.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.common.SignInButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726) at android.app.ActivityThread.-wrap12(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6119) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.common.SignInButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference at com.example.pranavgopal.myapplication.MainActivity.onCreate(MainActivity.java:53) at android.app.Activity.performCreate(Activity.java:6679) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)  at android.app.ActivityThread.-wrap12(ActivityThread.java)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:154)  at android.app.ActivityThread.main(ActivityThread.java:6119)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) *

Activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.pranavgopal.myapplication.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabMode="fixed"
            app:tabGravity="fill"/>
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"  />
</android.support.constraint.ConstraintLayout> 
Shivam Kumar
  • 1,892
  • 2
  • 21
  • 33
  • Please post your logcat errors and consider editing your post so the code snippets are properly formatted. Also, elaborate a bit to reach the minimum text for the post. – DaveNOTDavid Jul 09 '17 at 19:47

1 Answers1

1

You have a NullPointerException on this line:

sign.setOnClickListener(this);

This is presumably because sign is not found when you call this line:

sign = (SignInButton) findViewById(R.id.sign_in_button);

Make sure the XML id is correct (R.id.sign_in_button).

aneurinc
  • 1,238
  • 12
  • 20
  • Hi, I have already tried with it and tried once again. Still its not working. XML ** – Pranav Gundra Jul 10 '17 at 15:57
  • If R.id.sign_in_button is in R.layout.activity_main there shouldn't be a NPE here. Try a clean and rebuild + invalidate caches. – aneurinc Jul 10 '17 at 18:43
  • Hi, I have tried that too. I have removed onClicklistener, then I am able to open the app on Emulator. But unable to sign in with Google – Pranav Gundra Jul 10 '17 at 18:52
  • Yeah that makes sense. Did you invalidate the caches as well? File -> Invalidate Cache / Restart. And have you tried it on a real device? If the cache is up to date and the id is in the layout file then I'm not sure why you are getting a NPE. – aneurinc Jul 10 '17 at 19:59
  • Hi, I haven't tried on Real Device. But I have invalidated and Restart the Cache. But still same problem – Pranav Gundra Jul 10 '17 at 20:36
  • Ok. Can you post R.layout.activity_main in your question as well. – aneurinc Jul 10 '17 at 20:55
  • Sure. I will do – Pranav Gundra Jul 10 '17 at 21:45
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/148828/discussion-between-345-and-pranav-gundra). – aneurinc Jul 10 '17 at 22:10
  • Hi, I am able open the app in Emulator after trying with your suggestion, But now the Google Signin button is not opening the activity. – Pranav Gundra Jul 11 '17 at 22:07
  • Hi, I have got an error in Build, Can you please go through this link on stackoverflow https://stackoverflow.com/questions/45514704/error-in-buildin-the-gradle thanks in advance – Pranav Gundra Aug 04 '17 at 20:12