Fatal exception at main android during dropbox authentication [duplicate] - java

This question already exists:
Dropbox Core API is not working. I don't want to hardcode app key and secret?
Closed 7 years ago.
I am getting fatal exception error at main nullpointer exception. basically i have 2 activities login and main activity.you will enter app key and app secret in login activity then after authentication it will take you to main activity any help ??
login activity
public class login_activity extends AppCompatActivity {
public String APP_kEY ;
public String APP_SECRET;
public String accessToken;
EditText app_key_view;
EditText App_secret_view;
Button dropbox;
public DropboxAPI<AndroidAuthSession> mDBApi;
#Override
protected void onCreate(Bundle savedInstanceState) {
SharedPreferences pref = getSharedPreferences("login",MODE_PRIVATE);
APP_kEY = pref.getString("appkey",null);
APP_SECRET = pref.getString("appsecret",null);
accessToken = pref.getString("access",null);
if (accessToken != null){
AppKeyPair appkeys = new AppKeyPair(APP_kEY,APP_SECRET);
AndroidAuthSession session = new AndroidAuthSession(appkeys);
session.setOAuth2AccessToken(accessToken);
Intent i = new Intent(login_activity.this,MainActivity.class);
startActivity(i);
finish();
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_activity);
app_key_view=(EditText)findViewById(R.id.app_key_text);
App_secret_view=(EditText)findViewById(R.id.app_secret_text);
dropbox = (Button)findViewById(R.id.link_dropbox);
//////////////////////////////////////////////////////////////
dropbox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
APP_kEY = app_key_view.getText().toString();
APP_SECRET = App_secret_view.getText().toString();
AppKeyPair appKeys = new AppKeyPair(APP_kEY,APP_SECRET);
AndroidAuthSession session = new AndroidAuthSession(appKeys);
mDBApi = new DropboxAPI<>(session);
mDBApi.getSession().startOAuth2Authentication(login_activity.this);
}
});
}
#Override
protected void onResume () {
super.onResume();
if(mDBApi.getSession().authenticationSuccessful()){
try {
mDBApi.getSession().finishAuthentication();
accessToken = mDBApi.getSession().getOAuth2AccessToken();
SharedPreferences.Editor editor = getSharedPreferences("login",MODE_PRIVATE).edit();
editor.putString("appkey",APP_kEY);
editor.putString("appsecret",APP_SECRET);
editor.putString("access",accessToken);
editor.commit();
Intent i = new Intent(login_activity.this,MainActivity.class);
startActivity(i);
finish();
}
catch (IllegalStateException e){
Log.i("DbAuthLog", "Error authenticationg", e);
}
}
}
Logcat
09-11 21:06:01.947 3842-3842/? I/art﹕ Late-enabling -Xcheck:jni
09-11 21:06:01.975 3842-3851/? I/art﹕ Debugger is no longer active
09-11 21:06:02.370 3842-3857/? I/art﹕ Background sticky concurrent mark sweep GC freed 2909(253KB) AllocSpace objects, 2(32KB) LOS objects, 0% free, 50MB/50MB, paused 36.891ms total 133.660ms
09-11 21:06:02.803 3842-3842/? D/AndroidRuntime﹕ Shutting down VM
09-11 21:06:02.803 3842-3842/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.ayzaz.timescopev1.timescope, PID: 3842
java.lang.RuntimeException: Unable to resume activity {com.example.ayzaz.timescopev1.timescope/com.example.ayzaz.timescopev1.timescope.login_activity}: java.lang.NullPointerException: Attempt to invoke virtual method 'com.dropbox.client2.session.Session com.dropbox.client2.DropboxAPI.getSession()' on a null object reference
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2986)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3017)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2392)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.dropbox.client2.session.Session com.dropbox.client2.DropboxAPI.getSession()' on a null object reference
at com.example.ayzaz.timescopev1.timescope.login_activity.onResume(login_activity.java:77)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1257)
at android.app.Activity.performResume(Activity.java:6076)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2975)
            at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3017)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2392)
            at android.app.ActivityThread.access$800(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
09-11 21:06:05.849 3842-3842/com.example.ayzaz.timescopev1.timescope I/Process﹕ Sending signal. PID: 3842 SIG: 9

onResume() always gets called after onCreate().
When onResume() begins, mDBApi is null, because this field is only ever assigned in the onClick() method.
You either need to assign mDBApi in onCreate() directly, or you need to check that it is not null before you try to use it.

Related

Android java.lang.NullPointerException error with BroadcastReceiver

Everytime the application gets to my second activity it crashes, giving the error.
My activity:
public class SecondActivity extends AppCompatActivity {
EditText barcodeText = findViewById(R.id.barcodeText);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
IntentFilter filter = new IntentFilter();
filter.addCategory(Intent.CATEGORY_DEFAULT);
filter.addAction(getResources().getString(R.string.activity_intent_filter_action));
registerReceiver(myBroadcastReceiver, filter);
}
private BroadcastReceiver myBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Bundle b = intent.getExtras();
if (action.equals(getResources().getString(R.string.activity_intent_filter_action))) {
try {
displayScanResult(intent);
} catch (Exception e) {
}
}
}
};
private void displayScanResult(Intent initiatingIntent)
{
String decodedSource = initiatingIntent.getStringExtra(getResources().getString(R.string.datawedge_intent_key_source));
String decodedData = initiatingIntent.getStringExtra(getResources().getString(R.string.datawedge_intent_key_data));
String decodedLabelType = initiatingIntent.getStringExtra(getResources().getString(R.string.datawedge_intent_key_label_type));
barcodeText.setText(decodedData);
}
}
Logcat:
07-01 12:37:03.373 349-349/com.example.provatimer E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.provatimer, PID: 349
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.provatimer/com.example.provatimer.SecondActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2236)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5256)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:149)
at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:99)
at android.content.Context.obtainStyledAttributes(Context.java:438)
at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:692)
at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:659)
at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:479)
at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:214)
at com.example.provatimer.SecondActivity.<init>(SecondActivity.java:14)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1606)
at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
at android.app.ActivityThread.access$800(ActivityThread.java:151) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5256) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699) 
I think it may have something to do with the context in the BroadcastReceiver, but I tried to declare it in the onCreate method but nothing changed.
Maybe I don't initialize correctly the intent in which the data should be stored, if so, how can I do it correctly?
All the Strings should be correct int the string.xml file, if the error may come from that I'll write them.
I think the error is happening here:
EditText barcodeText = findViewById(R.id.barcodeText);
You are invoking findViewById() directly in the class member declaration.
You have invoke findViewById() after setContentView()
EditText barcodeText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
barcodeText = findViewById(R.id.barcodeText);
}

NullPoint error when trying to call a function of another class [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I am trying to call a function registerGCM(); from my reg.java class into the MainActivity.java class.
When I use the function from inside the reg.java activity the app works just fine but whenever I call it from inside the MainActivity I get this error
07-28 13:38:38.540 24434-24434/com.example.kmi_dev.fbloginsample E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.kmi_dev.fbloginsample, PID: 24434
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.kmi_dev.fbloginsample/com.example.kmi_dev.fbloginsample.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.kmi_dev.fbloginsample.reg.registerGCM()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.kmi_dev.fbloginsample.reg.registerGCM()' on a null object reference
at com.example.kmi_dev.fbloginsample.MainActivity.onCreate(MainActivity.java:158)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
            at android.app.ActivityThread.access$800(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Content of the MainActivity where call is being made
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
private static final String MYPREFERENCES = "myPref";
private CallbackManager callbackManager;
private LoginButton fbLoginButton;
private Button login;
.
.
.
.
GPSTracker gps;
reg GCM_REG;
// flag for Internet connection status
Boolean isInternetPresent = false;
// Connection detector class
ConnectionDetector cd;
SessionManager session;
.
.
String gcmId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//get global variable class
final GlobalClass globalVariable = (GlobalClass) getApplicationContext();
gcmId = GCM_REG.registerGCM();
Content of registerGCM()
public String registerGCM() {
gcm = GoogleCloudMessaging.getInstance(this);
regId = getRegistrationId(context);
if (TextUtils.isEmpty(regId)) {
registerInBackground();
Log.d("MainActivity",
"registerGCM - successfully registered with GCM server - regId: "
+ regId);
} else {
Toast.makeText(getApplicationContext(),
"RegId already available. RegId: " + regId,
Toast.LENGTH_LONG).show();
}
final GlobalClass globalVariable = (GlobalClass) getApplicationContext();
globalVariable.setGcmRegId(regId);
return regId;
}
public String getRegistrationId(Context context) {
final SharedPreferences prefs = getSharedPreferences(reg.class.getSimpleName(), Context.MODE_PRIVATE);
String registrationId = prefs.getString(REG_ID, "");
if (registrationId.isEmpty()) {
Log.i(TAG, "Registration not found.");
return "";
}
int registeredVersion = prefs.getInt(APP_VERSION, Integer.MIN_VALUE);
int currentVersion = getAppVersion(context);
if (registeredVersion != currentVersion) {
Log.i(TAG, "App version changed.");
return "";
}
return registrationId;
}
Any Idea why I am unable to call this function???
You never initialize GCM_REG. That's why you get a NullPointerException.

NullPointerException when I try to capture an image (built-in camera) and save it to a file [duplicate]

This question already has answers here:
Android Camera : data intent returns null
(11 answers)
Closed 8 years ago.
Here's what the app does - User clicks button (to take a picture) on Activity A, the captured image gets set as on an ImageView in Activity A, and then the user clicks a "save" button, which takes him/her to Activity B, where the image they took gets displayed (on an ImageView in Activity B)
In order to do this I am trying to find a way to save the image. I tried many different things, but I keep getting a NullPointerException. Here is my code:
I highlighted the area where I think the error is:
public void onClick(View view) {
switch (view.getId()) {
case R.id.take_picture_button:
takePic = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
if (takePic.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile(); //so photoFile = the file we created up top
} catch (IOException ex) {
// Error occurred while creating the File
ex.printStackTrace();
}
// Continue only if the File was successfully created
if (photoFile != null) {
**takePic.putExtra(MediaStore.EXTRA_OUTPUT**, //extra_output is just the name of the Intent-extra used to indicate a content resolver Uri to be used to store the requested image or video.
**Uri.fromFile(photoFile));**
startActivityForResult(takePic, cameraData);
}
And here is the code for the onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == cameraData && resultCode == RESULT_OK) {
mReturningWithResult = true;
extras = data.getExtras();
And here is where I set my image view to my captured image (on Activity A)
#Override
protected void onPostResume() {
super.onPostResume();
if (mReturningWithResult) {
foodImage = (Bitmap) extras.get("data");
foodImageView.setImageBitmap(foodImage);
}
mReturningWithResult = false;//resetting it for next time
}
Here is the logcat (sorry I'm new to this)
10-15 20:58:59.612 32005-32005/com.example.nikhil.foodshark D/OpenGLRenderer﹕ Enabling debug mode 0
10-15 20:59:21.545 32005-32005/com.example.nikhil.foodshark I/PersonaManager﹕ getPersonaService() name persona_policy
10-15 20:59:23.127 32005-32005/com.example.nikhil.foodshark W/IInputConnectionWrapper﹕ showStatusIcon on inactive InputConnection
10-15 20:59:33.678 32005-32005/com.example.nikhil.foodshark D/AndroidRuntime﹕ Shutting down VM
10-15 20:59:33.678 32005-32005/com.example.nikhil.foodshark W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41a39da0)
10-15 20:59:33.678 32005-32005/com.example.nikhil.foodshark E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.nikhil.foodshark, PID: 32005
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=null} to activity {com.example.nikhil.foodshark/com.example.nikhil.foodshark.NewDish}: java.lang.NullPointerException
at android.app.ActivityThread.deliverResults(ActivityThread.java:3680)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3723)
at android.app.ActivityThread.access$1400(ActivityThread.java:174)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1355)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5593)
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:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.nikhil.foodshark.NewDish.onActivityResult(NewDish.java:144)
at android.app.Activity.dispatchActivityResult(Activity.java:5650)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3676)
            at android.app.ActivityThread.handleSendResult(ActivityThread.java:3723)
            at android.app.ActivityThread.access$1400(ActivityThread.java:174)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1355)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:146)
            at android.app.ActivityThread.main(ActivityThread.java:5593)
            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:1283)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
            at dalvik.system.NativeStart.main(Native Method)
10-15 20:59:56.353 32005-32005/com.example.nikhil.foodshark I/Process﹕ Sending signal. PID: 32005 SIG: 9
10-15 20:59:56.613 378-378/com.example.nikhil.foodshark I/PersonaManager﹕ getPersonaService() name persona_policy
10-15 20:59:56.723 378-378/com.example.nikhil.foodshark I/Adreno-EGL﹕ <qeglDrvAPI_eglInitialize:381>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_KK_2.7_RB1.04.04.02.007.050_msm8960_refs/tags/AU_LINUX_ANDROID_KK_2.7_RB1.04.04.02.007.050__release_AU ()
OpenGL ES Shader Compiler Version: 17.01.12.SPL
Build Date: 03/28/14 Fri
Local Branch:
Remote Branch: refs/tags/AU_LINUX_ANDROID_KK_2.7_RB1.04.04.02.007.050
Local Patches: NONE
Reconstruct Branch: NOTHING
10-15 20:59:56.763 378-378/com.example.nikhil.foodshark D/OpenGLRenderer﹕ Enabling debug mode 0
Do you guys know a way I can fix this? Thank you!
You are passing MediaStore.EXTRA_OUTPUT, in which case, the intent field in onActivityResult can be null.
The solution is to just use the photo file you created, and passed as uri in the putExtra
So instead of trying to get the photo file location from the intent, just use Uri.fromFile(photoFile)
replace
extras = data.getExtras();
...
with
`Uri.fromFile(photoFile)`
or just use photoFile if that is what you want...just dont rely on intent data

New error java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

I have a problem with sample code from google maps !
This code worked when i used eclipse. I changed for android studio and i have a wird error.
Error is : ( i have no onSaveInstanceState method)
Caused by: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1360)
at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1378)
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:595)
at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:574)
at android.support.v4.app.DialogFragment.show(DialogFragment.java:138)
at com.example.smartoo.HomeActivity.servicesConnected(HomeActivity.java:325)
at com.example.smartoo.HomeActivity.stopUpdates(HomeActivity.java:373)
at com.example.smartoo.HomeActivity.onStop(HomeActivity.java:209)
at android.app.Instrumentation.callActivityOnStop(Instrumentation.java:1212)
at android.app.Activity.performStop(Activity.java:5376)
at android.app.ActivityThread.performStopActivityInner(ActivityThread.java:3185)
            at android.app.ActivityThread.handleStopActivity(ActivityThread.java:3234)
            at android.app.ActivityThread.access$1100(ActivityThread.java:135)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1223)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            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:779)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
            at dalvik.system.NativeStart.main(Native Method)
Error is on this line :
errorFragment.show(getSupportFragmentManager(), LocationUtils.APPTAG);
The code :
/**
* Verify that Google Play services is available before making a request.
*
* #return true if Google Play services is available, otherwise false
*/
private boolean servicesConnected() {
// Check that Google Play services is available
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
// If Google Play services is available
if (ConnectionResult.SUCCESS == resultCode) {
// In debug mode, log the status
Log.d(LocationUtils.APPTAG, getString(R.string.play_services_available));
// Continue
return true;
// Google Play services was not available for some reason
} else {
// Display an error dialog
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(resultCode, this, 0);
if (dialog != null) {
ErrorDialogFragment errorFragment = new ErrorDialogFragment();
errorFragment.setDialog(dialog);
errorFragment.show(getSupportFragmentManager(), LocationUtils.APPTAG);
}
return false;
}
}
Thx !
Normally, the above code is called inside onStart/OnResume method or after these methods, not inside onStop/onSaveInstance. You are trying to do some operation after activity is getting killed. Perform serivcesConnected call before onStop/finish/saveInstances method call.

Android: Google play games services connection error ( java.lang.IllegalStateException: GoogleApiClient must be connected.)

I've programmed a game for android, everything works fine, but now I want my app to have Google play Games services (leaderboards and achievements). I used the Google example code to log in to the Google services (no errors in the script), but every time I want to connect with my App in debug mode, I get this error:
6-29 11:48:29.391 23779-23779/com.JFKGames.theepicbutton E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.JFKGames.theepicbutton, PID: 23779
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=9001, result=10004, data=null} to activity {com.JFKGames.theepicbutton/com.JFKGames.theepicbutton.MainActivity}: java.lang.IllegalStateException: GoogleApiClient must be connected.
at android.app.ActivityThread.deliverResults(ActivityThread.java:3446)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3489)
at android.app.ActivityThread.access$1300(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1258)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5102)
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:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalStateException: GoogleApiClient must be connected.
at com.google.android.gms.internal.fq.a(Unknown Source)
at com.google.android.gms.games.Games.c(Unknown Source)
at com.google.android.gms.games.internal.api.LeaderboardsImpl.submitScore(Unknown Source)
at com.google.android.gms.games.internal.api.LeaderboardsImpl.submitScore(Unknown Source)
at com.JFKGames.theepicbutton.MainActivity.onActivityResult(MainActivity.java:79)
at android.app.Activity.dispatchActivityResult(Activity.java:5446)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3442)
            at android.app.ActivityThread.handleSendResult(ActivityThread.java:3489)
            at android.app.ActivityThread.access$1300(ActivityThread.java:139)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1258)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5102)
            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:785)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
            at dalvik.system.NativeStart.main(Native Method)
And the App crashes. Here's my code for the MainActivity where I want it to connect:
public class MainActivity extends BaseGameActivity implements
GameHelper.GameHelperListener, View.OnClickListener {
public static int REQUEST_LEADERBOARD = 1002;
boolean mExplicitSignOut = false;
boolean mInSignInFlow = false;
GoogleApiClient mClient() {
return null;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
setRequestedClients(BaseGameActivity.CLIENT_GAMES | BaseGameActivity.CLIENT_APPSTATE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button)findViewById(R.id.startbutton);
button.setOnClickListener (this);
Button highscorebutton = (Button)findViewById(R.id.highscorebutton);
highscorebutton.setOnClickListener(this);
findViewById(R.id.sign_in_button).setOnClickListener(this);
findViewById(R.id.sign_out_button).setOnClickListener(this);
}
public void onClick(View view) {
if(view.getId()==R.id.startbutton) {
startActivityForResult(new Intent(this, buttonActivity.class), 1);
} else if(view.getId()==R.id.highscorebutton) {
startActivityForResult(Games.Leaderboards.getLeaderboardIntent(getApiClient(), getString(R.string.the_best_players)),REQUEST_LEADERBOARD);
} else if (view.getId() == R.id.sign_in_button) {
// start the asynchronous sign in flow
beginUserInitiatedSignIn();
}
else if (view.getId() == R.id.sign_out_button) {
// sign out.
signOut();
// show sign-in button, hide the sign-out button
findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
findViewById(R.id.sign_out_button).setVisibility(View.GONE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Games.Leaderboards.submitScore(getApiClient(), getString(R.string.the_best_players), resultCode);
if(requestCode==1) {
if(resultCode > leseHighscore()) {
schreibeHighscore(resultCode);
}
}
}
#Override
public void onSignInFailed() {
findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
findViewById(R.id.sign_out_button).setVisibility(View.GONE);
}
#Override
public void onSignInSucceeded() {
View a = findViewById(R.id.highscorebutton);
a.setVisibility(View.VISIBLE);
View b = findViewById(R.id.button3);
b.setVisibility(View.VISIBLE);
findViewById(R.id.sign_in_button).setVisibility(View.GONE);
findViewById(R.id.sign_out_button).setVisibility(View.VISIBLE);
}
}
Thanks, GoogleWelt
According to the official documentation, "Before any operation is executed, the GoogleApiClient must be connected"
When the user in not connected(signed in) and clicks to show leaderboards or achievements, it results in the exception thrown. Modify your code for launching the leaderboard like this:
} else if(view.getId()==R.id.highscorebutton) {
if (isSignedIn())
startActivityForResult(Games.Leaderboards.getLeaderboardIntent(getApiClient(), getString(R.string.the_best_players)), REQUEST_LEADERBOARD);
else showAlert("Please sign in to view leaderboards");
}
Use the same logic for showing achievements:
if (isSignedIn())
startActivityForResult(Games.Achievements.getAchievementsIntent(getApiClient()), REQUEST_ACHIEVEMENT);
else showAlert("Please sign in to view achievements");
Check the part where you are getting ApiClient i.e. getApiClient().
Write the code below to see if GoogleApiClient is Connected or not.
GoogleApiClient mGoogleApiClient;
if(mGoogleApiClient.isConnected()){
// good
}else{
//connect it
mGoogleApiClient.connect(GoogleApiClient.SIGN_IN_MODE_OPTIONAL);
}

Categories

Resources