2015-07-27 2 views
1

Привет, поэтому я в настоящее время интегрирую Google Войти в свое приложение. В последнее время это было моей единственной проблемой, что по какой-то причине Android Studio не признает область Plus_Login (которая необходима для доступа к базовой информации профиля и т. Д.). Моя текущая ошибка этойКнопка входа в Google+ не работает Android Studio

Error:(40, 17) error: method addScope in class Builder cannot be applied to given types; 
required: Scope 
found: String 
reason: actual argument String cannot be converted to Scope by method invocation conversion 

и вот мой OnCreate файла, где обнаружена ошибка

EDIT 1 - Добавлен оператор импорта и объявление переменных

package com.instigate.aggregator06; 

import android.content.Intent; 
import android.content.IntentSender; 
import android.os.Bundle; 
import android.support.v7.app.AppCompatActivity; 
import android.util.Log; 
import android.view.View; 

import com.google.android.gms.common.ConnectionResult; 
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.common.Scopes; 
import com.google.android.gms.common.api.Scope; 
import com.google.android.gms.plus.Plus; 

public class SocialNetworkActivity extends AppCompatActivity implements 
     ConnectionCallbacks, OnConnectionFailedListener, View.OnClickListener { 

    private static final String TAG = "Social Network Activity"; 

    /* Request code used to invoke sign in user interactions. */ 
    private static final int RC_SIGN_IN = 0; 

    /* Client used to interact with Google APIs. */ 
    private GoogleApiClient mGoogleApiClient; 

    /* A flag indicating that a PendingIntent is in progress and prevents 
    * us from starting further intents. 
    */ 
    private boolean mIntentInProgress; 

public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     mGoogleApiClient = new GoogleApiClient.Builder(this) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .addApi(Plus.API) 
       .addScope(Scopes.PLUS_LOGIN) // <----- This is where the error is found 
       .addScope(Scopes.PLUS_ME) 
       .build(); 

     findViewById(R.id.sign_in_button).setOnClickListener(this); 
    } 

Я искал какое-то время найти решение этой ошибки (видя, что область действия Plus_Login должна работать) пока не нашли решения.

EDIT 2 - ошибки после решения Я нашел ответ на этот вопрос. По-видимому, вместо:

.addScope(Scopes.PLUS_LOGIN) 
.addScope(Scopes.PLUS_ME) 

мы пишем этот

.addScope(new Scope(Scopes.PLUS_LOGIN)) 
.addScope(new Scope(Scopes.PLUS_ME)) 

которая решила мою проблему.

Однако он показал новую проблему:

findViewById(R.id.sign_in_button).setOnClickListener(this); 

где LogCat указывает на то, что есть NullPointerException в этой точке.

EDIT 3 - решаемые NullPointerException Я решил проблему NullPointer Exception, однако мой Google+ Вход Баттона по-прежнему не работает.

здесь общий класс (продолжение фрагмента кода, упомянутого выше)

package com.instigate.aggregator06; 

import android.content.Intent; 
import android.content.IntentSender; 
import android.os.Bundle; 
import android.support.v7.app.AppCompatActivity; 
import android.util.Log; 
import android.view.View; 

import com.google.android.gms.common.ConnectionResult; 
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.common.Scopes; 
import com.google.android.gms.common.api.Scope; 
import com.google.android.gms.plus.Plus; 

public class SocialNetworkActivity extends AppCompatActivity implements 
     ConnectionCallbacks, OnConnectionFailedListener, View.OnClickListener { 

    private static final String TAG = "Social Network Activity"; 

    /* Request code used to invoke sign in user interactions. */ 
    private static final int RC_SIGN_IN = 0; 

    /* Client used to interact with Google APIs. */ 
    private GoogleApiClient mGoogleApiClient; 

    /* A flag indicating that a PendingIntent is in progress and prevents 
    * us from starting further intents. 
    */ 
    private boolean mIntentInProgress; 

    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_social_network); 

     mGoogleApiClient = new GoogleApiClient.Builder(this) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .addApi(Plus.API) 
       //.addScope(Scopes.PLUS_LOGIN) 
       //.addScope(Scopes.PLUS_ME) 
       .addScope(new Scope(Scopes.PLUS_ME)) 
       .addScope(new Scope(Scopes.PLUS_LOGIN)) 
       .build(); 

     this.findViewById(R.id.sign_in_button).setOnClickListener(this); 
    } 

    protected void onStart() { 
     super.onStart(); 
     mGoogleApiClient.connect(); 
    } 

    protected void onStop() { 
     super.onStop(); 

     if (mGoogleApiClient.isConnected()) { 
      mGoogleApiClient.disconnect(); 
     } 
    } 

    /* Code in case second one doesn't work 

    @Override 
    public void onConnectionFailed(ConnectionResult connectionResult) { 
     // Could not connect to Google Play Services. The user needs to select an account, 
     // grant permissions or resolve an error in order to sign in. Refer to the javadoc for 
     // ConnectionResult to see possible error codes. 
     Log.d(TAG, "onConnectionFailed:" + connectionResult); 

     if (!mIsResolving && mShouldResolve) { 
      if (connectionResult.hasResolution()) { 
       try { 
        connectionResult.startResolutionForResult(this, RC_SIGN_IN); 
        mIsResolving = true; 
       } catch (IntentSender.SendIntentException e) { 
        Log.e(TAG, "Could not resolve ConnectionResult.", e); 
        mIsResolving = false; 
        mGoogleApiClient.connect(); 
       } 
      } else { 
       // Could not resolve the connection result, show the user an 
       // error dialog. 
       showErrorDialog(connectionResult); 
      } 
     } 
    }*/ 

    public void onConnectionFailed(ConnectionResult result) { 
     if (!mIntentInProgress && result.hasResolution()) { 
      try { 
       mIntentInProgress = true; 
       startIntentSenderForResult(result.getResolution().getIntentSender(), 
         RC_SIGN_IN, null, 0, 0, 0); 
      } catch (IntentSender.SendIntentException e) { 
       // The intent was canceled before it was sent. Return to the default 
       // state and attempt to connect to get an updated ConnectionResult. 
       mIntentInProgress = false; 
       mGoogleApiClient.connect(); 
      } 
     } 
    } 

    public void onConnected(Bundle connectionHint) { 
     // We've resolved any connection errors. mGoogleApiClient can be used to 
     // access Google APIs on behalf of the user. 

     Log.d(TAG, "onConnected:" + connectionHint); 
     Intent j = new Intent(SocialNetworkActivity.this, AccountPageActivity.class); 
     startActivity(j); 

    } 

    protected void onActivityResult(int requestCode, int responseCode, Intent intent) { 
     if (requestCode == RC_SIGN_IN) { 
      mIntentInProgress = false; 

      if (!mGoogleApiClient.isConnecting()) { 
       mGoogleApiClient.connect(); 
      } 
     } 
    } 

    public void onConnectionSuspended(int cause) { 
     mGoogleApiClient.connect(); 
    } 

    @Override 
    public void onClick(View v) { 
     if (v.getId() == R.id.sign_in_button) { 
      //onSignInClicked(); 
      mGoogleApiClient.connect(); 
     } 

     // ... 
    } 

    /* I find this unnecesary 

    private void onSignInClicked() { 
     // User clicked the sign-in button, so begin the sign-in process and automatically 
     // attempt to resolve any errors that occur. 
     //mShouldResolve = true; 
     mGoogleApiClient.connect(); 

     // Show a message to the user that we are signing in. 
     //mStatusTextView.setText(R.string.signing_in); 
    }*/ 

    public void backToMainPage(View view) { 
     Intent j = new Intent(SocialNetworkActivity.this, MainActivity.class); 
     startActivity(j); 
    } 

} 

и вот мой 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="com.instigate.aggregator06.SelectSNActivity" 
    android:orientation="vertical" 
    android:id="@+id/SelectSNActivity" 
    android:weightSum="1"> 

    <Button 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="@string/backbtn2" 
     android:id="@+id/backbtntest" 
     android:layout_gravity="right" 
     android:layout_alignParentBottom="true" 
     android:layout_alignParentRight="true" 
     android:layout_alignParentEnd="true" 
     android:layout_marginBottom="43dp" 
     android:onClick="backToMainPage"/> 

    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:textAppearance="?android:attr/textAppearanceLarge" 
     android:text="@string/selectSocialNetwork" 
     android:id="@+id/selectSocialNetworkHeader" 
     android:textStyle="bold" 
     android:textSize="36sp" 
     android:layout_gravity="center_horizontal" 
     android:layout_alignParentTop="true" 
     android:layout_centerHorizontal="true" /> 

    <com.google.android.gms.common.SignInButton 
     android:id="@+id/sign_in_button" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_below="@+id/selectSocialNetworkHeader" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentStart="true" 
     android:layout_marginTop="52dp" /> 


</RelativeLayout> 

Любая помощь очень ценится, спасибо.

+0

Какова ваша заявка на импорт для областей применения – Raghunandan

+0

Mi ssing 'setContentView' в действии, если не проверить идентификатор кнопки в xml – Raghunandan

ответ

1

Вы

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

Вы пропускаете setContentView(R.layout.activity_main)

Ваш макет должен иметь

<com.google.android.gms.common.SignInButton 
    android:id="@+id/sign_in_button" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" /> 

Также не проверить идентификатор кнопки в вашем XML и убедитесь, что вы ссылаетесь на тот же в деятельности

+0

Когда вы говорите ссылку с тем же действием, что вы имеете в виду в общем XML-файле? (Я также добавил файл xml в вопрос для дальнейшего уточнения) –

+0

@RobertMelikyan да. Если он не работает, вам нужно будет проверить файл конфигурации.json file – Raghunandan

+0

@RobertMelikyan на самом деле есть образец github для google для google + signin – Raghunandan

Смежные вопросы