简体   繁体   中英

google+ integration code from learnsauce.com throwing so many errors and build fails

i tried so many sites for google+ sign in integration but even the developers.android code has many errors. So i watched a video from learn sauce : this is the link of video tutorial for g+ integration by learn sauce and i used the exact code given in their attached pdf but i am facing tremendous errors. As i am novice in the field of programming, please help me. I am attaching the code below: Please don't mark down this question reputation because i am novice in this field please! please !

Build.gradle(module app)

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "com.example.user.noteapp"
        minSdkVersion 14
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.2.0'
    compile 'com.google.android.gms:play-services:6.5.87'
    compile 'de.hdodenhof:circleimageview:1.3.0'
}

Manifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.user.noteapp">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.USE_CREDENTIALS" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Strings.xml

<resources>
    <string name="app_name">Note App</string>
    <string name="action_settings">Settings</string>

    <!-- Button text -->
    <string name="btn_logout_from_google">Logout from Google</string>
    <string name="btn_revoke_access">Revoke Access</string>
</resources>

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">
    <com.google.android.gms.common.SignInButton
        android:id="@+id/btn_sign_in"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20dp"/>
    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/profile_layout"
        android:layout_below="@+id/btn_sign_in"
        android:layout_alignParentLeft="true"
        android:visibility="gone"
        android:layout_alignParentStart="true">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="Profile Details"
            android:id="@+id/textView"
            android:textStyle="bold"
            android:textSize="18sp"
            android:layout_centerHorizontal="true"
            android:layout_alignParentTop="true"
            />
        <ImageView
            android:layout_width="150dp"
            android:layout_height="150dp"
            android:id="@+id/imageView_profile_image"
            android:layout_below="@+id/textView"
            android:layout_alignLeft="@+id/textView"
            android:layout_alignStart="@+id/textView"
            android:layout_marginTop="39dp" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Name"
            android:id="@+id/textView_name"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:layout_below="@+id/imageView_profile_image"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="40dp" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="Email"
            android:id="@+id/textView_email"
            android:layout_below="@+id/textView_name"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="25dp" />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="LogOut"
            android:id="@+id/button_logout"
            android:layout_below="@+id/textView_email"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="24dp" />
        <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Revoke"
        android:id="@+id/button_revoke"
        android:layout_marginTop="10dp"
        android:layout_below="@+id/button_logout"
        android:layout_centerHorizontal="true" />
    </RelativeLayout>
</RelativeLayout>

MainActivity.java

package com.example.user.noteapp;

import android.content.Intent;
import android.content.IntentSender;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.service.carrier.CarrierMessagingService;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

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.plus.Plus;
import com.google.android.gms.plus.model.people.Person;

import java.io.InputStream;

public class MainActivity extends AppCompatActivity {
    private GoogleApiClient mGoogleApiClient;
    private SignInButton btnSignIn;
    private Button button_revoke,button_logout;
    private TextView textView_name, textView_email;
    private RelativeLayout profile_layout;
    private ImageView imageView_profile_image;
    private boolean mIntentInProgress;
    private boolean mSignInClicked;
    private ConnectionResult mConnectionResult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnSignIn = (SignInButton) findViewById(R.id.btn_sign_in);
        btnSignIn.setOnClickListener(this);
        button_revoke = (Button) findViewById(R.id.button_revoke);
        button_revoke.setOnClickListener(this);
        button_logout = (Button) findViewById(R.id.button_logout);
        button_logout.setOnClickListener(this);
        imageView_profile_image = (ImageView) findViewById(R.id.imageView_profile_image);
        textView_name = (TextView) findViewById(R.id.textView_name);
        textView_email = (TextView) findViewById(R.id.textView_email);
        profile_layout = (RelativeLayout) findViewById(R.id.profile_layout);
        // Initializing google plus api client
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this).addApi(Plus.API)
                .addScope(Plus.SCOPE_PLUS_LOGIN).build();
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_sign_in:
// Signin button clicked
                signInWithGplus();
                break;
            case R.id.button_logout:
// logout button clicked
                signOutFromGplus();
                break;
            case R.id.button_revoke:
// revoke button clicked
                revokeGplusAccess();
                break;
        }
    }
    protected void onStart() {
        super.onStart();
        mGoogleApiClient.connect();
    }
    protected void onStop() {
        super.onStop();
        if (mGoogleApiClient.isConnected()) {
            mGoogleApiClient.disconnect();
        }
    }
    @Override
    public void onConnected(Bundle bundle) {
        mSignInClicked = false;
        Toast.makeText(this, "User is connected!", Toast.LENGTH_LONG).show();
// Get user's information
        getProfileInformation();
// Update the UI after signin
        updateUI(true);
    }
    @Override
    public void onConnectionSuspended(int i) {
        mGoogleApiClient.connect();
        updateUI(false);
    }
    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        if (!connectionResult.hasResolution()) {
            GooglePlayServicesUtil.getErrorDialog(connectionResult.getErrorCode(), this,
                    0).show();
            return;
        }
        if (!mIntentInProgress) {
// Store the ConnectionResult for later usage
            mConnectionResult = connectionResult;
            if (mSignInClicked) {
// The user has already clicked 'sign-in' so we attempt to
// resolve all
// errors until the user is signed in, or they cancel.
                resolveSignInError();
            }
        }
    }
    private static final int GOOGLE_SIGIN = 100;
    private void resolveSignInError() {
        if (mConnectionResult.hasResolution()) {
            try {
                mIntentInProgress = true;
                mConnectionResult.startResolutionForResult(this, GOOGLE_SIGIN);
            }
            catch (IntentSender.SendIntentException e) {
                mIntentInProgress = false;
                mGoogleApiClient.connect();
            }
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int responseCode,
                                    Intent intent) {
        if (requestCode == GOOGLE_SIGIN) {
            if (responseCode != RESULT_OK) {
                mSignInClicked = false;
            }
            mIntentInProgress = false;
            if (!mGoogleApiClient.isConnecting()) {
                mGoogleApiClient.connect();
            }
        }
    }
    private void updateUI(boolean isSignedIn) {
        if (isSignedIn) {
            btnSignIn.setVisibility(View.GONE);
            profile_layout.setVisibility(View.VISIBLE);
        } else {
            btnSignIn.setVisibility(View.VISIBLE);
            profile_layout.setVisibility(View.GONE);
        }
    }
    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 personGooglePlusProfile = currentPerson.getUrl();
                String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
                textView_name.setText(personName);
                textView_email.setText(email);
// by default the profile url gives 50x50 px image only
// we can replace the value with whatever dimension we want by
// replacing sz=X
                personPhotoUrl = personPhotoUrl.substring(0,
                        personPhotoUrl.length() - 2)
                        + 400;
                new LoadProfileImage(imageView_profile_image).execute(personPhotoUrl);
            } else {
                Toast.makeText(getApplicationContext(),
                        "Person information is null", Toast.LENGTH_LONG).show();
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void signInWithGplus() {
        if (!mGoogleApiClient.isConnecting()) {
            mSignInClicked = true;
            resolveSignInError();
        }
    }
/**
 * Sign-out from google
 * */
private void signOutFromGplus() {
    if (mGoogleApiClient.isConnected()) {
        Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
        mGoogleApiClient.disconnect();
        mGoogleApiClient.connect();
        updateUI(false);
    }
}
    /**
     * Revoking access from google
     * */
    private void revokeGplusAccess() {
        if (mGoogleApiClient.isConnected()) {
            Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
            Plus.AccountApi.revokeAccessAndDisconnect(mGoogleApiClient)
                    .setResultCallback(new CarrierMessagingService.ResultCallback<AsyncTask.Status>() {
                        @Override
                        public void onResult(AsyncTask.Status arg0) {
                            Log.e("pavan", "User access revoked!");
                            mGoogleApiClient.connect();
                            updateUI(false);
                        }
                    });
        }
    }
    /**
     * Background Async task to load user profile picture from url
     * */
    private class LoadProfileImage extends AsyncTask<String, Void, Bitmap> {
        ImageView bmImage;
        public LoadProfileImage(ImageView bmImage) {
            this.bmImage = bmImage;
        }
        protected Bitmap doInBackground(String... urls) {
            String urldisplay = urls[0];
            Bitmap mIcon11 = null;
            try {
                InputStream in = new java.net.URL(urldisplay).openStream();
                mIcon11 = BitmapFactory.decodeStream(in);
            } catch (Exception e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return mIcon11;
        }
        protected void onPostExecute(Bitmap result) {
            bmImage.setImageBitmap(result);
        }
    }
}

Errors:

Error:(44, 18) error: no suitable method found for setOnClickListener(MainActivity)
method View.setOnClickListener(OnClickListener) is not applicable
(argument mismatch; MainActivity cannot be converted to OnClickListener)
method SignInButton.setOnClickListener(OnClickListener) is not applicable
(argument mismatch; MainActivity cannot be converted to OnClickListener)
Error:(95, 5) error: method does not override or implement a method from a supertype
Error:(204, 103) error: <anonymous com.example.user.noteapp.MainActivity$1> is not abstract and does not override abstract method onReceiveResult(Status) in ResultCallback
Error:(100, 5) error: method does not override or implement a method from a supertype
Error:(55, 41) error: incompatible types: MainActivity cannot be converted to ConnectionCallbacks
Error:(86, 5) error: method does not override or implement a method from a supertype
Error:(48, 42) error: incompatible types: MainActivity cannot be converted to OnClickListener
Error:(46, 42) error: incompatible types: MainActivity cannot be converted to OnClickListener
Error:(59, 5) error: method does not override or implement a method from a supertype
Error:(205, 25) error: method does not override or implement a method from a supertype
Error:(204, 40) error: incompatible types: <anonymous android.service.carrier.CarrierMessagingService.ResultCallback<android.os.AsyncTask.Status>> cannot be converted to com.google.android.gms.common.api.ResultCallback<com.google.android.gms.common.api.Status>
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.

The MainActivity should implement OnClickListener,GoogleApiClient.ConnectionCallbacks, and GoogleApiClient.OnConnectionFailedListener, like this:

    public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
            GoogleApiClient.OnConnectionFailedListener, OnClickListener{
//Class Content 

//And this function needs changed
         /**
         * Revoking access from google
         * */
        private void revokeGplusAccess() {
            if (mGoogleApiClient.isConnected()) {
                Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);



                //You will notice AsyncTask.Status changed to com.google.android.gms.common.api.Status
                Plus.AccountApi.revokeAccessAndDisconnect(mGoogleApiClient)
                    .setResultCallback(new CarrierMessagingService.ResultCallback<com.google.android.gms.common.api.Status>() {
                            @Override
                            public void onResult(AsyncTask.Status arg0) {
                                Log.e("pavan", "User access revoked!");
                                mGoogleApiClient.connect();
                                updateUI(false);
                            }
                        });
            }
        }
}

Instead of : new CarrierMessagingService.ResultCallback<com.google.android.gms.common.api.Status>

Use new com.google.android.gms.common.api.ResultCallback<com.google.android.gms.common.api.Status>

Also If you hit Ctr+I on the keyboard it will bring up methods that can be implemented.

replace

public class MainActivity extends AppCompatActivity {

with

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

Calling btnSignIn.setOnClickListener(this); trying to set your activity as click listener for this button.

You have already defined onClick method:

@Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_sign_in:
// Signin button clicked
                signInWithGplus();
                break;
            case R.id.button_logout:
// logout button clicked
                signOutFromGplus();
                break;
            case R.id.button_revoke:
// revoke button clicked
                revokeGplusAccess();
                break;
        }
    }

so you just need to implement interface.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM