Android: finish() Activity Runtime Exception - java

I am closing an activity via finish().
It works fine on several devices but on a Samsung Galaxy S3 Neo running Android 4.4 I get the following issue:
java.lang.RuntimeException
android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3706)
android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:3724)
android.app.ActivityThread.access$1500(ActivityThread.java:169)
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1330)
android.os.Handler.dispatchMessage(Handler.java:102)
android.os.Looper.loop(Looper.java:136)
android.app.ActivityThread.main(ActivityThread.java:5476)
java.lang.reflect.Method.invokeNative(Native Method)
java.lang.reflect.Method.invoke(Method.java:515)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
dalvik.system.NativeStart.main(Native Method)
Caused by: android.util.Log.println_native(Native Method)
android.util.Log.e(Log.java:307)
com.ads.adstimer.fragment.Registration.RegistrationActivity.onDestroy(RegistrationActivity.java:214)
android.app.Activity.performDestroy(Activity.java:5623)
android.app.Instrumentation.callActivityOnDestroy(Instrumentation.java:1123)
android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3693)
android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:3724)
android.app.ActivityThread.access$1500(ActivityThread.java:169)
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1330)
android.os.Handler.dispatchMessage(Handler.java:102)
android.os.Looper.loop(Looper.java:136)
android.app.ActivityThread.main(ActivityThread.java:5476)
java.lang.reflect.Method.invokeNative(Native Method)
java.lang.reflect.Method.invoke(Method.java:515)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
dalvik.system.NativeStart.main(Native Method)
I have found two posts about that subject: First, Second
But they did not help me.
My activity code. Note that I am using AppIntro:
public class RegistrationActivity extends AppIntro {
private AsyncTaskRegisterInBackground registerPushToken;
(...)
#Override
public void onDonePressed() {
(...)
if (regid.isEmpty()) {
registerPushToken = new AsyncTaskRegisterInBackground();
registerPushToken.setParams(activity, gcm, regid);
registerPushToken.execute();
}
(...)
}
#Override
public void onTaskCompleted(String responseRegid) {
try {
// load authToken from Server: JsonObjectRequest
builderOnFailureDialog = new MaterialDialog.Builder(activity)
.title(getResources().getString(R.string.registrierung_dialog_registrieren_failure_retry_title))
.content(onFailureDialogContent)
.positiveText(getResources().getString(R.string.registrierung_dialog_registrieren_failure_retry_positive_text))
.negativeText(getResources().getString(R.string.registrierung_dialog_registrieren_failure_retry_negative_text))
.onNegative(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(#NonNull MaterialDialog dialog, #NonNull DialogAction which) {
activity.finish();
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
onFailureDialog.dismiss();
onSuccessDialog.dismiss();
} catch (Exception e) {
Log.e("Activity.onDestroy()", e.getMessage());
}
}
}
Or is the reason for the problem the async task running in background?

call finish() inside runOnUiThread().
i.e.
replace
finish();
with
runOnUiThread(new Runnable() {
public void run() {
finish()
}
});

Related

Performing some actions and repeating them based on the time

Im writing my project app in Android Studio. The app is connected to microcontroller and send logic 1 on button Click to get data string from microcontroller all by BT. I have question for you how can i automatize it to send this logic 1 with some delay. I tried some methods but them dont work properly. The app stops
//Send Button
sendButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
sendData();
}
catch (IOException ex) { }
}
});
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
sendButton.performClick();
}
},20000);
LogCat:
2020-03-27 18:44:10.913 11754-11754/com.example.bt_serial_test_1_0 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.bt_serial_test_1_0, PID: 11754
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.view.View$DeclaredOnClickListener.onClick(View.java:5645)
at android.view.View.performClick(View.java:6608)
at com.example.bt_serial_test_1_0.MainActivity$4.run(MainActivity.java:104)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:6878)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:876)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.view.View$DeclaredOnClickListener.onClick(View.java:5640)
at android.view.View.performClick(View.java:6608) 
at com.example.bt_serial_test_1_0.MainActivity$4.run(MainActivity.java:104) 
at android.os.Handler.handleCallback(Handler.java:873) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:207) 
at android.app.ActivityThread.main(ActivityThread.java:6878) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:876) 
Caused by: java.lang.IllegalArgumentException: Invalid message body
at android.telephony.SmsManager.sendTextMessageInternal(SmsManager.java:337)
at android.telephony.SmsManager.sendTextMessage(SmsManager.java:325)
at com.example.bt_serial_test_1_0.MainActivity.sendSms(MainActivity.java:239)
at java.lang.reflect.Method.invoke(Native Method) 
at android.view.View$DeclaredOnClickListener.onClick(View.java:5640) 
at android.view.View.performClick(View.java:6608) 
at com.example.bt_serial_test_1_0.MainActivity$4.run(MainActivity.java:104) 
at android.os.Handler.handleCallback(Handler.java:873) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:207) 
at android.app.ActivityThread.main(ActivityThread.java:6878) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:876) 
this method is in onCreate. Can someone please help me to resolve this problem
Here is a Handler example for a repeating task.
// Create the Handler object (on the main thread by default)
Handler handler = new Handler();
// Define the code block to be executed
private Runnable runnableCode = new Runnable() {
#Override
public void run() {
// Do something here on the main thread
Log.d("Handlers", "Called on main thread");
// Repeat this the same runnable code block again another 2 seconds
handler.postDelayed(runnableCode, 2000);
}
};
// Start the initial runnable task by posting through the handler
handler.post(runnableCode);
You can modify it for your case like that
sendButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
handler().postDelayed(r,1000);
}
catch (IOException ex) { }
}
});
final Runnable r = new Runnable()
{
public void run()
{
sendButton.performClick();
}
};

NPE thrown by MqttAndroidClient.publish() without any variable set to null

This event makes me think I forgot everything about programming in Java, as a NPE is thrown without any variable set to null.
In the next code how is it possible that the process reach the catch clause with e equal to NPE if neither msg nor mqttAndroidClient are null?
BTW, MqttAndroidClient is not supposed to throw a NPE according to MQTT documentation.
public class MainActivity extends AppCompatActivity {
MqttAndroidClient mqttAndroidClient;
final String serverUri = "tcp://iot.eclipse.org:1883";
String clientId = "ExampleAndroidClient";
final String publishTopic = "location";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mqttAndroidClient = MqttClientSingleton.getMqttClient(getApplicationContext(), serverUri, clientId);
mqttAndroidClient.setCallback(new MqttCallback() {
#Override
public void connectionLost(Throwable cause) {
try {
mqttAndroidClient.connect();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
#Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
}
#Override
public void deliveryComplete(IMqttDeliveryToken token) {
}
});
mqttAndroidClient.connect();
try {
MqttMessage msg = new MqttMessage("test".getBytes());
mqttAndroidClient.publish(publishTopic, msg);
} catch (Exception e) {
throw new RuntimeException(e);
}
;
}
}
This is the MqttClientSingleton
import android.content.Context;
import org.eclipse.paho.android.service.MqttAndroidClient;
/**
* Created by storassa on 4/30/17.
*/
public class MqttClientSingleton {
private static MqttAndroidClient client;
public static MqttAndroidClient getMqttClient(Context c, String uri, String id) {
if (client == null) {
client = new MqttAndroidClient(c, uri, id);
return client;
}
else
return client;
}
}
This is the logcat
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.storassa.android.giulia/com.storassa.android.giulia.MainActivity}: java.lang.RuntimeException: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2202)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2252)
at android.app.ActivityThread.access$800(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1200)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5103)
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:788)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:604)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.RuntimeException: java.lang.NullPointerException
at com.storassa.android.giulia.MainActivity.onCreate(MainActivity.java:54)
at android.app.Activity.performCreate(Activity.java:5275)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2166)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2252) 
at android.app.ActivityThread.access$800(ActivityThread.java:139) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1200) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:136) 
at android.app.ActivityThread.main(ActivityThread.java:5103) 
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:788) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:604) 
at dalvik.system.NativeStart.main(Native Method) 
Caused by: java.lang.NullPointerException
at org.eclipse.paho.android.service.MqttAndroidClient.publish(MqttAndroidClient.java:812)
at org.eclipse.paho.android.service.MqttAndroidClient.publish(MqttAndroidClient.java:668)
at com.storassa.android.giulia.MainActivity.onCreate(MainActivity.java:52)
at android.app.Activity.performCreate(Activity.java:5275) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2166) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2252) 
at android.app.ActivityThread.access$800(ActivityThread.java:139) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1200) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:136) 
at android.app.ActivityThread.main(ActivityThread.java:5103) 
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:788) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:604) 
at dalvik.system.NativeStart.main(Native Method) 
NEW EDIT
I added the MqttClientSingleton code and the line with mqttAndroidClient.connect() that got lost in the copy and paste

How can I change the volume properly?

I have been stuck on this for way too long (4 hours yesterday, 3 hours today!) now. In my main menu screen, I have a mute button. I want it to call a method in my background service, which mutes all of the MediaPlayer audio that would be played in the background of my game.
Full code here
Here is something that might be causing the issue:
I am getting the error whenever the audio plays (which plays fine):
QCMediaPlayer mediaplayer NOT present
E/MediaPlayer﹕ Should have subtitle controller already set
package com.example.USERNAME.buttonsmasher;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
public class TwentySeconds extends Service {
static MediaPlayer ten;
static MediaPlayer three;
final String TAG = "MyCountdown";
static CountDownTimer cdt;
double millisUntilFinishedRounded;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Context context = this;
three = MediaPlayer.create(TwentySeconds.this, R.raw.threetwoone);
ten = MediaPlayer.create(TwentySeconds.this, R.raw.tenmoreseconds);
// ten = MediaPlayer.create(TwentySeconds.this, R.raw.tenmoreseconds);
// three = MediaPlayer.create(TwentySeconds.this, R.raw.threetwoone);
Log.v(TAG, "In start command");
cdt = new CountDownTimer(20000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
Log.v(TAG, millisUntilFinished + "left");
millisUntilFinishedRounded = (millisUntilFinished / 1000) * 1000;
if (millisUntilFinishedRounded == 10000) { //TEN SECONDS
// ten = MediaPlayer.create(TwentySeconds.this, R.raw.tenmoreseconds);
// while(ten == null){
ten = MediaPlayer.create(TwentySeconds.this, R.raw.tenmoreseconds);
// }
ten.start();
}
if (millisUntilFinishedRounded == 3000) {
/* Context context = this;
three = MediaPlayer.create(TwentySeconds.this, R.raw.threetwoone);
*/
// while(three == null){
three = MediaPlayer.create(TwentySeconds.this, R.raw.tenmoreseconds);
//}
three.start();
}
}
#Override
public void onFinish() {
Log.v(TAG, "Finished");
Intent intent = new Intent(TwentySeconds.this, GameOver.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Log.v(TAG, "About to start activity");
startActivity(intent);
}
};
cdt.start();
return START_STICKY;
}
public static void stopTimer() {
cdt.cancel();
}
public static void myMute() {
ten.setVolume(0, 0);
three.setVolume(0, 0);
}
public static void unMute() {
ten.setVolume(1, 1);
three.setVolume(1, 1);
}
#Override
public void onDestroy() {
stopSelf();
super.onDestroy();
}
}
_______________________________________________________________________________________________________________________________
Here is the method in Main_Menu (x starts as zero)
if ((x%2) == 0) { //If it's even
TwentySeconds.unMute();
Toast.makeText(Main_Menu.this, "UNMUTED", Toast.LENGTH_SHORT).show();
x++;
} else { //If its odd
TwentySeconds.myMute();
Toast.makeText(Main_Menu.this, "MUTED", Toast.LENGTH_SHORT).show();
x++;
}
__________________________________________________________________
Here is the stack trace:
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3842)
at android.view.View.performClick(View.java:4457)
at android.view.View$PerformClick.run(View.java:18491)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5272)
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:883)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3837)
at android.view.View.performClick(View.java:4457)
at android.view.View$PerformClick.run(View.java:18491)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5272)
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:883)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.USERNAME.buttonsmasher.TwentySeconds.myMute(TwentySeconds.java:106)
at com.example.USERNAME.buttonsmasher.Main_Menu.mute(Main_Menu.java:103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3837)
at android.view.View.performClick(View.java:4457)
at android.view.View$PerformClick.run(View.java:18491)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5272)
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:883)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
at dalvik.system.NativeStart.main(Native Method)
I would really appreciate any feedback (positive or negative)!
Let me know if you need any thing else. Thanks so much for everything, I hope I can solve this issue... :)

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

TCP socket on Android 4.0.3

I am working on a project in which I have a TCP connection with a server via Android.
I am using the following code:
public class MyService extends Service {
private static final String TAG = "MyService";
MediaPlayer player;
Socket s;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
player = MediaPlayer.create(this, R.raw.braincandy);
player.setLooping(false); // Set looping
}
#Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
player.stop();
try {
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
player.start();
try {
s = new Socket("192.168.1.54", 64000);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I am running the connection as a service.
The real problem is I can make a connection with my Android phone (2.3.7) and with the emulator (2.3.3) but when I want to test in on my tablet (4.0.3), my app always crashes when I want to start the connection.
Can someone help me with this?
Here is the logcat log:
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start service
com.gunther.servicetcp.MyService#412b0a98 with Intent
{ cmp=com.gunther.servicetcp/.MyService }: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2376)
at android.app.ActivityThread.access$1900(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.os.NetworkOnMainThreadException
0at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
at libcore.io.IoBridge.connect(IoBridge.java:112)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.Socket.startupSocket(Socket.java:566)
at java.net.Socket.tryAllAddresses(Socket.java:127)
at java.net.Socket.<init>(Socket.java:177)
at java.net.Socket.<init>(Socket.java:149)
at com.gunther.servicetcp.MyService.onStart(MyService.java:53)
at android.app.Service.onStartCommand(Service.java:438)
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2359)
: ... 10 more
You shouldn't do network operations on the main thread. This will lead to your app being unresponsive. Before Honeycomb you could get away with it, but Honeycomb and newer Android versions will check and throw the exception you're getting. See also this page of the Android Developers API
Services's onStart() method runs on the main thread, (yes, services seem to run on the main thread of the application.) so you should fork another thread in the onStart() method and do everything you need to do in that thread.

Categories

Resources