I'm trying to make a game where I store a high score.
The "Implementing Sign-in on Android" link:
https://developers.google.com/games/services/training/signin#signing_the_player_in_at_startup
says to use the MyGameProgress class to save the score, achievements, etc..
However, I get a "cannot resolve symbol MyGameProgress" when I try to declare a variable as a MyGameProgress
(ex. MyGameProgress mGameProgress = new MyGameProgress() )
Anybody have a clue ?
below is my MainActivity.java file:
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.games.Games;
import com.google.example.games.basegameutils.BaseGameUtils;
public class MainActivity extends ActionBarActivity {
int Score = 0;
GoogleApiClient mGoogleApiClient;
MyGameProgress mGameProgress = new MyGameProgress();
private static int RC_SIGN_IN = 9001;
private boolean mResolvingConnectionFailure = false;
private boolean mAutoStartSignInFlow = true;
private boolean mSignInClicked = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (mResolvingConnectionFailure) {
// Already resolving
return;
}
// If the sign in button was clicked or if auto sign-in is enabled,
// launch the sign-in flow
if (mSignInClicked || mAutoStartSignInFlow) {
mAutoStartSignInFlow = false;
mSignInClicked = false;
mResolvingConnectionFailure = true;
// Attempt to resolve the connection failure using BaseGameUtils.
// The R.string.signin_other_error value should reference a generic
// error string in your strings.xml file, such as "There was
// an issue with sign in, please try again later."
if (!BaseGameUtils.resolveConnectionFailure(this,
mGoogleApiClient, connectionResult,
RC_SIGN_IN, "R.string.signin_other_error")) {
mResolvingConnectionFailure = false;
}
}
// Put code here to display the sign-in button
}
public void increaseScore(View view) {
Score = Score + 1;
TextView ScoreTextV = (TextView)findViewById(R.id.textView);
ScoreTextV.setText(Integer.toString(Score));
};
public void FinishGame(View view) {
//Games.Leaderboards.submitScore(getApiClient(),
// getString(R.string.leaderboard_high_score), Score);
// when user finishes level:
mGameProgress.addScore(userScore);
mGameProgress.addAchievement(fooAchievement);
mGameProgress.addAchievement(barAchievement);
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
mGameProgress.save(mGoogleApiClient);
}
}
}
in my build.gradle (module.app) I have included this under dependencies:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile project(':BaseGameUtils')
compile 'com.android.support:appcompat-v7:21.0.3'
//compile 'com.google.android.gms:play-services-games:6.5.87'
compile 'com.google.android.gms:play-services:6.5.+'
in my AndroidManifest.xml I included:
<meta-data android:name="com.google.android.gms.games.APP_ID"
android:value="#string/app_id" />
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
I also imported the BaseGameUtils module.
for convenience, Here's the code snippet from the "Implementing Sign-in on Android" link I provided above:
MyGameProgress mGameProgress = ....;
// when user finishes level:
mGameProgress.addScore(userScore);
mGameProgress.addAchievement(fooAchievement);
mGameProgress.addAchievement(barAchievement);
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
mGameProgress.save(mGoogleApiClient);
}
#Override
protected void onConnected() {
// sign in successful, so save progress if we have any.
if (mGameProgress != null) {
mGameProgress.save(mGoogleApiClient);
}
// ...
}
if I need to create the MyGameProgress class myself I don't know how to create the 'save' method so that it would save the high score to the game services cloud.
I also saw something about 'snapshots' for saving game progress. Do you think that's a better way of doing it. Should I research doing it that way instead ?
It turns out that MyGameProgress (which has a 'save' method) was a class that the documentation wanted me to create.
I was able instead, however, to just use the Games.Leaderboards.submitScore method.
I was able to make it work with the statement:
Games.Leaderboards.submitScore(mGoogleApiClient, getString(R.string.leaderboard_high_score), Score);
Note:
Originally some documentation said to use
Games.Leaderboards.submitScore(getApiClient(), getString(R.string.leaderboard_high_score), Score);
but the getApiClient() part was making it not work.
It worked after I Replaced it with a
GoogleApiClient variable mGoogleApiClient.
Related
I am a newbie in both in this forum and in Android world. I just developed a singleplayer trivia game, named "Reklamsız Bilgi Yarışması", only supports my local language but accessable in all over the world.
I just followed the guides and integrated AdColony to my AdMob account and get the perfect results, with test video ads.
However, after going live, nothing happened. Many of my customers wrote me that they can not get Ad Videos. Also, in admob, I saw 650 requests happened and only 4 of them get the video!
In AdColony statistics, I saw only 5 lucky guy requested the video and got watched full video, then took their rewards.
So, how could it be? Hundreds of request but only %0.25 of them were answered by AdMob (Or AdColony), I could not understand.
Lastly, %98 percent of my customers are from Turkey, %1 from Azerbaijan and %1 from Germany.
Is there any possible mistake in coding? Because I saw the test ads, on my physical device, not on the emulator also.
Thank You !
<<<<<<<<<<<< In Manıfest >>>>>>>>>>>>>>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity
android:name="com.google.android.gms.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
android:theme="#android:style/Theme.Translucent" />
<activity android:name="com.jirbo.adcolony.AdColonyOverlay"
android:configChanges="keyboardHidden|screenSize"
android:theme="#android:style/Theme.Translucent.NoTitleBar.Fullscreen" />
<activity android:name="com.jirbo.adcolony.AdColonyFullscreen"
android:configChanges="keyboardHidden|screenSize"
android:theme="#android:style/Theme.Black.NoTitleBar.Fullscreen" />
<activity android:name="com.jirbo.adcolony.AdColonyBrowser"
android:configChanges="keyboardHidden|screenSize"
android:theme="#android:style/Theme.Black.NoTitleBar.Fullscreen" />
I Have All of the needed codes in Manifest I think
<<<<<<<<<>>>>>>>>>>>
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:23.4.0'
compile 'com.google.android.gms:play-services-ads:9.8.0'
compile 'com.google.firebase:firebase-core:9.8.0'
}
apply plugin: 'com.google.gms.google-services'
In Libs, I have "Adcolony *jar"
<<<<<<<<<<< In Java >>>>>>>>>>>>>
import com.jirbo.adcolony.AdColony;
import com.jirbo.adcolony.AdColonyAdapter;
import com.jirbo.adcolony.AdColonyBundleBuilder;
import com.jirbo.adcolony.*;
import com.google.ads.mediation.admob.AdMobAdapter;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.reward.RewardItem;
import com.google.android.gms.ads.reward.RewardedVideoAd;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
public class oyunsonu extends Activity implements RewardedVideoAdListener{
// I Have those implementation with the importations stated above
private static final String AD_UNIT_ID = "xxxxxxxx";
private static final String APP_ID = "xxxxxxxx";
private static final String LOGTAG = "GMS";
private boolean mIsRewardedVideoLoading;
private RewardedVideoAd mRewardedVideoAd2;
private final Object mLock = new Object();
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.oyunsonu);
checkGooglePlayServicesAvailable();
MobileAds.initialize(this, APP_ID);
mRewardedVideoAd2 = MobileAds.getRewardedVideoAdInstance(this);
mRewardedVideoAd2.setRewardedVideoAdListener(this);
loadRewardedVideoAd();
}
private void loadRewardedVideoAd() {
synchronized (mLock) {
if (!mIsRewardedVideoLoading && !mRewardedVideoAd2.isLoaded()) {
mIsRewardedVideoLoading = true;
Bundle extras = new Bundle();
extras.putBoolean("_noRefresh", true);
AdRequest adRequest = new AdRequest.Builder().addNetworkExtrasBundle(AdColonyAdapter.class, extras)
.addNetworkExtrasBundle(AdMobAdapter.class, extras)
.build();
mRewardedVideoAd2.loadAd(AD_UNIT_ID, adRequest);
}
}
}
private void showRewardedVideo() {
if (mRewardedVideoAd2.isLoaded()) {
mRewardedVideoAd2.show();
}
}
private boolean checkGooglePlayServicesAvailable()
{
final int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext()) ;
if (status == ConnectionResult.SUCCESS)
{
return true;
}
Log.e(LOGTAG, "Google Play Services not available: " + GooglePlayServicesUtil.getErrorString(status));
if (GooglePlayServicesUtil.isUserRecoverableError(status))
{
final Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(status, this, 1);
if (errorDialog != null)
{
errorDialog.show();
}
}
return false;
}
#Override
public void onRewardedVideoAdLeftApplication() {
}
#Override
public void onRewardedVideoAdClosed() {
loadRewardedVideoAd();
}
#Override
public void onRewardedVideoAdFailedToLoad(int errorCode) {
mIsRewardedVideoLoading = false;
Toast.makeText(this, "Sunucu Kaynaklı Hata! Ödüllü Reklam Mevcut Değil!", Toast.LENGTH_SHORT).show();
reklamizlex.setVisibility(View.INVISIBLE);
}
#Override
public void onRewardedVideoAdLoaded() {
mIsRewardedVideoLoading = false;
reklamizlex.setVisibility(View.VISIBLE);
}
#Override
public void onRewardedVideoAdOpened() {
}
#Override
public void onRewarded(RewardItem reward) {
rekflag = 1;
yenidenoyna.setBackgroundResource(R.drawable.butonbosgri);
anamenuyegit.setBackgroundResource(R.drawable.butonbosgri);
reklamizlex.setBackgroundResource(R.drawable.butonbosgri);
final Intent yenidenoynamakr = new Intent(getApplicationContext(), sorulars.class);
yenidenoynamakr.putExtra("rekdurumu", rekflag);
yenidenoynamakr.putExtra("sonskorx", sonskorz);
yenidenoynamakr.putExtra("katsec", katdurumu);
yenidenoynamakr.putExtra("ajdurumu", ajsay);
yenidenoynamakr.putExtra("yydurumu", yysay);
yenidenoynamakr.putExtra("sdegdurumu", dsay);
yenidenoynamakr.putExtra("ssaydurumu", ssay);
yenidenoynamakr.putExtra("jokkodurumu", jokko);
startActivity(yenidenoynamakr);
}
#Override
public void onRewardedVideoStarted() {
}
}
Here are all codes that I used, which are about the "Rewarded Video Ads"
I could not solve the problem but i think it is caused by AdColony. Because 7 people could manage to see live Ads, the others got the warning as "RewardedVideoFailedtoLoad". I think AdColony limited my Ad views because my App has only 2.500 hit now and also almost 99% exist in Turkey. Probably about the location and download numbers. I've just updated my game with Chartboost.
I am currently experiencing a problem, what I believe might be my button.
From Android Studio: I have made an app, and currently, a click of a button from one page (AccountListActivity) is supposed to redirect to another page (SelectSNActivity). It worked well before, however after I recently added a Google+ sign in option (on the SelectSNActivity), the button won't work and instead redirects me back to the starting page.
I was wondering if the problem of the code might be in the AccountListActivity (since that is where the button is initiating an Intent from.
I have no errors and am able to run the app on an emulator and actual device. If you are able to discover the source of the bug, or if you would like me to past additional files, don't hesitate to comment or post below, thank you very much.
Here is the:
.java code for AccountListActivity
package com.instigate.aggregator06;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Map;
public class AccountListActivity extends AppCompatActivity {
public HashMap accountList = new HashMap();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account_list);
TextView emptyview = (TextView) findViewById(R.id.empty);
ListView accountslist=(ListView) findViewById(R.id.list);
emptyview.setVisibility(View.VISIBLE);
accountslist.setVisibility(View.GONE);
/*if (accountList.length() == 0)
{
emptyview.setVisibility(View.GONE);
accountslist.setVisibility(View.VISIBLE);
}
else
{
accountslist.setVisibility(View.VISIBLE);
emptyview.setVisibility(View.GONE);
} */
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_account_list, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void goToSelectSNPage(View view)
{
Intent k = new Intent(AccountListActivity.this,SelectSNActivity.class);
startActivity(k);
}
}
xml code AccountListActivity
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="8dp"
android:paddingRight="8dp"
android:id="#+id/accountPage">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/accountPageHeader"
android:id="#+id/accountPageHeader"
android:layout_gravity="center_horizontal"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="36sp"/>
<LinearLayout
android:layout_below="#id/accountPageHeader"
android:paddingLeft="8dp"
android:paddingRight="8dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView android:id="#+id/empty"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="#string/noAccounts"
android:visibility="visible"
android:textSize="24sp"
/>
<ScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/scrollView"
android:visibility="gone">
<ListView android:id="#+id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</ScrollView>
<Button android:id="#+id/addAccount"
android:text="#string/addAccount"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:onClick="goToSelectSNPage"/>
</LinearLayout>
</RelativeLayout>
.java code for SelectSNActivity
package com.instigate.aggregator06;
import android.content.DialogInterface;
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 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.Scopes;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.Scope;
import com.google.android.gms.plus.Plus;
/**
* Minimal activity demonstrating basic Google Sign-In.
*/
public class SelectSNActivity extends AppCompatActivity implements
View.OnClickListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "SelectSNActivity";
/* RequestCode for resolutions involving sign-in */
private static final int RC_SIGN_IN = 9001;
/* Keys for persisting instance variables in savedInstanceState */
private static final String KEY_IS_RESOLVING = "is_resolving";
private static final String KEY_SHOULD_RESOLVE = "should_resolve";
/* Client for accessing Google APIs */
private GoogleApiClient mGoogleApiClient;
/* View to display current status (signed-in, signed-out, disconnected, etc) */
private TextView mStatus;
/* Is there a ConnectionResult resolution in progress? */
private boolean mIsResolving = false;
/* Should we automatically resolve ConnectionResults when possible? */
private boolean mShouldResolve = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Restore from saved instance state
// [START restore_saved_instance_state]
if (savedInstanceState != null) {
mIsResolving = savedInstanceState.getBoolean(KEY_IS_RESOLVING);
mShouldResolve = savedInstanceState.getBoolean(KEY_SHOULD_RESOLVE);
}
// [END restore_saved_instance_state]
// Set up button click listeners
findViewById(R.id.googleSignInBtn).setOnClickListener(this);
//findViewById(R.id.sign_out_button).setOnClickListener(this);
//findViewById(R.id.disconnect_button).setOnClickListener(this);
// Large sign-in
((SignInButton) findViewById(R.id.googleSignInBtn)).setSize(SignInButton.SIZE_WIDE);
// Start with sign-in button disabled until sign-in either succeeds or fails
findViewById(R.id.googleSignInBtn).setEnabled(false);
// Set up view instances
//mStatus = (TextView) findViewById(R.id.status);
// [START create_google_api_client]
// Build GoogleApiClient with access to basic profile
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Plus.API)
.addScope(new Scope(Scopes.PROFILE))
.build();
// [END create_google_api_client]
}
private void updateUI(boolean isSignedIn) {
if (isSignedIn) {
// Show signed-in user's name
String name = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient).getDisplayName();
mStatus.setText(getString(R.string.signed_in_fmt, name));
// Set button visibility
findViewById(R.id.googleSignInBtn).setVisibility(View.GONE);
//findViewById(R.id.sign_out_and_disconnect).setVisibility(View.VISIBLE);
} else {
// Show signed-out message
mStatus.setText(R.string.signed_out);
// Set button visibility
findViewById(R.id.googleSignInBtn).setEnabled(true);
findViewById(R.id.googleSignInBtn).setVisibility(View.VISIBLE);
//findViewById(R.id.sign_out_and_disconnect).setVisibility(View.GONE);
}
}
// [START on_start_on_stop]
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
mGoogleApiClient.disconnect();
}
// [END on_start_on_stop]
// [START on_save_instance_state]
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(KEY_IS_RESOLVING, mIsResolving);
outState.putBoolean(KEY_SHOULD_RESOLVE, mIsResolving);
}
// [END on_save_instance_state]
// [START on_activity_result]
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d(TAG, "onActivityResult:" + requestCode + ":" + resultCode + ":" + data);
if (requestCode == RC_SIGN_IN) {
// If the error resolution was not successful we should not resolve further errors.
if (resultCode != RESULT_OK) {
mShouldResolve = false;
}
mIsResolving = false;
mGoogleApiClient.connect();
}
}
// [END on_activity_result]
#Override
public void onConnected(Bundle bundle) {
// onConnected indicates that an account was selected on the device, that the selected
// account has granted any requested permissions to our app and that we were able to
// establish a service connection to Google Play services.
Log.d(TAG, "onConnected:" + bundle);
// Show the signed-in UI
updateUI(true);
}
#Override
public void onConnectionSuspended(int i) {
// The connection to Google Play services was lost. The GoogleApiClient will automatically
// attempt to re-connect. Any UI elements that depend on connection to Google APIs should
// be hidden or disabled until onConnected is called again.
Log.w(TAG, "onConnectionSuspended:" + i);
}
// [START on_connection_failed]
#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);
}
} else {
//Show the signed-out UI
updateUI(false);
}
}
// [END on_connection_failed]
private void showErrorDialog(ConnectionResult connectionResult) {
int errorCode = connectionResult.getErrorCode();
if (GooglePlayServicesUtil.isUserRecoverableError(errorCode)) {
// Show the default Google Play services error dialog which may still start an intent
// on our behalf if the user can resolve the issue.
GooglePlayServicesUtil.getErrorDialog(errorCode, this, RC_SIGN_IN,
new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
mShouldResolve = false;
updateUI(false);
}
}).show();
} else {
// No default Google Play Services error, display a message to the user.
String errorString = getString(R.string.play_services_error_fmt, errorCode);
Toast.makeText(this, errorString, Toast.LENGTH_SHORT).show();
mShouldResolve = false;
updateUI(false);
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.googleSignInBtn:
// User clicked the sign-in button, so begin the sign-in process and automatically
// attempt to resolve any errors that occur.
mStatus.setText(R.string.signing_in);
// [START sign_in_clicked]
mShouldResolve = true;
mGoogleApiClient.connect();
// [END sign_in_clicked]
break;
/*case R.id.sign_out_button:
// Clear the default account so that GoogleApiClient will not automatically
// connect in the future.
// [START sign_out_clicked]
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
}
// [END sign_out_clicked]
updateUI(false);
break;
case R.id.disconnect_button:
// Revoke all granted permissions and clear the default account. The user will have
// to pass the consent screen to sign in again.
// [START disconnect_clicked]
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
Plus.AccountApi.revokeAccessAndDisconnect(mGoogleApiClient);
mGoogleApiClient.disconnect();
}
// [END disconnect_clicked]
updateUI(false);
break;*/
}
}
public void goToSignInPage(View view)
{
Intent j = new Intent(SelectSNActivity.this, SignInActivity.class);
startActivity(j);
}
}
xml code for SelectSNActivity
<LinearLayout 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">
<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"
/>
<com.google.android.gms.common.SignInButton
android:id="#+id/googleSignInBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/fbBtn"
android:id="#+id/fbBtn"
android:onClick="goToSignInPage"/>
</LinearLayout>
Note after using Heisenberg's fix, I ran the application. It opens the SelectSNActivity however it quickly exits and back to the MainActivity page by itself. Here are the two errors which I understood:
com.instigate.aggregator06.SelectSNActivity.updateUI(SelectSNActivity.java:83)
which refers to
// Show signed-out message
mStatus.setText(R.string.signed_out);
and
com.instigate.aggregator06.SelectSNActivity.onConnectionFailed(SelectSNActivity.java:165)
which refers to
/ Could not resolve the connection result, show the user an
// error dialog.
showErrorDialog(connectionResult);
}
} else {
//Show the signed-out UI
updateUI(false); <--------- this line
}
}
This is the whole error log
07-21 16:47:46.572 138-507/? E/ALSAModule﹕ buffersize: 6144, periodsize:2048
07-21 16:47:46.582 138-507/? E/ALSAModule﹕ audio type flag: 0
07-21 16:47:46.582 138-507/? E/ALSAModule﹕ buffersize: 6144, periodsize:2048
07-21 16:47:46.582 138-507/? E/ALSAModule﹕ audio type flag: 0
07-21 16:48:00.012 515-529/system_process E/WindowManager﹕ Starting window AppWindowToken{4202bd70 token=Token{41cfb398 ActivityRecord{41bf3338 u0 com.ttxapps.wifiadb/.MainActivity t40}}} timed out
07-21 16:48:06.972 132-444/? E/FrameworkListener﹕ read() failed (Connection reset by peer)
07-21 16:48:21.062 23495-23495/? E/memtrack﹕ Couldn't load memtrack module (No such file or directory)
07-21 16:48:21.062 23495-23495/? E/android.os.Debug﹕ failed to load memtrack module: -2
07-21 16:48:33.862 860-860/com.google.process.gapps E/NetworkScheduler.SchedulerReceiver﹕ Invalid parameter app
07-21 16:48:33.862 860-860/com.google.process.gapps E/NetworkScheduler.SchedulerReceiver﹕ Invalid package name : Perhaps you didn't include a PendingIntent in the extras?
07-21 16:48:33.982 860-860/com.google.process.gapps E/NetworkScheduler.SchedulerReceiver﹕ Invalid parameter app
07-21 16:48:33.982 860-860/com.google.process.gapps E/NetworkScheduler.SchedulerReceiver﹕ Invalid package name : Perhaps you didn't include a PendingIntent in the extras?
07-21 16:48:34.852 23641-23641/? E/memtrack﹕ Couldn't load memtrack module (No such file or directory)
07-21 16:48:34.852 23641-23641/? E/android.os.Debug﹕ failed to load memtrack module: -2
07-21 16:48:35.522 23177-23177/com.ttxapps.wifiadb E/WifiADB﹕ IabPurchase: failed to query inventory: IabResult: Error refreshing inventory (querying prices of items). (response: 6:Error)
07-21 16:48:39.632 138-507/? E/ALSAModule﹕ buffersize: 6144, periodsize:2048
07-21 16:48:39.632 138-507/? E/ALSAModule﹕ audio type flag: 0
07-21 16:48:39.642 138-507/? E/ALSAModule﹕ buffersize: 6144, periodsize:2048
07-21 16:48:39.642 138-507/? E/ALSAModule﹕ audio type flag: 0
07-21 16:48:41.302 23657-23657/com.instigate.aggregator06 E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.instigate.aggregator06, PID: 23657
java.lang.NullPointerException
at com.instigate.aggregator06.SelectSNActivity.updateUI(SelectSNActivity.java:83)
at com.instigate.aggregator06.SelectSNActivity.onConnectionFailed(SelectSNActivity.java:165)
at com.google.android.gms.common.internal.zzj.zzh(Unknown Source)
at com.google.android.gms.common.api.zze.zzd(Unknown Source)
at com.google.android.gms.common.api.zze.zza(Unknown Source)
at com.google.android.gms.common.api.zze.zza(Unknown Source)
at com.google.android.gms.common.api.zze$zzb$1.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:794)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:610)
at dalvik.system.NativeStart.main(Native Method)
You've geiven setContentView(R.layout.activity_main); in the oncreate() of SelectSNActivity. Replace it with setContentView(R.layout.activity_select_sn);
I follow code at page: http://socket.io/blog/native-socket-io-and-android/
and download, run successfully project https://github.com/nkzawa/socket.io-android-chat.
And I want to connect socket io with my node server
Code at: server nodejs version of socket io "version": "1.3.5",
var socketIO = require('socket.io'),
http = require('http'),
port = process.env.PORT || 8080,
ip = process.env.IP || '192.168.0.105', //My IP address. I try to "127.0.0.1" but it the same => don't run
server = http.createServer().listen(port, ip, function() {
console.log("IP = " , ip);
console.log("start socket successfully");
});
io = socketIO.listen(server);
//io.set('match origin protocol', true);
io.set('origins', ':');
var run = function(socket){
socket.on("message", function(value) {
console.log(value);
});
socket.on("user-join", function(value) {
console.log(value + "user-join");
socket.broadcast.emit("new-users", value);
});
}
io.sockets.on('connection', run);
Code at Android:
package com.example.phamhuu.chatnodejs;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.github.nkzawa.socketio.client.IO;
import com.github.nkzawa.socketio.client.Socket;
import java.net.URISyntaxException;
public class MainActivity extends ActionBarActivity {
private Socket mSocket;
{
try {
IO.Options options = new IO.Options();
options.port = 8080;
mSocket = IO.socket("http://192.168.0.105:8080");
//mSocket = IO.socket("http://chat.socket.io");
} catch (URISyntaxException e) {
Log.e("abc", "index=" + e);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSocket.connect();
Log.e("result socket connect", String.valueOf(mSocket.connected()));
mSocket.emit("message", "Send message to server.");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I make sure add 'android.permission.INTERNET'
I try it on real device (My PC and my device the same wifi )but socket can't connect to server at address: 192.168.0.105 port: 8080
Can you help me?
Thanks very much.
Not really an answer to the question, but if you want to create a chat with Node.JS which works for also android clients, you can take a look at the alternative: JXM (on github) - messaging backend for JXcore (open sourced fork of Node.JS).
The problem you describe here probably will not be relevant any more.
There are practically ready samples to be used as they are (server part; clients: browsers, android, node).
I've wrote my few cents on this subject here: Simple Node.js chat program NOT using socket.io
I'm checking avalibility of google play services on device. I do it with these code:
final int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
final DialogInterface.OnCancelListener cancelListener = new DialogInterface.OnCancelListener() {
#Override
public void onCancel(final DialogInterface dialog) {
finish();
}
};
final Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(
resultCode, this, GOOGLE_PLAY_SERVICES_REQUEST_CODE, cancelListener
);
errorDialog.show();
}
I get resultCode = 2 (it's mean that Google Play Services needs to update). Dialog is shown, but instead of text, I get paths to layout.
It's looks like there are some interference of resource in app and resource in PlaYServices lib. But how it's possible and how to avoid id?
Since the accepted answer is somewhat unclear, I'll leave a signpost with my conclusions (mostly extracted from the comments on the question) which I believe are correct.
Short version: It seems that resource ids were incorrectly generated for this app.
It's obvious that the Google Play Services dialog intended to show strings in those places. The getErrorDialog() method is implemented like this (obfuscated, but the meaning can still be understood):
...
case 1:
return localBuilder.setTitle(R.string.common_google_play_services_install_title).create();
case 3:
return localBuilder.setTitle(R.string.common_google_play_services_enable_title).create();
case 2:
return localBuilder.setTitle(R.string.common_google_play_services_update_title).create();
...
Also, mistakenly doing something like getResources().getString(R.layout.my_layout) will return a string with the name of the original resource file ("res/layout/my_layout.xml").
So, we can conclude that, for some reason, the value of the Play Services Library resource, say, com.google.android.gms.R.string.common_google_play_services_install_title is actually the same as for the resource R.layout.dialog_share in the application project.
This probably stems for an incorrect build process, or an incorrect usage of the Google Play Services library (for example, including its jar directly, without the corresponding library process).
I have tested the code with google play service library version 4452000(use version >= 4452000). The code is as follows:
public class MainActivity extends Activity{
ProgressBar pBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
final DialogInterface.OnCancelListener cancelListener = new DialogInterface.OnCancelListener() {
#Override
public void onCancel(final DialogInterface dialog) {
finish();
}
};
final Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(
resultCode, this, 10, cancelListener
);
errorDialog.show();
}
}
}
Check your version of google play services and update if needed.
Here's the class I've been working on to check google play. It's not in production later this summer it will be so let me know with a comment if you have problems. It works tested on zten9120 and HTC EVO. The flow is like this. If static method isGooglePlay(context) returns false. Initialize the class and call the non static isgoogleplay() which will present the dialog to the user if googleplay services is not installed. The oncofigurationchange method handles when the device is rotated. onstop sets the class to null.
Modify three events in your activity.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!MyGooglePlay.isGooglePlay(getApplicationContext())) {
myGP = new MyGooglePlay(this);
myGP.isGooglePlay();
}
#Override
public void onStop() {
super.onStop();
myGP = null;
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (myGP != null) {
if (myGP.errorFragment.isVisible()) {
myGP.errorFragment.dismissAllowingStateLoss();
}
}
}
Here's the code which I keep in separate class
package com.gosylvester.bestrides.util;
import android.app.Dialog;
import android.content.Context;
import android.content.IntentSender;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.ActionBarActivity;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
public class MyGooglePlay {
private static final int CONNECTION_FAILURE_RESOLUTION_REQUEST = 31502;
private ActionBarActivity activity;
private FragmentManager fragManager;
public MyGooglePlay(ActionBarActivity activity) {
this.activity = activity;
this.fragManager = activity.getSupportFragmentManager();
}
public static boolean isGooglePlay(Context context) {
return (GooglePlayServicesUtil.isGooglePlayServicesAvailable(context) == ConnectionResult.SUCCESS);
}
public boolean isGooglePlay() {
if (isGooglePlay(activity)) {
return true;
} else {
return checkGooglePlay();
}
}
private static final String DIALOG_ERROR = "dialog_error";
public ErrorDialogFragment errorFragment;
private boolean checkGooglePlay() {
int mIsGooglePlayServicesAvailable = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(activity);
switch (mIsGooglePlayServicesAvailable) {
case ConnectionResult.SUCCESS:
return true;
default:
Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(
mIsGooglePlayServicesAvailable, activity,
CONNECTION_FAILURE_RESOLUTION_REQUEST);
// If Google Play services can provide an error dialog
if (errorDialog != null) {
// Create a new DialogFragment for the error dialog
errorFragment = ErrorDialogFragment.newInstance();
// Set the dialog in the DialogFragment
errorFragment.setDialog(errorDialog);
// Show the error dialog in the DialogFragment
errorFragment.show(fragManager, "LocationUpdates");
}
// case ConnectionResult.SERVICE_MISSING:
// case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED:
// case ConnectionResult.SERVICE_DISABLED:
// case ConnectionResult.SERVICE_INVALID:
// case ConnectionResult.DATE_INVALID:
}
return false;
}
public void dismissMe() {
DialogFragment frag = (DialogFragment) fragManager
.findFragmentByTag("LocationUpdates");
if (frag != null) {
frag.dismissAllowingStateLoss();
}
}
public static class ErrorDialogFragment extends DialogFragment {
// Global field to contain the error dialog
private Dialog mDialog;
static ErrorDialogFragment newInstance() {
ErrorDialogFragment d = new ErrorDialogFragment();
return d;
}
// Default constructor. Sets the dialog field to null
public ErrorDialogFragment() {
super();
mDialog = null;
}
// Set the dialog to display
public void setDialog(Dialog dialog) {
mDialog = dialog;
}
public void onPause(){
super.onPause();
this.dismissAllowingStateLoss();
}
// Return a Dialog to the DialogFragment.
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return mDialog;
}
}
public void onConnectionFailed(ConnectionResult connectionResult) {
/*
* Google Play services can resolve some errors it detects. If the error
* has a resolution, try sending an Intent to start a Google Play
* services activity that can resolve error.
*/
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(activity,
CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
/*
* If no resolution is available, display a dialog to the user with
* the error.
*/
showErrorDialog(connectionResult.getErrorCode(), activity);
}
}
/* Creates a dialog for an error message */
private void showErrorDialog(int errorCode, ActionBarActivity activity) {
// Create a fragment for the error dialog
ErrorDialogFragment dialogFragment = new ErrorDialogFragment();
// Pass the error that should be displayed
Bundle args = new Bundle();
args.putInt(DIALOG_ERROR, errorCode);
dialogFragment.setArguments(args);
dialogFragment
.show(activity.getSupportFragmentManager(), "errordialog");
}
}
Good Luck with getting google play services installed.
public static boolean isGooglePlayServiceAvailable(Context context) {
boolean isAvailable = false;
int result = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(context);
if (result == ConnectionResult.SUCCESS) {
Log.d(TAG, "Play Service Available");
isAvailable = true;
} else {
Log.d(TAG, "Play Service Not Available");
if (GooglePlayServicesUtil.isUserRecoverableError(result)) {
GooglePlayServicesUtil.getErrorDialog(result,
(Activity) context, PLAY_SERVICES_RESOLUTION_REQUEST)
.show();
} else {
Log.d(TAG, "Play Service Not Available");
GooglePlayServicesUtil.getErrorDialog(result,
(Activity) context, PLAY_SERVICES_RESOLUTION_REQUEST)
.show();
}
}
return isAvailable;
}
Updated answer : (as per GooglePlayServicesUtil.getErrorDialog is null)
If Google Play Services is not installed on the device, you may not be able to use the error dialog.
As per Rahim's comment in the above, you should only use the dialog if you have an "isUserRecoverableError" (his code):
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (status != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(status)) {
GooglePlayServicesUtil.getErrorDialog(status, this,
REQUEST_CODE_RECOVER_PLAY_SERVICES).show();
} else {
Toast.makeText(this, "This device is not supported.", Toast.LENGTH_LONG).show();
finish();
}
}
UPDATE - (from http://www.riskcompletefailure.com/2013/03/common-problems-with-google-sign-in-on.html)
One additional bug that surfaced quite a lot around the release of the latest version of Google Play Services was the onConnectionFailed method being called with a ConnectionResult which does not have a resolution, and has an error code of ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED.
As you might guess from the name, this indicates that the version of Google Play Services on the device is too low. Normally new versions will be updated automatically, but there is always a time delay in the roll out, so it is quite possible to get this error as updates are released.
You can handle this in the onConnectionFailed by calling getErrorDialog on GooglePlayServicesUtil, but the best way is to actually check whether Google Play Services is installed and up to date before even trying to connect. You can see a snippet of how to do this in the documentation.
So this is suggesting that this error (as you yourself say) should be recoverable, although note the clause that I have made bold. I am not convinced that this dialog would always be usable. Common sense suggests to me that this might depend on the version from which you were upgrading. So I recommend that you explicitly check that the error is marked as recoverable. If it is marked as recoverable then this looks like a bug in Google Play Services.
I found solution. I don't undertand why it's happening, but there is a solution.
I've built my project with maven and include a google play services framework as android library project.
Today, I've migrated to gradle and include dependecy go GPS with gradle and it solved my problem.
Im trying to do this tutorial
But keep getting this error:
08-21 14:12:49.599: E/AndroidRuntime(714):
java.lang.NoClassDefFoundError:
com.akiraapps.LicenseCheck$MyLicenseCheckerCallback
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings.Secure;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.vending.licensing.AESObfuscator;
import com.google.android.vending.licensing.LicenseChecker;
import com.google.android.vending.licensing.LicenseCheckerCallback;
import com.google.android.vending.licensing.Policy;
import com.google.android.vending.licensing.ServerManagedPolicy;
public class LicenseCheck extends Activity {
private static final String BASE64_PUBLIC_KEY = "no";
private static final byte[] SALT = new byte[] { no};
private TextView mStatusText;
private Button mCheckLicenseButton;
private LicenseCheckerCallback mLicenseCheckerCallback;
private LicenseChecker mChecker;
// A handler on the UI thread.
private Handler mHandler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.main);
mStatusText = (TextView) findViewById(R.id.status_text);
mCheckLicenseButton = (Button) findViewById(R.id.check_license_button);
mCheckLicenseButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
doCheck();
}
});
mHandler = new Handler();
// Try to use more data here. ANDROID_ID is a single point of attack.
String deviceId = Secure.getString(getContentResolver(), Secure.ANDROID_ID);
// Library calls this when it's done.
mLicenseCheckerCallback = new MyLicenseCheckerCallback();
// Construct the LicenseChecker with a policy.
mChecker = new LicenseChecker(
this, new ServerManagedPolicy(this,
new AESObfuscator(SALT, getPackageName(), deviceId)),
BASE64_PUBLIC_KEY);
doCheck();
}
protected Dialog onCreateDialog(int id) {
final boolean bRetry = id == 1;
return new AlertDialog.Builder(this)
.setTitle(R.string.unlicensed_dialog_title)
.setMessage(bRetry ? R.string.unlicensed_dialog_retry_body : R.string.unlicensed_dialog_body)
.setPositiveButton(bRetry ? R.string.retry_button : R.string.buy_button, new DialogInterface.OnClickListener() {
boolean mRetry = bRetry;
public void onClick(DialogInterface dialog, int which) {
if ( mRetry ) {
doCheck();
} else {
Intent marketIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(
"http://market.android.com/details?id=" + getPackageName()));
startActivity(marketIntent);
}
}
})
.setNegativeButton(R.string.quit_button, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
}).create();
}
private void doCheck() {
mCheckLicenseButton.setEnabled(false);
setProgressBarIndeterminateVisibility(true);
mStatusText.setText(R.string.checking_license);
mChecker.checkAccess(mLicenseCheckerCallback);
}
private void displayResult(final String result) {
mHandler.post(new Runnable() {
public void run() {
mStatusText.setText(result);
setProgressBarIndeterminateVisibility(false);
mCheckLicenseButton.setEnabled(true);
}
});
}
private void displayDialog(final boolean showRetry) {
mHandler.post(new Runnable() {
public void run() {
setProgressBarIndeterminateVisibility(false);
showDialog(showRetry ? 1 : 0);
mCheckLicenseButton.setEnabled(true);
}
});
}
private class MyLicenseCheckerCallback implements LicenseCheckerCallback {
public void allow(int policyReason) {
System.out.println("Allow");
if (isFinishing()) {
// Don't update UI if Activity is finishing.
return;
}
// Should allow user access.
displayResult(getString(R.string.allow));
}
public void dontAllow(int policyReason) {
System.out.println("dontAllow");
if (isFinishing()) {
// Don't update UI if Activity is finishing.
return;
}
displayResult(getString(R.string.dont_allow));
// Should not allow access. In most cases, the app should assume
// the user has access unless it encounters this. If it does,
// the app should inform the user of their unlicensed ways
// and then either shut down the app or limit the user to a
// restricted set of features.
// In this example, we show a dialog that takes the user to Market.
// If the reason for the lack of license is that the service is
// unavailable or there is another problem, we display a
// retry button on the dialog and a different message.
displayDialog(policyReason == Policy.RETRY);
}
public void applicationError(int errorCode) {
System.out.println("applicationError");
if (isFinishing()) {
// Don't update UI if Activity is finishing.
return;
}
// This is a polite way of saying the developer made a mistake
// while setting up or calling the license checker library.
// Please examine the error code and fix the error.
String result = String.format(getString(R.string.application_error), errorCode);
displayResult(result);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
mChecker.onDestroy();
}
}
I follow the tutorial for setting up LVL as a library project and those imports seem to be ok.
Why do I get this error? Why can it not find the inner class? If I right click and say show definition it jumps to the inner class.
I had same problem.
Below steps solved the probelm
take standard library example
coppied the library.jar file from the library project into your libs folder
So this SO Answer is what fixed it
I created a folder called libs and coppied the library.jar file from the library project included in the licensing package downloaded with the manager
What I dont understand is per this answer this should have been done for me
As I am using ADT 20.0.3
Basically it comes down to an example that I downloaded directly from android and got stuck for a few hours trying to figure out what was wrong and this seems like this step should have been in the readme/help docs OR Im doing something wrong.
If you know why this is the answer and how to do it better please answer and Ill change the answer to yours.
I had the exact same exception and none of the above recommendations worked for me.
However I got mine working by ensuring that your LVL project is a library project (right click project -> properties -> android and tick the "Is Libary" checkbo).
To include this in your application project remove any other references to this and apply the changes. Then if not already there navigate to (right click application project --> properties --> android) and in the library section click Add and select your LVL project. Apply Changes. Ok and clean project.
Hope this helps someone.