Migrating from AppState API to Saved Games API - android

So I'm trying to put some modifications on this code now the problem is the application refuses to connect to the game play service and load data , because it uses the old appstate api ! Now i need to migrate from the old Appstate to the new Saved Gamed API
The Android Manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="maths.workout.jellyapp"
android:versionCode="4"
android:versionName="1.3" >
<uses-sdk
android:minSdkVersion="9"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.arkay.funwithmaths.HomeMenuActivity"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:theme="#android:style/Theme.Black.NoTitleBar" >
</activity>
<activity
android:name="com.arkay.funwithmaths.SplashScreenActivity"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:theme="#android:style/Theme.Black.NoTitleBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.arkay.funwithmaths.MultiPlayerPlayActivity"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:theme="#android:style/Theme.Black.NoTitleBar.Fullscreen" >
</activity>
<activity
android:name="com.arkay.funwithmaths.SinglePlayerPlayFragment"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:theme="#android:style/Theme.Black.NoTitleBar" >
</activity>
<activity
android:name="com.arkay.funwithmaths.SettingActivity"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:theme="#android:style/Theme.Black.NoTitleBar" >
</activity>
<!-- <activity
android:name="com.google.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" /> -->
<activity
android:name="com.google.android.gms.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" />
<!-- Google Play Service -->
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version"/>
<meta-data android:name="com.google.android.gms.appstate.APP_ID"
android:value="#string/app_id" />
<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" />
<!-- End Google Play -->
</application>
The Home Menu Activiy
package com.arkay.funwithmaths;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import maths.workout.jellyapp.R;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.appstate.AppStateManager;
import com.google.android.gms.appstate.AppStateStatusCodes;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.games.Games;
import com.google.example.games.basegameutils.BaseGameActivity;
/**
* Home Screen of the app. It will display tow button one for Play and one for play multiplayer
* #author I-BALL
*
*/
public class HomeMenuActivity extends BaseGameActivity implements
View.OnClickListener, GooglePlayServicesClient.OnConnectionFailedListener, SinglePlayerPlayFragment.Listener {
public static final String PREFS_NAME = "preferences";
private static final String DATABASE_NAME = "database.db";
public static final String MUSIC_SOUND = "music_sound";
public static final String SOUND_EFFECT = "sound_effect";
public static final String VIBRATION = "vibration";
public static final String THIS_lEVEL_TOTAL_SCORE = "this_level_total_score";
public static final String IS_LAST_LEVEL_COMPLETED = "is_last_level_completed";
public static final String LAST_LEVEL_SCORE = "last_level_score";
public static final String MULTI_PLAYER_TOP_TRUE_SCORE="multi_player_game_score";
//Achivement
public static final String HOW_MANY_TIMES_PLAY_QUIZ = "how_many_time_play_quiz";
public static final String HOW_MANY_QUESTION_COMPLETED = "count_question_completed";
public static final String LEVEL_COMPLETED = "level_completed";
public static final String TOTAL_SCORE = "total_score";
public static final String LEVEL ="level";
public static final String VERY_CURIOUS_UNLOCK="is_very_curious_unlocked";
private Button btnSinglePlayer, btnMultiplayer, btnSetting,btnAchivement,btnLeaderBoard,btnHelp;
final int RC_RESOLVE = 5000, RC_UNUSED = 5001;
private static final int OUR_STATE_KEY = 2;
private GameData gameData;
SharedPreferences settings;
SinglePlayerPlayFragment singlePlayerFragment;
/** The view to show the ad. */
private AdView adView;
//Intersial Ads
private InterstitialAd interstitial;
private final Handler mHandler = new Handler();
private ProgressDialog progress;
public HomeMenuActivity() {
super( BaseGameActivity.CLIENT_GAMES | BaseGameActivity.CLIENT_APPSTATE);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFormat(PixelFormat.RGBA_8888);
setContentView(R.layout.activity_home_menu);
settings = getSharedPreferences(HomeMenuActivity.PREFS_NAME, 0);
gameData = new GameData(getSharedPreferences(HomeMenuActivity.PREFS_NAME, 0));
btnSinglePlayer = (Button)findViewById(R.id.btnSinglePlayer);
btnSinglePlayer.setOnClickListener(this);
btnMultiplayer = (Button)findViewById(R.id.btnMultiplayer);
btnMultiplayer.setOnClickListener(this);
btnSetting = (Button)findViewById(R.id.btnSetting);
btnSetting.setOnClickListener(this);
btnAchivement = (Button)findViewById(R.id.btnAchivement);
btnAchivement.setOnClickListener(this);
btnLeaderBoard = (Button)findViewById(R.id.btnLeaderBoard);
btnLeaderBoard.setOnClickListener(this);
btnHelp= (Button)findViewById(R.id.btnHelp);
btnHelp.setOnClickListener(this);
checkDB();
findViewById(R.id.sign_in_button).setOnClickListener(this);
findViewById(R.id.sign_out_button).setOnClickListener(this);
singlePlayerFragment = new SinglePlayerPlayFragment();
singlePlayerFragment.setListener(this);
SignInButton mSignInButton = (SignInButton)findViewById(R.id.sign_in_button);
mSignInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// start the asynchronous sign in flow
System.out.println("Click on Sign-in");
beginUserInitiatedSignIn();
}
});
/** Create the interstitial.*/
interstitial = new InterstitialAd(this);
interstitial.setAdUnitId(getString(R.string.admob_intersititial));
/** Create ad request. */
Resources ress = getResources();
/**set testmost false when publish app*/
boolean isTestMode = ress.getBoolean(R.bool.istestmode);
AdRequest adRequest =null;
if(isTestMode){
adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice("B15149A4EC1ED23173A27B04134DD483").build();
}else{
adRequest = new AdRequest.Builder().build();
}
/** Begin loading your interstitial. */
interstitial.loadAd(adRequest);
// Create an ad.
adView = new AdView(getApplicationContext());
adView.setAdSize(AdSize.SMART_BANNER);
adView.setAdUnitId(getString(R.string.admob_banner));
// Add the AdView to the view hierarchy. The view will have no size until the ad is loaded.
LinearLayout layout = (LinearLayout) findViewById(R.id.ads_layout);
layout.addView(adView);
mHandler.postDelayed(mUpdateUITimerTask, 10 * 1200);
progress = new ProgressDialog(this);
progress.setTitle("Please Wait!!");
progress.setMessage("Data Loading..");
progress.setCancelable(false);
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.show();
}
/**
* Display Interstital ads.
*/
public void displayInterstitial() {
if (interstitial.isLoaded()) {
interstitial.show();
}
}
public void checkDB() {
try {
String packageName = this.getPackageName();
String destPath = "/data/data/" + packageName + "/databases";
String fullPath = "/data/data/" + packageName + "/databases/"+ DATABASE_NAME;
// this database folder location
File f = new File(destPath);
// this database file location
File obj = new File(fullPath);
// check if databases folder exists or not. if not create it
if (!f.exists()) {
f.mkdirs();
f.createNewFile();
}else{
boolean isDelete = f.delete();
Log.i("Delete", "Delete"+isDelete);
}
// check database file exists or not, if not copy database from assets
if (!obj.exists()) {
this.CopyDB(fullPath);
}else{
this.CopyDB(fullPath);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void CopyDB(String path) throws IOException {
InputStream databaseInput = null;
String outFileName = path;
OutputStream databaseOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
// open database file from asset folder
databaseInput = this.getAssets().open(DATABASE_NAME);
while ((length = databaseInput.read(buffer)) > 0) {
databaseOutput.write(buffer, 0, length);
databaseOutput.flush();
}
databaseInput.close();
databaseOutput.flush();
databaseOutput.close();
}
#Override
public void onSignInFailed() {
System.out.println("Sing In Fail");
findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
findViewById(R.id.sign_out_button).setVisibility(View.GONE);
findViewById(R.id.sign_out_bar).setVisibility(View.GONE);
findViewById(R.id.sign_in_bar).setVisibility(View.VISIBLE);
progress.cancel();
}
#Override
public void onSignInSucceeded() {
System.out.println("Sing In Succcess");
findViewById(R.id.sign_in_button).setVisibility(View.GONE);
findViewById(R.id.sign_out_button).setVisibility(View.VISIBLE);
findViewById(R.id.sign_in_bar).setVisibility(View.GONE);
findViewById(R.id.sign_out_bar).setVisibility(View.VISIBLE);
loadFromCloud();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
System.out.println("Result Code: onConnectionFailed: " + arg0);
}
public void unlockAchievement(int achievementId, String fallbackString) {
if (isSignedIn()) {
Games.Achievements.unlock(getApiClient(), getString(achievementId));
}
}
#Override
public void onStartGameRequested(boolean hardMode) {
getSupportFragmentManager().popBackStack();
this.findViewById(R.id.linearLayout1).setVisibility(View.VISIBLE);
}
#Override
public void onShowAchievementsRequested() {
// TODO Auto-generated method stub
if (isSignedIn()) {
startActivityForResult(Games.Achievements.getAchievementsIntent(getApiClient()),
RC_UNUSED);
} else {
showAlert(getString(R.string.achievements_not_available));
}
}
#Override
public void onShowLeaderboardsRequested() {
}
#Override
public void onSignInButtonClicked() {
}
#Override
public void onSignOutButtonClicked() {
}
boolean addList = false;
#Override
public void onBackPressed() {
getSupportFragmentManager().popBackStack();
this.findViewById(R.id.linearLayout1).setVisibility(View.VISIBLE);
if(getSupportFragmentManager().getBackStackEntryCount()==0){
super.onBackPressed();
displayInterstitial(false);
}
}
public void displayInterstitial(boolean isFirstTime) {
if (interstitial.isLoaded()) {
interstitial.show();
if(isFirstTime){
// Create the interstitial.
interstitial = new InterstitialAd(this);
interstitial.setAdUnitId(getString(R.string.admob_intersititial));
// Begin loading your interstitial.
interstitial.loadAd(new AdRequest.Builder().build());
}
}
}
#Override
public void displyHomeScreen() {
getSupportFragmentManager().popBackStack();
}
/**
* Update leaderboards with the user's score.
*
* #param finalScore The score the user got.
*/
#Override
public void updateLeaderboards(int finalScore) {
if (isSignedIn()) {
if (finalScore >= 0) {
Games.Leaderboards.submitScore(getApiClient(), getString(R.string.leaderboard_fun_with_maths),
finalScore);
byte[] scoreData = intToByteArray(finalScore);
AppStateManager.update(getApiClient(), 1, scoreData);
}
}
}
public static byte[] intToByteArray(int a) {
return BigInteger.valueOf(a).toByteArray();
}
public static int byteArrayToInt(byte[] b) {
return new BigInteger(b).intValue();
}
public void loadFromCloud() {
if(isSignedIn()){
AppStateManager.load(getGameHelper().getApiClient(), OUR_STATE_KEY).setResultCallback(mResultCallback);
}
}
public void saveToCloud() {
if(isSignedIn()){
AppStateManager.update(getGameHelper().getApiClient(), OUR_STATE_KEY, gameData.toBytes());
}
}
ResultCallback<AppStateManager.StateResult> mResultCallback = new
ResultCallback<AppStateManager.StateResult>() {
#Override
public void onResult(AppStateManager.StateResult result) {
AppStateManager.StateConflictResult conflictResult = result.getConflictResult();
AppStateManager.StateLoadedResult loadedResult = result.getLoadedResult();
if (loadedResult != null) {
processStateLoaded(loadedResult);
} else if (conflictResult != null) {
processStateConflict(conflictResult);
}
}
};
private void processStateConflict(AppStateManager.StateConflictResult result) {
// Need to resolve conflict between the two states.
// We do that by taking the union of the two sets of cleared levels,
// which means preserving the maximum star rating of each cleared
// level:
byte[] serverData = result.getServerData();
byte[] localData = result.getLocalData();
GameData localGame = new GameData(localData);
GameData serverGame = new GameData(serverData);
GameData resolvedGame = localGame.unionWith(serverGame);
AppStateManager.resolve(getApiClient(), result.getStateKey(), result.getResolvedVersion(),
resolvedGame.toBytes()).setResultCallback(mResultCallback);
}
private void processStateLoaded(AppStateManager.StateLoadedResult result) {
switch (result.getStatus().getStatusCode()) {
case AppStateStatusCodes.STATUS_OK:
// Data was successfully loaded from the cloud: merge with local data.
gameData = gameData.unionWith(new GameData(result.getLocalData()));
saveToCloud();
gameData.saveDataLocal(settings);
GameData tem = new GameData(result.getLocalData());
System.out.println("Game Data: "+tem);
System.out.println("Local Data: "+gameData);
progress.cancel();
break;
case AppStateStatusCodes.STATUS_STATE_KEY_NOT_FOUND:
// key not found means there is no saved data. To us, this is the same as
// having empty data, so we treat this as a success.
progress.cancel();
break;
case AppStateStatusCodes.STATUS_NETWORK_ERROR_NO_DATA:
// can't reach cloud, and we have no local state. Warn user that
// they may not see their existing progress, but any new progress won't be lost.
progress.cancel();
break;
case AppStateStatusCodes.STATUS_NETWORK_ERROR_STALE_DATA:
// can't reach cloud, but we have locally cached data.
progress.cancel();
break;
case AppStateStatusCodes.STATUS_CLIENT_RECONNECT_REQUIRED:
// need to reconnect AppStateClient
reconnectClient();
break;
default:
break;
}
}
#Override
public GameData getGameData() {
return this.gameData;
}
#Override
public void saveDataToCloud() {
saveToCloud();
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btnSinglePlayer:
getSupportFragmentManager().beginTransaction().replace( R.id.fragment_container, singlePlayerFragment ).addToBackStack( "tag" ).commit();
break;
case R.id.btnMultiplayer:
Intent selectLevelActivity = new Intent(this, MultiPlayerPlayActivity.class);
startActivity(selectLevelActivity);
break;
case R.id.btnSetting:
selectLevelActivity = new Intent(this, SettingActivity.class);
startActivity(selectLevelActivity);
break;
case R.id.btnLeaderBoard:
if (isSignedIn()) {
SharedPreferences.Editor edit = settings.edit();
edit.putInt(VERY_CURIOUS_UNLOCK, 1);
edit.commit();
unlockAchievement(R.string.achievement_very_curious,"Very Curious");
startActivityForResult(Games.Leaderboards.getAllLeaderboardsIntent(getApiClient()),RC_UNUSED);
} else {
showAlert(getString(R.string.leaderboards_not_available));
}
break;
case R.id.btnAchivement:
if (isSignedIn()) {
unlockAchievement(R.string.achievement_curious, "Curious");
startActivityForResult(Games.Achievements.getAchievementsIntent(getApiClient()),RC_UNUSED);
}else {
showAlert(getString(R.string.achievements_not_available));
}
break;
case R.id.btnHelp:
QuizCompletedForMultiPlayerDialog cdd=new QuizCompletedForMultiPlayerDialog(this);
cdd.show();
break;
}
if (v.getId() == R.id.sign_in_button) {
beginUserInitiatedSignIn();
findViewById(R.id.sign_in_button).setVisibility(View.GONE);
findViewById(R.id.sign_out_button).setVisibility(View.VISIBLE);
findViewById(R.id.sign_in_bar).setVisibility(View.GONE);
findViewById(R.id.sign_out_bar).setVisibility(View.VISIBLE);
} else if (v.getId() == R.id.sign_out_button) {
signOut();
findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
findViewById(R.id.sign_out_button).setVisibility(View.GONE);
findViewById(R.id.sign_out_bar).setVisibility(View.GONE);
findViewById(R.id.sign_in_bar).setVisibility(View.VISIBLE);
}
}
#Override
public void onResume() {
super.onResume();
if (adView != null) {
adView.resume();
}
}
#Override
public void onPause() {
if (adView != null) {
adView.pause();
}
super.onPause();
}
/** Called before the activity is destroyed. */
#Override
public void onDestroy() {
// Destroy the AdView.
if (adView != null) {
adView.destroy();
}
super.onDestroy();
}
class QuizCompletedForMultiPlayerDialog extends Dialog implements
android.view.View.OnClickListener {
public Activity c;
public Dialog d;
int levelStaus = 1;
int levelNo = 1;
int lastLevelScore = 0;
public QuizCompletedForMultiPlayerDialog(Activity a) {
super(a);
this.c = a;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.custom_help_dialog);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnPlayAgain:
break;
case R.id.btnQuit:
default:
break;
}
dismiss();
}
}
/**
* Display Ads after some interval of game start.
*/
private final Runnable mUpdateUITimerTask = new Runnable() {
public void run() {
displayInterstitial(true);
}
};
}

Related

Sending notifications from smartphone to Wear OS smartwatch

I've been trying to develop a simple app that can send notifications from a smartphone to an Wear OS smartwatch (more specifically, a Huawei Smartwatch 2).
I've used this code as a basis: github link. Note that this code doens't have the "notifications part" I'm trying to develop.
The bottom line is: I can receive data on the smartwatch, but only when the app on it is running. The ServiceListener service, from what I could tell, from debugging, is not being activated. Basically, anything I write on that file, even Log data, isn't being displayed.
The ServiceListener service:
package com.example.nowor_000.sincronizaciondatos;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationManagerCompat;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.wearable.DataApi;
import com.google.android.gms.wearable.DataEvent;
import com.google.android.gms.wearable.DataEventBuffer;
import com.google.android.gms.wearable.DataMapItem;
import com.google.android.gms.wearable.MessageEvent;
import com.google.android.gms.wearable.Wearable;
import com.google.android.gms.wearable.WearableListenerService;
import static android.content.ContentValues.TAG;
import static com.google.android.gms.wearable.PutDataRequest.WEAR_URI_SCHEME;
/**
* Created by nowor_000 on 26/11/2015.
*/
public class ServiceListener extends WearableListenerService {
public static final String NOTIFICATION_PATH = "/notification";
public static final String NOTIFICATION_TIMESTAMP = "timestamp";
public static final String NOTIFICATION_TITLE = "title";
public static final String NOTIFICATION_CONTENT = "content";
public static final String ACTION_DISMISS = "com.example.nowor_000.sincronizaciondatos.DISMISS";
//private static final String WEAR_INICIAR_ACTIVIDAD = "/iniciar";
private static final String START_ACTIVITY_PATH = "/start-activity";
private int notificationId = 001;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "onStartCommand ServiceListener.");
if (null != intent) {
String action = intent.getAction();
if (ACTION_DISMISS.equals(action)) {
dismissNotification();
}
}
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDataChanged(DataEventBuffer dataEvents) {
Log.i(TAG, "onDataChanged ServiceListener.");
for (DataEvent dataEvent : dataEvents) {
if (dataEvent.getType() == DataEvent.TYPE_CHANGED) {
if (NOTIFICATION_PATH.equals(dataEvent.getDataItem().getUri().getPath())) {
DataMapItem dataMapItem = DataMapItem.fromDataItem(dataEvent.getDataItem());
String title = dataMapItem.getDataMap().getString(NOTIFICATION_TITLE);
String content = dataMapItem.getDataMap().getString(NOTIFICATION_CONTENT);
sendNotification(title, content);
}
}
}
}
private void sendNotification(String title, String content) {
Log.i(TAG, "Sending notification.");
// this intent will open the activity when the user taps the "open" action on the notification
Intent viewIntent = new Intent(this, MainActivity.class);
PendingIntent pendingViewIntent = PendingIntent.getActivity(this, 0, viewIntent, 0);
// this intent will be sent when the user swipes the notification to dismiss it
Intent dismissIntent = new Intent(ACTION_DISMISS);
PendingIntent pendingDeleteIntent = PendingIntent.getService(this, 0, dismissIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(title)
.setContentText(content)
.setDeleteIntent(pendingDeleteIntent)
.setContentIntent(pendingViewIntent);
Notification notification = builder.build();
NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(this);
notificationManagerCompat.notify(notificationId++, notification);
}
private void dismissNotification() {
new ServiceListener.DismissNotificationCommand(this).execute();
}
private class DismissNotificationCommand implements GoogleApiClient.ConnectionCallbacks, ResultCallback<DataApi.DeleteDataItemsResult>, GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "DismissNotification";
private final GoogleApiClient mGoogleApiClient;
public DismissNotificationCommand(Context context) {
mGoogleApiClient = new GoogleApiClient.Builder(context)
.addApi(Wearable.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
public void execute() {
mGoogleApiClient.connect();
}
#Override
public void onConnected(Bundle bundle) {
final Uri dataItemUri =
new Uri.Builder().scheme(WEAR_URI_SCHEME).path(NOTIFICATION_PATH).build();
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Deleting Uri: " + dataItemUri.toString());
}
Wearable.DataApi.deleteDataItems(
mGoogleApiClient, dataItemUri).setResultCallback(this);
}
#Override
public void onConnectionSuspended(int i) {
Log.d(TAG, "onConnectionSuspended");
}
#Override
public void onResult(DataApi.DeleteDataItemsResult deleteDataItemsResult) {
if (!deleteDataItemsResult.getStatus().isSuccess()) {
Log.e(TAG, "dismissWearableNotification(): failed to delete DataItem");
}
mGoogleApiClient.disconnect();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d(TAG, "onConnectionFailed");
}
}
}
The MainActivity on the smartphone:
package com.example.nowor_000.sincronizaciondatos;
import android.os.Bundle;
import android.provider.SyncStateContract;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.wearable.DataApi;
import com.google.android.gms.wearable.MessageApi;
import com.google.android.gms.wearable.Node;
import com.google.android.gms.wearable.NodeApi;
import com.google.android.gms.wearable.PutDataMapRequest;
import com.google.android.gms.wearable.PutDataRequest;
import com.google.android.gms.wearable.Wearable;
import static android.content.ContentValues.TAG;
public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, View.OnClickListener {
public static final String NOTIFICATION_PATH = "/notification";
public static final String NOTIFICATION_TIMESTAMP = "timestamp";
public static final String NOTIFICATION_TITLE = "title";
public static final String NOTIFICATION_CONTENT = "content";
public static final String ACTION_DISMISS = "de.peterfriese.notificationwithopenactivityonwearableaction.DISMISS";
/**
* sincronizacion
*/
private static final String KEY_CONTADOR = "com.example.key.contador";
private static final String ITEM_CONTADOR = "/contador";
/**
* sincronizacion
*/
private static final String WEAR_INICIAR_ACTIVIDAD = "/iniciar";
private static final String WEAR_ENVIAR_TEXTO = "/enviar_texto";
Button btnEnviarTexto;
EditText editText;
private int contador;
/**
* CLIENTE
*/
private GoogleApiClient apiClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
/**
*API CLIENT es clave para establecer la comunicación
*/
apiClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
addViews();
/**
* sincronizacion
*/
final TextView textoContador = (TextView) findViewById(R.id.textoContador);
textoContador.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
contador++;
textoContador.setText(Integer.toString(contador));
PutDataMapRequest putDataMapReq = PutDataMapRequest.create(ITEM_CONTADOR);
putDataMapReq.getDataMap().putInt(KEY_CONTADOR, contador);
PutDataRequest putDataReq = putDataMapReq.asPutDataRequest();
PendingResult<DataApi.DataItemResult> resultado = Wearable.DataApi.putDataItem(apiClient, putDataReq);
/**
* ESTA LINEA SE ME OLVIDO EN EL VIDEOTUTORIAL
*/
enviarMensaje(ITEM_CONTADOR, Integer.toString(contador));
}
});
/**
* sincronizacion
*/
}
private void addViews() {
editText = (EditText) findViewById(R.id.edtitText);
btnEnviarTexto = (Button) findViewById(R.id.btnEnviarTexto);
btnEnviarTexto.setOnClickListener(this);
}
#Override
public void onClick(View v) {
sendNotification();
switch (v.getId()) {
case R.id.btnEnviarTexto:
String text = editText.getText().toString();
if (!TextUtils.isEmpty(text)) {
enviarMensaje(WEAR_ENVIAR_TEXTO, text);
editText.getText().clear();
editText.requestFocus();
} else {
enviarMensaje(WEAR_ENVIAR_TEXTO, "\n->Escribe un mensaje, en el EditText<-");
}
break;
}
}
//<editor-fold desc="ENVIAR MENSAJE EditText">
private void enviarMensaje(final String path, final String texto) {
new Thread(new Runnable() {
#Override
public void run() {
NodeApi.GetConnectedNodesResult nodos = Wearable.NodeApi.getConnectedNodes(apiClient).await();
for (Node nodo : nodos.getNodes()) {
Wearable.MessageApi.sendMessage(apiClient, nodo.getId(), path, texto.getBytes())
.setResultCallback(
new ResultCallback<MessageApi.SendMessageResult>() {
#Override
public void onResult(MessageApi.SendMessageResult resultado) {
if (!resultado.getStatus().isSuccess()) {
Log.e("sincronizacion", "Error al enviar mensaje. Codigo" + resultado.getStatus().getStatusCode());
}
}
}
);
}
}
}).start();
}
//</editor-fold>
//<editor-fold desc="CICLO DE VIDA">
#Override
protected void onStart() {
super.onStart();
apiClient.connect();
}
#Override
protected void onStop() {
if (apiClient != null && apiClient.isConnected()) {
apiClient.disconnect();
}
super.onStop();
}
//</editor-fold>
//<editor-fold desc="METODOS API DATA LAYER">
#Override
public void onConnected(Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
//</editor-fold>
//<editor-fold desc="MENU">
#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);
}
//</editor-fold>
private void sendNotification() {
if (apiClient.isConnected()) {
Log.i(TAG, "Sending data.");
PutDataMapRequest dataMapRequest = PutDataMapRequest.create(NOTIFICATION_PATH);
// Make sure the data item is unique. Usually, this will not be required, as the payload
// (in this case the title and the content of the notification) will be different for almost all
// situations. However, in this example, the text and the content are always the same, so we need
// to disambiguate the data item by adding a field that contains teh current time in milliseconds.
dataMapRequest.getDataMap().putDouble(NOTIFICATION_TIMESTAMP, System.currentTimeMillis());
dataMapRequest.getDataMap().putString(NOTIFICATION_TITLE, "This is the title");
dataMapRequest.getDataMap().putString(NOTIFICATION_CONTENT, "This is a notification with some text.");
PutDataRequest putDataRequest = dataMapRequest.asPutDataRequest().setUrgent();
Wearable.DataApi.putDataItem(apiClient, putDataRequest);
} else {
Log.e(TAG, "No connection to wearable available!");
}
}
}
The AndroidManifest for the smartphone:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.nowor_000.sincronizaciondatos">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<!--ETIQUETA PPARA INDICAR LA VERSION DE GOOGLE PLAY QUE ESTAMOS USANDO -->
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
The AndroidManifest for the smartwatch:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.nowor_000.sincronizaciondatos">
<uses-feature android:name="android.hardware.type.watch" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#android:style/Theme.DeviceDefault">
<meta-data android:name="com.google.android.gms.version" android:value="#integer/google_play_services_version" />
<uses-library android:name="com.google.android.wearable"
android:required="true" />
<activity
android:name=".MainActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".ServiceListener"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.google.android.gms.wearable.DATA_CHANGED" />
<action android:name="com.google.android.gms.wearable.MESSAGE_RECEIVED" />
<data android:scheme="wear" android:host="*"
android:path="/start-activity" />
</intent-filter>
</service>
</application>
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE" />
</manifest>
If you need any more code please say. Thanks!

Realm Database / App crashes in start up / call realm.init(context) before creating a realm configuration

I'm a newbie in Android and I'm trying to create a Realm database by watching tutorials. But my app doesn't start, it crashes. My main idea is the user finds nearby shops, by his location, select type of shop if he wants (restaurant, caffee etc) and if he can't find the shop he wants, the app gives him the option to add a shop (by pin a marker in a map, select a name and a type). In the errors gives me call realm.init(context) before creating a realm configuration Whoever can help I'd appreciate it. This app is my graduation project. I've reached this far;
MainScreen.java
public class MainScreen extends AppCompatActivity {
private ImageButton btn;
Animation scale;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
scale = AnimationUtils.loadAnimation(this, R.anim.gps_button_animation);
btn = (ImageButton) findViewById(R.id.ImageButton);
btn.startAnimation(scale);
}
public void InfoActivity(View view) {
Intent intent = new Intent(this, InfoActivity.class);
startActivity(intent);
}
public void MapsActivity (View view){
Intent intent = new Intent(this, MapsActivity.class);
startActivity(intent);
}
public void Anazitisi (View view){
Intent intent = new Intent(this, Anazitisi.class);
startActivity(intent);
}
public void AddShopActivity (View view){
Intent intent = new Intent(this, AddShopActivity.class);
startActivity(intent);
}
}
AddShopActivity.java
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.example.konarx.a11042016.ShopProperties.Shop;
import io.realm.Realm;
import io.realm.RealmResults;
public class AddShopActivity extends MainScreen{
private EditText editText_name;
private Spinner spinner;
private ArrayAdapter<CharSequence> adapter;
private Button button_save;
private Realm realm;
private TextView textView_log;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_shop);
realm = Realm.getDefaultInstance();
editText_name = (EditText) findViewById(R.id.editName);
button_save = (Button) findViewById(R.id.buttonSave);
textView_log = (TextView) findViewById(R.id.textView_Log);
spinner = (Spinner)findViewById(R.id.spinner);
adapter = ArrayAdapter.createFromResource(this,R.array.eidoskatastimatos, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new android.widget.AdapterView.OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getBaseContext(), adapterView.getItemAtPosition(i)+" selected", Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
button_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
save_into_database(editText_name.getText().toString().trim(), spinner.getAdapter().toString().trim());
refresh_views();
}
});
}
private void refresh_views() {
RealmResults<Shop> shopRealmResults = realm.where(Shop.class).findAll();
String output = "";
for (Shop shop: shopRealmResults){
output += shop.toString();
}
textView_log.setText(output);
}
private void save_into_database(final String title, final String type) {
realm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm bgRealm) {
Shop shop = bgRealm.createObject(Shop.class);
shop.setTitle(title);
shop.setType(type);
}
}, new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess() {
Log.v("Database", "saved!");
}
}, new Realm.Transaction.OnError() {
#Override
public void onError(Throwable error) {
Log.v("Database", error.getMessage());
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
realm.close();
}
}
Shop.java
package com.example.konarx.a11042016.ShopProperties;
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
public class Shop extends RealmObject{
#PrimaryKey
private int id;
private String title;
private String type;
private String Latitude;
private String Longitude;
// Standard getters & setters
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getLatitude() {
return Latitude;
}
public void setLatitude(String latitude) {
Latitude = latitude;
}
public String getLongitude() {
return Longitude;
}
public void setLongitude(String longitude) {
Longitude = longitude;
}
#Override
public String toString() {
return "Shop{" +
"id=" + id +
", title='" + title + '\'' +
", type='" + type + '\'' +
", Latitude='" + Latitude + '\'' +
", Longitude='" + Longitude + '\'' +
'}';
}
}
BaseApplication.java
import android.app.Application;
import io.realm.Realm;
import io.realm.RealmConfiguration;
public class BaseApplication extends Application{
#Override
public void onCreate() {
super.onCreate();
RealmConfiguration config = new RealmConfiguration.Builder().build();
Realm.setDefaultConfiguration(config);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.konarx.a11042016">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-feature android:name="android.hardware.location.gps" />
<application
android:allowBackup="true"
android:icon="#drawable/logo"
android:label="#string/app_name"
android:name=".BaseApplication"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainScreen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".InfoActivity"
android:label="Πληροφορίες"></activity>
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:label="Χάρτης"></activity>
<activity
android:name=".Anazitisi"
android:label="Αναζήτηση"></activity>
<activity
android:name=".AddShopActivity"
android:label="Προσθήκη Καταστήματος"></activity>
</application>
</manifest>
public class BaseApplication extends Application{
#Override
public void onCreate() {
super.onCreate();
Realm.init(this); // add this line
RealmConfiguration config = new RealmConfiguration.Builder().build();
Realm.setDefaultConfiguration(config);
}
}

I am getting crash on the list view using volley library .

I am facing crash on the getting list view with use of volley library .
I have used login with Facebook separate . and got list view with volley library separate. But when i am integrating both then i am getting crash . I want to login with Facebook after successful login i want list view. But i am getting crash .
see in the image when i did with separate project then i am getting list view with volley library.
But after adding Facebook login. I am getting crash. Please tell me solution for same.
MainActivity.java
public class MainActivity extends Activity {
private CallbackManager callbackManager;
private LoginButton loginButton;
private TextView btnLogin;
private ProgressDialog progressDialog;
User user;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(this);
setContentView(R.layout.activity_main);
//Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
if(PrefUtils.getCurrentUser(MainActivity.this) != null){
//Intent homeIntent = new Intent(MainActivity.this, LogoutActivity.class);
Intent homeIntent = new Intent(MainActivity.this, ListViewActivity.class);
startActivity(homeIntent);
finish();
}
try {
PackageInfo info = getPackageManager().getPackageInfo(
"com.comida",
PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (PackageManager.NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
/* FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});*/
}
#Override
protected void onResume() {
super.onResume();
callbackManager=CallbackManager.Factory.create();
loginButton= (LoginButton)findViewById(R.id.login_button);
loginButton.setReadPermissions("public_profile", "email","user_friends");
btnLogin= (TextView) findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Loading...");
progressDialog.show();
loginButton.performClick();
loginButton.setPressed(true);
loginButton.invalidate();
loginButton.registerCallback(callbackManager, mCallBack);
loginButton.setPressed(false);
loginButton.invalidate();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
private FacebookCallback<LoginResult> mCallBack = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
progressDialog.dismiss();
// App code
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
Log.e("response: ", response + "");
try {
user = new User();
user.facebookID = object.getString("id").toString();
user.email = object.getString("email").toString();
user.name = object.getString("name").toString();
user.gender = object.getString("gender").toString();
PrefUtils.setCurrentUser(user,MainActivity.this);
}catch (Exception e){
e.printStackTrace();
}
Toast.makeText(MainActivity.this,"welcome "+user.name,Toast.LENGTH_LONG).show();
Intent intent=new Intent(MainActivity.this,ListViewActivity.class);
//Intent intent=new Intent(MainActivity.this,LogoutActivity.class);
startActivity(intent);
finish();
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender, birthday");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
progressDialog.dismiss();
}
#Override
public void onError(FacebookException e) {
progressDialog.dismiss();
}
};
#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);
}*/
}
ListViewActivity.java
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.ListView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.comida.MainActivity;
import com.comida.R;
import com.comida.adater.CustomListAdapter;
import com.comida.app.AppController;
import com.comida.model.Movie;
public class ListViewActivity extends Activity {
// Log tag
private static final String TAG = ListViewActivity.class.getSimpleName();
private static final String url = "http://wpgmiiyrhn.localtunnel.me/api/v1/restaurants?per_page=10&page=1&sort_col=average_ratings";
// Movies json url
//private static final String url = "http://api.androidhive.info/json/movies.json";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listview);
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapter(this, movieList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// changing action bar color
getActionBar().setBackgroundDrawable(
new ColorDrawable(Color.parseColor("#1b1b1b")));
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
//movie.setTitle(obj.getString("title"));
movie.setName(obj.getString("name"));
//movie.setThumbnailUrl(obj.getString("image"));
movie.setThumbnailUrl(obj.getString("image_url"));
movie.setAverage_ratings(obj.getString("average_ratings"));
movie.setCuisine(obj.getString("cuisine"));
movie.setAddress(obj.getJSONObject("address").getString("area"));
//movie.setAddress(obj.getString("address"));
//movie.setYear(obj.getInt("releaseYear"));
// Genre is json array
/*JSONArray genreArry = obj.getJSONArray("genre");
ArrayList<String> genre = new ArrayList<String>();
for (int j = 0; j < genreArry.length(); j++) {
genre.add((String) genreArry.get(j));
}
movie.setGenre(genre);*/
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
/*#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}*/
}
adater -> CustomListAdapter.java
import com.comida.R;
import com.comida.app.AppController;
import com.comida.model.Movie;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import java.util.List;
public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Movie> movieItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapter(Activity activity, List<Movie> movieItems) {
this.activity = activity;
this.movieItems = movieItems;
}
#Override
public int getCount() {
return movieItems.size();
}
#Override
public Object getItem(int location) {
return movieItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_row, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
/*ImageView img;
img = (ImageView)convertView
.findViewById(R.id.img);
img.setImageResource(R.drawable.bc);
else {*/
NetworkImageView _ImageView = (NetworkImageView) convertView.findViewById(R.id.thumbnail);
_ImageView.setDefaultImageResId(R.drawable.bc);
//NetworkImageView.setImageUrl(m.getThumbnailUrl(), ImageLoader);
/*NetworkImageView thumbNail = (NetworkImageView) convertView
.findViewById(R.id.thumbnail);*/
TextView name = (TextView) convertView.findViewById(R.id.name);
TextView average_ratings = (TextView) convertView.findViewById(R.id.average_ratings);
TextView address=(TextView) convertView.findViewById(R.id.area);
TextView cuisine =(TextView) convertView.findViewById(R.id.cuisine);
//TextView genre = (TextView) convertView.findViewById(R.id.genre);
//TextView year = (TextView) convertView.findViewById(R.id.releaseYear);
// getting movie data for the row
Movie m = movieItems.get(position);
// thumbnail image
//_ImageView.setImageUrl(m.getThumbnailUrl(), imageLoader);
/*if (TextUtils.isEmpty(m.getThumbnailUrl()))
thumbNail.setImageResource(R.drawable.bc);
else
//Log.d("KeyHash:","Neeraj");*/
_ImageView.setImageUrl(m.getThumbnailUrl(), imageLoader);
/*if (m.getThumbnailUrl().compareTo("")!=0)
thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);
//else{
//thumbNail.setImageResource(R.drawable.bc);
else {
thumbNail.setDefaultImageResId(R.drawable.bc);
//thumbNail.setErrorImageResId(R.drawable.bc);
}*/
// title
name.setText(m.getName());
// rating
average_ratings.setText("Rating: " + String.valueOf(m.getAverage_ratings()));
address.setText("Area: " + String.valueOf(m.getAddress()));
cuisine.setText("Cusine: " + String.valueOf(m.getCuisine()));
/*// genre
String genreStr = "";
for (String str : m.getGenre()) {
genreStr += str + ", ";
}
genreStr = genreStr.length() > 0 ? genreStr.substring(0,
genreStr.length() - 2) : genreStr;
genre.setText(genreStr);
// release year
year.setText(String.valueOf(m.getYear()));*/
return convertView;
}
}
app ->appcontroller.java
import com.comida.util.LruBitmapCache;
import android.app.Application;
import android.text.TextUtils;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public ImageLoader getImageLoader() {
getRequestQueue();
if (mImageLoader == null) {
mImageLoader = new ImageLoader(this.mRequestQueue,
new LruBitmapCache());
}
return this.mImageLoader;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
// set the default tag if tag is empty
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
Movie -> movie.java
public class Movie {
private String name, thumbnailUrl;
//private int year;
private String average_ratings,area,cuisine,address;
// private ArrayList<String> genre;
public Movie() {
}
public Movie(String name, String thumbnailUrl, String average_ratings, String area, String cuisine, String address
) {
this.name = name;
this.thumbnailUrl = thumbnailUrl;
//this.year = year;
this.average_ratings = average_ratings;
this.area=area;
this.cuisine=cuisine;
this.address=address;
//this.genre = genre;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getThumbnailUrl() {
return thumbnailUrl;
}
public void setThumbnailUrl(String thumbnailUrl) {
this.thumbnailUrl = thumbnailUrl;
}
/*public int getYear() {
return year;
}*/
/*public void setYear(int year) {
this.year = year;
}*/
public String getAverage_ratings() {
return average_ratings;
}
public void setAverage_ratings(String average_ratings) {
this.average_ratings = average_ratings;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCuisine() {
return cuisine;
}
public void setCuisine(String cuisine) {
this.cuisine = cuisine;
}
/*public ArrayList<String> getGenre() {
return genre;
}
public void setGenre(ArrayList<String> genre) {
this.genre = genre;
}
*/
}
util -> LruBitmapCache
import com.android.volley.toolbox.ImageLoader.ImageCache;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
public class LruBitmapCache extends LruCache<String, Bitmap> implements ImageCache {
public static int getDefaultLruCacheSize() {
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = maxMemory / 8;
return cacheSize;
}
public LruBitmapCache() {
this(getDefaultLruCacheSize());
}
public LruBitmapCache(int sizeInKiloBytes) {
super(sizeInKiloBytes);
}
#Override
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes() * value.getHeight() / 1024;
}
#Override
public Bitmap getBitmap(String url) {
return get(url);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
put(url, bitmap);
}
}
logcat ->
/com.comida E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.comida, PID: 7059
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.comida/com.comida.ListViewActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'com.android.volley.toolbox.ImageLoader com.comida.app.AppController.getImageLoader()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.android.volley.toolbox.ImageLoader com.comida.app.AppController.getImageLoader()' on a null object reference
at com.comida.adater.CustomListAdapter.<init>(CustomListAdapter.java:22)
at com.comida.ListViewActivity.onCreate(ListViewActivity.java:44)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
07-21 17:09:01.800 2971-3347/system_process W/ActivityManager: Force finishing activity com.comida/.ListViewActivity
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.comida"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="24" />
<!-- To access internet -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- To access accounts configured on device -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<!-- To use account credentials -->
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:name="android.support.multidex.MultiDexApplication"
android:theme="#style/AppTheme">
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="#string/facebook_app_id"/>
<activity android:name="com.facebook.FacebookActivity"
android:configChanges=
"keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:theme="#android:style/Theme.Translucent.NoTitleBar"
android:label="#string/app_name" />
<activity
android:name="com.comida.MainActivity"
android:label="#string/app_name" >
</activity>
<activity
android:name=".ListViewActivity"
>
</activity>
<!--<activity
android:name=".LogoutActivity"
android:label="#string/title_activity_logout" >
</activity>-->
<activity
android:name="SplashActivity"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
</application>
</manifest>
Update your Manifest File.
Change tag android:name="Your.Pakage.Name.AppController"
"path.to.this.class.AppController"
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:name="Your.Pakage.Name.AppController"
android:theme="#style/AppTheme">
Update:
Now you are setting actionbar properties and getting issue.
To fix change Activity to AppCompatActivity
ListViewActivity extend AppCompatActivity

Sinch Service does not seem to start with Android Studio and Parse.com (Android Messaging Tutorial)

I am following this tutorial: https://www.sinch.com/tutorials/android-messaging-tutorial-using-sinch-and-parse
Github for tutorial: https://github.com/sinch/android-messaging-tutorial
The issue I have is that the service does not seem to start at all. I have gone over the code and cannot spot anything that looks wrong (but then again i'm a beginner lol).
I am not receiving any broadcast back in the MenuFragment3 class and due to that the progressDialog just keeps spinning. I have also checked to see if a service is running on both a number of emulators and a real device, like I said it seems as though the service never starts and I really cannot see why.
If you need anything more let me know and thanks for any help!
Firstly I start the service when a user logs in here:
serviceIntent = new Intent(getApplicationContext(), MessageService.class);
startService(serviceIntent);
Heres the manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.yupo.dominic.yupo" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".UserAuth"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Login"
android:label="#string/title_login_area">
</activity>
<activity
android:name=".StudentLogged"
android:label="#string/title_student_area">
</activity>
<activity
android:name=".Register"
android:label="#string/register">
</activity>
<activity
android:name=".LectureLogged"
android:label="#string/title_lecture_area">
</activity>
<service android:name=".MessageService">
</service>
</application>
</manifest>
Heres the MessageService class:
package com.yupo.dominic.yupo;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager;
import com.parse.Parse;
import com.parse.ParseUser;
import com.sinch.android.rtc.ClientRegistration;
import com.sinch.android.rtc.Sinch;
import com.sinch.android.rtc.SinchClient;
import com.sinch.android.rtc.SinchClientListener;
import com.sinch.android.rtc.SinchError;
import com.sinch.android.rtc.messaging.MessageClient;
import com.sinch.android.rtc.messaging.MessageClientListener;
import com.sinch.android.rtc.messaging.WritableMessage;
public class MessageService extends Service implements SinchClientListener {
private static final String APP_KEY = "mykeyiscorrect";
private static final String APP_SECRET = "mysecretiscorrect";
private static final String ENVIRONMENT = "sandbox.sinch.com";
private final MessageServiceInterface serviceInterface = new MessageServiceInterface();
private SinchClient sinchClient = null;
private MessageClient messageClient = null;
private String currentUserId;
private LocalBroadcastManager broadcaster;
private Intent broadcastIntent = new Intent("com.yupo.dominic.yupo.StudentLogged");
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Parse.initialize(this, "thisiscorrect", "thisiscorrect");
currentUserId = ParseUser.getCurrentUser().getObjectId();
if (currentUserId != null && !isSinchClientStarted()) {
startSinchClient(currentUserId);
}
broadcaster = LocalBroadcastManager.getInstance(this);
return super.onStartCommand(intent, flags, startId);
}
public void startSinchClient(String username) {
sinchClient = Sinch.getSinchClientBuilder().context(this).userId(username).applicationKey(APP_KEY)
.applicationSecret(APP_SECRET).environmentHost(ENVIRONMENT).build();
sinchClient.addSinchClientListener(this);
sinchClient.setSupportMessaging(true);
sinchClient.setSupportActiveConnectionInBackground(true);
sinchClient.checkManifest();
sinchClient.start();
}
private boolean isSinchClientStarted() {
return sinchClient != null && sinchClient.isStarted();
}
#Override
public void onClientFailed(SinchClient client, SinchError error) {
broadcastIntent.putExtra("success", false);
broadcaster.sendBroadcast(broadcastIntent);
sinchClient = null;
}
#Override
public void onClientStarted(SinchClient client) {
broadcastIntent.putExtra("success", true);
broadcaster.sendBroadcast(broadcastIntent);
client.startListeningOnActiveConnection();
messageClient = client.getMessageClient();
}
#Override
public void onClientStopped(SinchClient client) {
sinchClient = null;
}
#Override
public IBinder onBind(Intent intent) {
return serviceInterface;
}
#Override
public void onLogMessage(int level, String area, String message) {
}
#Override
public void onRegistrationCredentialsRequired(SinchClient client, ClientRegistration clientRegistration) {
}
public void sendMessage(String recipientUserId, String textBody) {
if (messageClient != null) {
WritableMessage message = new WritableMessage(recipientUserId, textBody);
messageClient.send(message);
}
}
public void addMessageClientListener(MessageClientListener listener) {
if (messageClient != null) {
messageClient.addMessageClientListener(listener);
}
}
public void removeMessageClientListener(MessageClientListener listener) {
if (messageClient != null) {
messageClient.removeMessageClientListener(listener);
}
}
#Override
public void onDestroy() {
sinchClient.stopListeningOnActiveConnection();
sinchClient.terminate();
}
public class MessageServiceInterface extends Binder {
public void sendMessage(String recipientUserId, String textBody) {
MessageService.this.sendMessage(recipientUserId, textBody);
}
public void addMessageClientListener(MessageClientListener listener) {
MessageService.this.addMessageClientListener(listener);
}
public void removeMessageClientListener(MessageClientListener listener) {
MessageService.this.removeMessageClientListener(listener);
}
public boolean isSinchClientStarted() {
return MessageService.this.isSinchClientStarted();
}
}
}
Here my version of the ListUsersActivity from the tutorial (For me it is called MenuFragment3 which is part of a sliding menu which is called from the StudentLogged or LectureLogged activities)
package com.yupo.dominic.yupo;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.parse.FindCallback;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import java.util.ArrayList;
import java.util.List;
public class MenuFragment3 extends Fragment{
View rootview;
ArrayList<String> names;
ParseUser currentUser;
String currentUserId;
ListView usersListView;
ArrayAdapter<String> namesArrayAdapter;
ProgressDialog progressDialog;
BroadcastReceiver receiver;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
currentUser = ParseUser.getCurrentUser();
if(currentUser.getString("type").equalsIgnoreCase("Lecturer"))
{
rootview = inflater.inflate(R.layout.menu3_2_layout, container, false);
}
else
{
rootview = inflater.inflate(R.layout.menu3_layout, container, false);
}
progressDialog = new ProgressDialog(getActivity());
progressDialog.setTitle("Loading");
progressDialog.setMessage("Please wait...");
progressDialog.show();
receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(getActivity(), "broadcast received", Toast.LENGTH_SHORT).show();
Boolean success = intent.getBooleanExtra("success", false);
progressDialog.dismiss();
//show a toast message if the Sinch
//service failed to start
if (!success) {
Toast.makeText(getActivity(), "Messaging service failed to start", Toast.LENGTH_LONG).show();
}
}
};
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(receiver, new IntentFilter("com.yupo.dominic.yupo.StudentLogged"));
currentUserId = ParseUser.getCurrentUser().getObjectId();
names = new ArrayList<String>();
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereNotEqualTo("objectId", currentUserId);
query.findInBackground(new FindCallback<ParseUser>() {
public void done(List<ParseUser> userList, com.parse.ParseException e) {
if (e == null) {
for (int i=0; i<userList.size(); i++) {
names.add(userList.get(i).getUsername().toString());
}
usersListView = (ListView)rootview.findViewById(R.id.usersListView);
namesArrayAdapter =
new ArrayAdapter<String>(getActivity(),
R.layout.user_list_item, names);
usersListView.setAdapter(namesArrayAdapter);
usersListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int i, long l) {
openConversation(names, i);
}
});
} else {
Toast.makeText(getActivity(),
"Error loading user list",
Toast.LENGTH_LONG).show();
}
}
});
return rootview;
}
public void openConversation(ArrayList<String> names, int pos) {
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereEqualTo("username", names.get(pos));
query.findInBackground(new FindCallback<ParseUser>() {
public void done(List<ParseUser> user, com.parse.ParseException e) {
if (e == null) {
//Intent intent = new Intent(getActivity(), MessagingActivity.class);
//intent.putExtra("RECIPIENT_ID", user.get(0).getObjectId());
//startActivity(intent);
Toast.makeText(getActivity(),
"working",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(),
"Error finding that user",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
You're trying to initialize Parse using your Sinch key and secret. In addition, you should initialize Parse in your application's onCreate method. Try:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
currentUserId = ParseUser.getCurrentUser().getObjectId();
if (currentUserId != null && !isSinchClientStarted()) {
startSinchClient(currentUserId);
}
broadcaster = LocalBroadcastManager.getInstance(this);
return super.onStartCommand(intent, flags, startId);
}

libGDX & Google Play Game Services "java.lang.RuntimeException: Unable to instantiate activity ComponentInfo"

Ok, so I'm trying to implement Google Play Games Services into my libGDX game. I followed the tutorial here: http://helios.hud.ac.uk/u1070589/blog/?p=202
When i run my game on my nexus, it force closes and logcat gives this Fatal Exception:
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.ggtized.bb/com.ggtized.bb.MainActivity}: java.lang.ClassNotFoundException: Didn't find class "com.ggtized.bb.MainActivity" on path: DexPathList...
Without the implementation, my game works fine. But the tutorial seems to have been a success for many and i want GPGS too..
What is causing this error. I have no idea.. Can someone help and might tell me whats the problem? Thank you for your replies!!
Here's my androidmanifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ggtized.bb"
android:versionCode="0"
android:versionName="1">
<uses-sdk
android:minSdkVersion="9"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<meta-data
android:name="com.google.android.gms.games.APP_ID"
android:value="#string/app_id" />
<activity
android:name="com.ggtized.bb.MainActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
android:label="#string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.google.android.gms.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" />
</application>
</manifest>
Here's my main Android activity:
package com.ggtized.bb;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
//import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.games.leaderboard.Leaderboard;
import com.google.android.gms.games.leaderboard.LeaderboardScoreBuffer;
import com.google.android.gms.games.leaderboard.OnLeaderboardScoresLoadedListener;
import com.google.example.games.basegameutils.GameHelper;
import com.google.example.games.basegameutils.GameHelper.GameHelperListener;
import com.ggtized.bb.GoogleInterface;
import com.ggtized.bb.BGame;
public class MainActivity extends AndroidApplication implements
GameHelperListener, GoogleInterface {
// ****AdMob
private AdView adView; // small ad
// First Ad Code
private static final String ADCODE = "ca-app-pub-6026787001894298/9413212162";
// First time an Ad is loaded
boolean firstTime = true;
// *************GPGS
private GameHelper aHelper;
private OnLeaderboardScoresLoadedListener theLeaderboardListener;
public MainActivity() {
aHelper = new GameHelper(this);
aHelper.enableDebugLog(true, "MYTAG");
// create a listener for getting raw data back from leaderboard
theLeaderboardListener = new OnLeaderboardScoresLoadedListener() {
public void onLeaderboardScoresLoaded(int arg0, Leaderboard arg1,
LeaderboardScoreBuffer arg2) {
System.out.println("In call back");
for (int i = 0; i < arg2.getCount(); i++) {
System.out.println(arg2.get(i).getScoreHolderDisplayName()
+ " : " + arg2.get(i).getDisplayScore());
}
}
};
}
// *************GPGS end
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ****AdMob
AndroidApplicationConfiguration cfg = new AndroidApplicationConfiguration();
cfg.useGL20 = false;
// *************GPGS
aHelper.setup(this);
// *************GPGS end
// initialize(new Game(), cfg);
this.getWindow().addFlags(
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
final RelativeLayout layout = new RelativeLayout(this);
requestWindowFeature(Window.FEATURE_NO_TITLE); // no title is needed
// Do the stuff that initialize() would do for you
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(
WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
// here we need to create the proper AdViews: one for the banner, and
// one for the full screen one
adView = new AdView(this);
adView.setAdSize(AdSize.SMART_BANNER);
adView.setAdUnitId(ADCODE); // Put in your secret key here
// Here we create the instance of the MyApp and we pass it the
// RequestHandler which implements the IReqHandler interface
View gameView = initializeForView(new BGame(null, this), cfg);
// Optionally populate the ad request builder.
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR) // Emulator
.addTestDevice("775A90563E174E374BC2617A3FD652B1") // testdevice
.build();
adView.loadAd(adRequest);
// Add the libgdx view
layout.addView(gameView);
// Add the AdMob view
final RelativeLayout.LayoutParams adParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
adParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
adParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
/*
* // Setting the ad listener to check if the ad is loaded before adding
* // view, solves the problem of skipping the first draw
* adView.setAdListener(new AdListener() {
*
* #Override public void onAdLoaded() {
*
* if (firstTime) { firstTime = false; layout.addView(adView, adParams);
* } } });
*/
layout.addView(adView, adParams);
// Setting the background adview to transparant also solves the problem
// of skipping the ad draw
adView.setBackgroundColor(Color.TRANSPARENT);
// Hook it all up
setContentView(layout);
// **************AdMob end
}
#Override
public void onResume() {
super.onResume();
if (adView != null) {
adView.resume();
}
}
#Override
public void onPause() {
// Pause the AdView.
if (adView != null) {
adView.pause();
}
super.onPause();
}
/** Called before the activity is destroyed. */
#Override
public void onDestroy() {
// Destroy the AdView.
if (adView != null) {
adView.destroy();
}
super.onDestroy();
}
// ****************GPGS
#Override
public void onStart(){
super.onStart();
aHelper.onStart(this);
}
#Override
public void onStop(){
super.onStop();
aHelper.onStop();
}
#Override
public void onActivityResult(int request, int response, Intent data) {
super.onActivityResult(request, response, data);
aHelper.onActivityResult(request, response, data);
}
public void onSignInFailed() {
System.out.println("sign in failed");
}
public void onSignInSucceeded() {
System.out.println("sign in succeeded");
}
public void Login() {
try {
runOnUiThread(new Runnable(){
//#Override
public void run(){
aHelper.beginUserInitiatedSignIn();
}
});
}catch (final Exception ex){
}
}
public void LogOut() {
try {
runOnUiThread(new Runnable(){
//#Override
public void run(){
aHelper.signOut();
}
});
}catch (final Exception ex){
}
}
public boolean getSignedIn() {
return aHelper.isSignedIn();
}
public void submitScore(int _score) {
System.out.println("in submit score");
aHelper.getGamesClient().submitScore(getString(R.string.leaderBoardID), _score);
}
public void getScores() {
startActivityForResult(aHelper.getGamesClient().getLeaderboardIntent(getString(R.string.leaderBoardID)), 105);
}
public void getScoresData() {
aHelper.getGamesClient().loadPlayerCenteredScores(theLeaderboardListener,
getString(R.string.leaderBoardID),
1,
1,
25) ;
}
// *************GPGS end
}
And here's my Main Game Class
package com.ggtized.bb;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Game;
import com.ggtized.Screens.SplashScreen;
import com.ggtized.BHelpers.AssetLoader;
import com.ggtized.BHelpers.IReqHandler;
public class BGame extends Game implements ApplicationListener {
// Code for Ads
public static IReqHandler ExternalHandler;
// *****GPGS
private GoogleInterface platformInterface;
public BGame(IReqHandler irh, GoogleInterface aInterface) {
BGame.ExternalHandler = irh;
platformInterface = aInterface;
platformInterface.Login();
}
#Override
public void create() {
AssetLoader.load();
setScreen(new SplashScreen(this));
}
#Override
public void dispose() {
super.dispose();
AssetLoader.dispose();
}
}
I finally managed to find a way to solve the issue. In your BaseGameUtils Build Path--->Librairies, you normally have a android-support-v4.jar (or a similar .jar). Delete it from the Build Path (you already have it in the Build Path of your main app, seems to be conflicting in this case).

Categories

Resources