Unable to resume activity - NullPointerException - java

I know this is quite a common question, but I have searched around and my attempts to solve the below issue have been unsuccessful.
In particular, below are the messages that I am receiving from logcat.
08-03 17:55:53.885: E/AndroidRuntime(1286): FATAL EXCEPTION: main
08-03 17:55:53.885: E/AndroidRuntime(1286): Process: com.dooba.beta, PID: 1286
08-03 17:55:53.885: E/AndroidRuntime(1286): java.lang.RuntimeException: Unable to resume activity {com.dooba.beta/com.dooba.beta.MatchingActivity}: java.lang.NullPointerException
08-03 17:55:53.885: E/AndroidRuntime(1286): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2788)
08-03 17:55:53.885: E/AndroidRuntime(1286): at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2817)
08-03 17:55:53.885: E/AndroidRuntime(1286): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2250)
08-03 17:55:53.885: E/AndroidRuntime(1286): at android.app.ActivityThread.access$800(ActivityThread.java:135)
08-03 17:55:53.885: E/AndroidRuntime(1286): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
08-03 17:55:53.885: E/AndroidRuntime(1286): at android.os.Handler.dispatchMessage(Handler.java:102)
08-03 17:55:53.885: E/AndroidRuntime(1286): at android.os.Looper.loop(Looper.java:136)
08-03 17:55:53.885: E/AndroidRuntime(1286): at android.app.ActivityThread.main(ActivityThread.java:5017)
08-03 17:55:53.885: E/AndroidRuntime(1286): at java.lang.reflect.Method.invokeNative(Native Method)
08-03 17:55:53.885: E/AndroidRuntime(1286): at java.lang.reflect.Method.invoke(Method.java:515)
08-03 17:55:53.885: E/AndroidRuntime(1286): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
08-03 17:55:53.885: E/AndroidRuntime(1286): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
08-03 17:55:53.885: E/AndroidRuntime(1286): at dalvik.system.NativeStart.main(Native Method)
08-03 17:55:53.885: E/AndroidRuntime(1286): Caused by: java.lang.NullPointerException
08-03 17:55:53.885: E/AndroidRuntime(1286): at com.dooba.beta.MatchingActivity.onResume(MatchingActivity.java:82)
08-03 17:55:53.885: E/AndroidRuntime(1286): at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1192)
08-03 17:55:53.885: E/AndroidRuntime(1286): at android.app.Activity.performResume(Activity.java:5310)
08-03 17:55:53.885: E/AndroidRuntime(1286): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2778)
08-03 17:55:53.885: E/AndroidRuntime(1286): ... 12 more
Below is the code for the activity
public class MatchingActivity extends Activity {
protected ParseRelation<ParseUser> mFriendsRelation;
protected ParseUser mCurrentUser;
protected List<ParseUser> mUsers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.matching);
// Show the Up button in the action bar.
}
#Override
protected void onResume() {
super.onResume();
mCurrentUser = ParseUser.getCurrentUser();
setProgressBarIndeterminateVisibility(true);
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.findInBackground(new FindCallback<ParseUser>() {
public void done(List<ParseUser> users, ParseException e) {
if (e == null) {
mUsers = users;
} else {
// Something went wrong.
}
}
});
//This give you a list of users. Then to access one user you need to know the index the user is at.
ParseUser user = mUsers.get(5);
//then you can access that user's information
user.getString("name");
user.getNumber("age");
user.getString("headline");
}
}
Below is the code for the xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout>
Any assistance would be greatly appreciated.
Thanks in advance.
Updated code:
Error received
for the line
mUsers = new List<ParseUser>();
I receive the following messages:
"Cannot instantiate the type List<ParseUser>"
for the lines
user.getString("name");
user.getNumber("age");
user.getString("headline");
I receive the following error:
"user cannot be resolved"
Thanks in advance, and below is the complete updated code.
public class MatchingActivity extends Activity {
protected ParseRelation<ParseUser> mFriendsRelation;
protected ParseUser mCurrentUser;
protected List<ParseUser> mUsers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.matching);
// Show the Up button in the action bar.
//create list variable
mUsers = new List<ParseUser>();
}
#Override
protected void onResume() {
super.onResume();
mCurrentUser = ParseUser.getCurrentUser();
setProgressBarIndeterminateVisibility(true);
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.findInBackground(new FindCallback<ParseUser>() {
public void done(List<ParseUser> users, ParseException e) {
if (e == null) {
//add all the users to your list variable
mUsers.addAll(users);
} else {
// Something went wrong.
}
}
});
//check the size of your list to see how big it is before accessing it
final int size = mUsers.size();
//or use a loop to loop through each one
for(ParseUser mParseUser : mUsers) {
//skip over the current user
if(mParseUser == ParseUser.getCurrentUser())
continue;
user.getString("name");
user.getNumber("age");
user.getString("headline");
}
}
}

I think your problem is in the following line of code
ParseUser user = mUsers.get(5);
mUsers.get(5) is probably null, or doesn't exist. There is nothing in your code which guarantees that the list has to be at least size 5.
Try this instead
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.matching);
//create list variable
mUsers = new List<ParseUser>();
}
#Override
protected void onResume() {
...
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.findInBackground(new FindCallback<ParseUser>()
{
public void done(List<ParseUser> users, ParseException e)
{
if (e == null)
{
//add all the users to your list variable
mUsers.addAll(users);
//check the size of your list to see how big it is before accessing it
final int size = mUsers.size();
//or use a loop to loop through each one
for(ParseUser mParseUser : mUsers)
{
//skip over the current user
if(mParseUser == ParseUser.getCurrentUser())
continue;
//use the correct type when getting
final String mName = user.getString("name");
final int mNumber = user.getNumber("age");
final String mHeadLine = user.getString("headline");
}
}
else
{
// Something went wrong.
}
}
});
}

Related

java.lang.RuntimeException: Unable to resume activity : java.lang.NullPointerException

I am facing issue with my code.I am getting RuntimeException.Kindly please do help me with this.
I'm getting the following error log :
06-17 18:11:32.646 13750-13750/? E/Zygote: v2
06-17 18:11:32.646 13750-13750/? E/Zygote: accessInfo : 0
06-17 18:11:33.226 13750-13750/com.example.cocol.timisoara2021 E/MotionRecognitionManager: mSContextService = android.hardware.scontext.ISContextService$Stub$Proxy#f847827
06-17 18:11:33.226 13750-13750/com.example.cocol.timisoara2021 E/MotionRecognitionManager: motionService = com.samsung.android.motion.IMotionRecognitionService$Stub$Proxy#d2d3ad4
06-17 18:11:33.226 13750-13750/com.example.cocol.timisoara2021 E/MotionRecognitionManager: motionService = com.samsung.android.motion.IMotionRecognitionService$Stub$Proxy#d2d3ad4
06-17 18:11:36.566 13750-14348/com.example.cocol.timisoara2021 E/GooglePlayServicesUtil: The Google Play services resources were not found. Check your project configuration to ensure that the resources are included.
06-17 18:11:36.666 13750-13750/com.example.cocol.timisoara2021 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.cocol.timisoara2021, PID: 13750
java.lang.RuntimeException: Unable to resume activity {com.example.cocol.timisoara2021/com.example.cocol.timisoara2021.Main2Activity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.wikitude.common.orientation.internal.a.a()' on a null object reference
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4226)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4328)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3427)
at android.app.ActivityThread.access$1100(ActivityThread.java:229)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7407)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.wikitude.common.orientation.internal.a.a()' on a null object reference
at com.wikitude.architect.ArchitectView.onResume(ProGuard:818)
at com.example.cocol.timisoara2021.Main2Activity.onResume(Main2Activity.java:59)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1287)
at android.app.Activity.performResume(Activity.java:7015)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4215)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4328) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3427) 
at android.app.ActivityThread.access$1100(ActivityThread.java:229) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:7407) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) 
And here is the line 53:architectView.onResume();
And the code:
package com.example.cocol.timisoara2021;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.wikitude.architect.ArchitectStartupConfiguration;
import com.wikitude.architect.ArchitectView;
public class Main2Activity extends AppCompatActivity {
private ArchitectView architectView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
this.architectView = (ArchitectView) this.findViewById(R.id.architectView);
final ArchitectStartupConfiguration config = new ArchitectStartupConfiguration();
config.setLicenseKey("KKvjW60rM1+LoIdIXdMFdqLeXM8rI6uDFqScJycG9rTXI7GHrRdOx9dycHtxv8Ef6Y6jHB/abqr26X6+eqQXyb+ci4ETEEzCQAQFg3h4/+7DhpwYxY3ayzp3jh/+THcSLe2aKZPAvImpV5Ci0Y7yW891E7d+ionYP0iqJJt6mbNTYWx0ZWRfX05DoEhYDMgfmFUvxnY5fbtk7wnaNnJf4Orfhl+Zfp9DmwItjh/lTSX7MTbprDG700m7vZfWqY1j41pA5vYMiBTiiE1vn6qK66jZ8H5nxjsi3Jp3iAynh2VltO95P6CQy5IKBC9HYdWDtvL/lEmWk1lCOhs4xX8kxwsfD1rxqICVD+zP5Uv+4wnug4++E6vFSwUtDgSN+hY38QnTmh6wXKO5aO7PUm20UXC/7k2lvWNwywwX6LMwF4H4ShnIDQDdWSMSuLshIHvR4SWPNN3r+wK5ImnI/fl/yWmkpH66wB5jWSuE6PvIOSIKz+esUzxprAfQxT6bkpenU/jxNwPaYB8ZbhUHCSCN7vWvGO7z12V/B98xWCGzRdZE5VZqNEOyPA/AfvjSJBmenYpvgm4dw0hgyBQrkoc56P6jOEc8W1aSKdfXfmv0olhbapaEzSoKubZXoZ0ZgPPfjQ6eHtzSVkoOB2fHCVONXseHnjsj9+LYNx3w+DLn0PY=");
this.architectView.onCreate(config);
}
protected void OnPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
architectView.onPostCreate();
try {
this.architectView.load("file:///android_asset/POI/index.html");
}catch (Exception e) {
}
}
#Override
protected void onPause() {
super.onPause();
architectView.onPause();
}
#Override
protected void onResume() {
super.onResume();
architectView.onResume();
}
#Override
protected void onDestroy() {
super.onDestroy();
architectView.onDestroy();
}
}
How can I fix this ?
Your onPostCreate method has an uppercase "O". Because of this i assume it is never called which means that the ArchitectView is in an invalid state when you call architectView.onResume.
Try:
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
architectView.onPostCreate();
try {
this.architectView.load("file:///android_asset/POI/index.html");
}catch (Exception e) {
}
}

I initialize a TextView before runtime because the views are not set yet

I write this counter but when I lunch the app get crashed I don't now where the error some help and thank you tell where is the Error here or how can I do code in right way
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
TextView txt = (TextView)findViewById(R.id.textView);
count i;
public void bu1(View view) {
starrtime();
}
public void bu2(View view) {
i.cancel();
}
void starrtime(){
i = new count(100,1000);
i.start();
}
public class count extends CountDownTimer {
public count(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onTick(long millisUntilFinished) {
txt.setText(String.valueOf(millisUntilFinished));
}
#Override
public void onFinish() {
txt.setText("Done");
}
}
}
this my log cat
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.kira.counter, PID: 4598
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.kira.counter/com.example.kira.counter.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2110)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
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.NullPointerException
at android.support.v7.app.AppCompatDelegateImplBase.(AppCompatDelegateImplBase.java:116)
at android.support.v7.app.AppCompatDelegateImplV9.(AppCompatDelegateImplV9.java:147)
at android.support.v7.app.AppCompatDelegateImplV11.(AppCompatDelegateImplV11.java:27)
at android.support.v7.app.AppCompatDelegateImplV14.(AppCompatDelegateImplV14.java:50)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:201)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:181)
at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:521)
at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:190)
at com.example.kira.counter.MainActivity.(MainActivity.java:23)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1208)
at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2101)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233) 
at android.app.ActivityThread.access$800(ActivityThread.java:135) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:136) 
at android.app.ActivityThread.main(ActivityThread.java:5001) 
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) 
I believe you can not initialize a TextView before runtime because the views are not set yet. Classes should be capitalized. Try this.
public class MainActivity extends AppCompatActivity{
private TextView txt;
private Count i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt = (TextView)findViewById(R.id.textView);
}
}

Cannot show Toast nor AlertDialog on AsyncTask's onPostExecute method

I'm struggling with this error since 2 days now and I can't figure out how to fix it.
I have an order method for a product that calls a webservice, I parse the response and if the response is negative I have to show an AlertDialog inside the onPostExecute method. This is the code i'm using:
private class test extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("deviceOS", "Android"));
String jsonStr = sh.makeServiceCall(urlTest, ServiceHandler.POST, params);
if (jsonStr != null) {
try {
JSONObject obj = new JSONObject(jsonStr);
error = obj.getBoolean("Error");
if(!error)
{
test = true;
JSONObject array = obj.getJSONObject("Response");
token = array.getString("Token");
}
else
{
test = false;
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
//checkResult();
AlertDialog.Builder reorder = new AlertDialog.Builder(myActivity.this);
reorder.setMessage("test");
reorder.setCancelable(true);
reorder.setPositiveButton("ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog orderError = reorder.create();
orderError.show();
}
}
When the app reaches the onPostExecute method it crashes and the log is this:
07-13 11:58:31.074: E/AndroidRuntime(2529): FATAL EXCEPTION: main
07-13 11:58:31.074: E/AndroidRuntime(2529): Process: com.test.Test, PID: 2529
07-13 11:58:31.074: E/AndroidRuntime(2529): java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
07-13 11:58:31.074: E/AndroidRuntime(2529): at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:148)
07-13 11:58:31.074: E/AndroidRuntime(2529): at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:99)
07-13 11:58:31.074: E/AndroidRuntime(2529): at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:154)
07-13 11:58:31.074: E/AndroidRuntime(2529): at android.app.AlertDialog$Builder.<init>(AlertDialog.java:379)
07-13 11:58:31.074: E/AndroidRuntime(2529): at test.test$login.onPostExecute(test.java:575)
07-13 11:58:31.074: E/AndroidRuntime(2529): at test.test$test.onPostExecute(test.java:1)
07-13 11:58:31.074: E/AndroidRuntime(2529): at android.os.AsyncTask.finish(AsyncTask.java:632)
07-13 11:58:31.074: E/AndroidRuntime(2529): at android.os.AsyncTask.access$600(AsyncTask.java:177)
07-13 11:58:31.074: E/AndroidRuntime(2529): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
07-13 11:58:31.074: E/AndroidRuntime(2529): at android.os.Handler.dispatchMessage(Handler.java:102)
07-13 11:58:31.074: E/AndroidRuntime(2529): at android.os.Looper.loop(Looper.java:135)
07-13 11:58:31.074: E/AndroidRuntime(2529): at android.app.ActivityThread.main(ActivityThread.java:5312)
07-13 11:58:31.074: E/AndroidRuntime(2529): at java.lang.reflect.Method.invoke(Native Method)
07-13 11:58:31.074: E/AndroidRuntime(2529): at java.lang.reflect.Method.invoke(Method.java:372)
07-13 11:58:31.074: E/AndroidRuntime(2529): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
07-13 11:58:31.074: E/AndroidRuntime(2529): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
Does anyone know what the error could be?
Why are you create 2 times AlertDialog? Using Builder you can show it. Change Below code and Works fine.
Replace
AlertDialog.Builder reorder = new AlertDialog.Builder(myActivity.this);
with
AlertDialog.Builder reorder = new AlertDialog.Builder(myActivity.this).create();
and
Remove
AlertDialog orderError = reorder.create();
orderError.show();
and add
reorder.show();
Thats it...
Make sure you have initialised "urlTest" before you are using it.
Try this.
private class test extends AsyncTask<Void, Void, Void> {
WeakReference<Activity> weakActivity;
public test(Activity activity) {
weakActivity = activity;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
//blah blah code!
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Activity activity = weakActivity.get();
if (activity != null) {
// Dismiss the progress dialog
//checkResult();
AlertDialog.Builder reorder = new AlertDialog.Builder(activity);
reorder.setMessage("test");
reorder.setCancelable(true);
reorder.setPositiveButton("ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog orderError = reorder.create();
orderError.show();
}
}
}

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);
}

IndexOutOfBound Exception throwing Android

i have make one android application in that data is coming from server so it's time consuming process so i have created one progress dialog box..
below is my code
#Override
protected void onResume() {
super.onResume();
if (placesListItems != null)
placesListItems.clear();
new LoadPlaces().execute();
}
#Override
public void onPause() {
super.onPause();
if (pDialog != null)
pDialog.dismiss();
}
class LoadPlaces extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage(Html.fromHtml("<b>Search</b><br/>Loading Places..."));
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
GooglePlaces googlePlaces = new GooglePlaces();
try {
double radius = 1000; // 10000 meters
// get nearest places
if (query != null) {
nearPlaces = googlePlaces.search(lat, lon, radius, query);
if (nearPlaces != null) {
for (Place p : nearPlaces.results) {
reference = p.reference;
lat = p.geometry.location.lat;
lon = p.geometry.location.lng;
break;
}
}
}
String types = "bar|restaurant|night_club|gym|health|food|shopping_mall|hospital";
if (reference != null) {
PlaceDetails placeDetails = googlePlaces.getPlaceDetails(reference);
if (placeDetails != null) {
String status = placeDetails.status;
// check place deatils status
// Check for all possible status
if (status.equals("OK")) {
if (placeDetails.result != null) {
lat = placeDetails.result.geometry.location.lat;
lon = placeDetails.result.geometry.location.lng;
nearDeals = googlePlaces.search(lat, lon, radius, types);
In below code if i press home button or screen goes of during fetching data from server (You can say progress dialog box is running) and if i come back to my application i got an error ARRAY INDEX OUT OF BOUND
// int total = ;
for (int i = nearDeals.results.size() - 1; i >= 0; i--) {
// Log.i("WHAT THE HELL",nearPlaces.results.get(i).name);
if (getResult(nearDeals.results.get(i).name, nearDeals.results.get(i).geometry.location.lat,
nearDeals.results.get(i).geometry.location.lng) == 0) {
// nearDeals.results.add(nearPlaces.results.get(i));
nearDeals.results.remove(i);
}
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
below is logcat
09-25 18:23:13.429: W/System.err(4375): java.lang.IndexOutOfBoundsException: Invalid index 15, size is 15
09-25 18:23:13.429: W/System.err(4375): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:257)
09-25 18:23:13.429: W/System.err(4375): at java.util.ArrayList.get(ArrayList.java:311)
09-25 18:23:13.429: W/System.err(4375): at com.eheuristics.android.diegodeals.googleplacesandmaps.MainActivity$LoadPlaces.doInBackground(MainActivity.java:204)
09-25 18:23:13.429: W/System.err(4375): at com.eheuristics.android.diegodeals.googleplacesandmaps.MainActivity$LoadPlaces.doInBackground(MainActivity.java:1)
09-25 18:23:13.429: W/System.err(4375): at android.os.AsyncTask$2.call(AsyncTask.java:185)
09-25 18:23:13.439: W/System.err(4375): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
09-25 18:23:13.439: W/System.err(4375): at java.util.concurrent.FutureTask.run(FutureTask.java:138)
09-25 18:23:13.439: W/System.err(4375): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
09-25 18:23:13.439: W/System.err(4375): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
09-25 18:23:13.439: W/System.err(4375): at java.lang.Thread.run(Thread.java:1019)
if i do not press home key, or do not screen goes off during progress dialog box is running then everything is working fine
//After getting solution from all of you, i have done blow like all suggest but i got another error like blow
LoadPlaces ob;
protected void onResume() {
super.onResume();
if (placesListItems != null)
placesListItems.clear();
ob.execute();
}
#Override
public void onPause() {
super.onPause();
if(ob!=null)
if(ob.getStatus() == AsyncTask.Status.RUNNING){
ob.cancel(true);
}
if (pDialog != null)
pDialog.dismiss();
}
then i got error like below
09-25 18:53:30.609: E/AndroidRuntime(4674): java.lang.RuntimeException: Unable to resume activity {com.eheuristics.android.diegodeals/com.eheuristics.android.diegodeals.googleplacesandmaps.MainActivity}: java.lang.IllegalStateException: Cannot execute task: the task is already running.
09-25 18:53:30.609: E/AndroidRuntime(4674): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2241)
09-25 18:53:30.609: E/AndroidRuntime(4674): at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2256)
09-25 18:53:30.609: E/AndroidRuntime(4674): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:965)
09-25 18:53:30.609: E/AndroidRuntime(4674): at android.os.Handler.dispatchMessage(Handler.java:99)
09-25 18:53:30.609: E/AndroidRuntime(4674): at android.os.Looper.loop(Looper.java:130)
09-25 18:53:30.609: E/AndroidRuntime(4674): at android.app.ActivityThread.main(ActivityThread.java:3835)
09-25 18:53:30.609: E/AndroidRuntime(4674): at java.lang.reflect.Method.invokeNative(Native Method)
09-25 18:53:30.609: E/AndroidRuntime(4674): at java.lang.reflect.Method.invoke(Method.java:507)
09-25 18:53:30.609: E/AndroidRuntime(4674): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:864)
09-25 18:53:30.609: E/AndroidRuntime(4674): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:622)
09-25 18:53:30.609: E/AndroidRuntime(4674): at dalvik.system.NativeStart.main(Native Method)
09-25 18:53:30.609: E/AndroidRuntime(4674): Caused by: java.lang.IllegalStateException: Cannot execute task: the task is already running.
09-25 18:53:30.609: E/AndroidRuntime(4674): at android.os.AsyncTask.execute(AsyncTask.java:380)
09-25 18:53:30.609: E/AndroidRuntime(4674): at com.eheuristics.android.diegodeals.googleplacesandmaps.MainActivity.onResume(MainActivity.java:137)
09-25 18:53:30.609: E/AndroidRuntime(4674): at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1150)
09-25 18:53:30.609: E/AndroidRuntime(4674): at android.app.Activity.performResume(Activity.java:3832)
09-25 18:53:30.609: E/AndroidRuntime(4674): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2231)
09-25 18:53:30.609: E/AndroidRuntime(4674): ... 10 more
You are starting the asynctask every time you show your activity. So, you should cancel the task when exiting (AsyncTask.cancel(true)), or check if it is still running in the onResume method.
In the cases where you get the error onResume() gets called again, starting a new AsyncTask. Now you have multiple AsyncTask simultanously accessing and altering the size of nearDeals.results (you call remove on it). When one asyncTask removes an item from the list, the second asyncTask may run into the ArrayIndexOutOfBounds since the list size has changed.
EDIT: It's actually not the removal of an item, but that you set a new instance of the list in googlePlaces.search and this list may have a different size than the one used by the old asynctask.
Solution: call cancel on your running async tasks in onPause (or in onResume before starting
the new task)

Categories

Resources