How do I stop a runnable when I start another activity? - java

I have a Android app that shows a dialog when a value is '1' and shows the dialog repeatedly till the value is set to '0'. A Runnable calls a Handler which starts the dialog, and the Runnable loops with a delay.
Problem is that when I go to another activity with the same function and go back, the dialog is already open. This causes my app to crash. I already try to use removeMessage and removeCallback but still have the problem.
Handler
Handler myHandler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
/* Dialog */
final AlertDialog.Builder AlertAlarm_Build;
LayoutInflater inflater = (LayoutInflater) Settings_Activity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
AlertAlarm_Build = new AlertDialog.Builder(Settings_Activity.this);
final View Disengaged_View;
Disengaged_View = inflater.inflate(R.layout.disengage_dialog,null);
final AlertDialog PasswordDialog = AlertAlarm_Build.create();
PasswordDialog.show();
final String[] given_password = new String[1];
final boolean[] Password_Pass = {false};
//respose
final RequestQueue requestHander;
requestHander = (RequestQueue) Volley.newRequestQueue(getApplicationContext());
...//Ask for password
//New
PasswordDialog.setOnDismissListener(new DialogInterface.OnDismissListener()
{
#Override
public void onDismiss(DialogInterface dialogInterface)
{
recreate();
}
});
}
};
Runnable
//Runnable
final Runnable aMyRunnable = new Runnable()
{
#Override
public void run()
{
RequestQueue requestRun;
requestRun = (RequestQueue) Volley.newRequestQueue(getApplicationContext());
if(New_engaged[0].equals("1") && New_alarm[0].equals("1"))
{
set_engaged[0] = "1";
myHandler.sendEmptyMessage(0);
}
else
{
requestRun.add(JOR_SystemCheck);
myHandler.postDelayed(this,5000);
}
}
};
onStop
protected void onStop() {
super.onStop();
myHandler.removeCallbacksAndMessages(aMyRunnable);
myHandler.removeMessages(0);
}
Error
/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.djwiz.eclipse5, PID: 17705
android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy#f8866f3 is not valid; is your activity running?
at android.view.ViewRootImpl.setView(ViewRootImpl.java:765)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:356)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:92)
at android.app.Dialog.show(Dialog.java:330)
at com.example.djwiz.eclipse5.Settings_Activity$1.handleMessage(Settings_Activity.java:68)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

Based on the documentation for removeCallbacksAndMessages
Remove any pending posts of callbacks and sent messages whose obj is token. If token is null, all callbacks and messages will be removed
Your code won't match any token:
myHandler.removeCallbacksAndMessages(aMyRunnable);
So the solution would be to use:
myHandler.removeCallbacksAndMessages(null);

Related

DialogFragment crashes when calling show()

I want to display a simple DialogFragment within a Fragment, but it crashes every time the show() method is called.
It either crashes back to the MainActivity or it throws me a NullPointer Exception that does not seem to be related to the crash directly. I think Logcat swallows the actual problem somehow.
Here is the call and the DialogFragment subclass:
private void showCheatingDialog() {
DialogFragment newFragment = new CheatingDialogFragment();
newFragment.show(getChildFragmentManager(), "CheatingDialogFragment");
}
#Override
public void onCheatingPositiveClick(DialogFragment dialog) {
try {
client.puzzleDone(BLUFF);
} catch(IOException ex) {
Log.e("tiles", ex.toString());
Toast.makeText(getActivity(), "Connection to the server failed", Toast.LENGTH_LONG).show();
Intent intent = new Intent(getActivity(), MainActivity.class);
startActivity(intent);
}
}
#Override
public void onCheatingCancelClick(DialogFragment dialog) {
// do nothing
}
public class CheatingDialogFragment extends DialogFragment {
public interface CheatingDialogListener {
public void onCheatingPositiveClick(DialogFragment dialog);
public void onCheatingCancelClick(DialogFragment dialog);
}
CheatingDialogListener listener;
// Override the Fragment.onAttach() method to instantiate the CheatingDialogListener
#Override
public void onAttach(Context context) {
super.onAttach(context);
// Verify that the host activity implements the callback interface
try {
// Instantiate the CheatingDialogListener so we can send events to the host
listener = (CheatingDialogListener) context;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(getActivity().toString()
+ " must implement CheatingDialogListener");
}
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Build the dialog and set up the button click handlers
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.cheating_dialog_fragment)
.setPositiveButton(R.string.cheating_dialog_positive, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Send the positive button event back to the host activity
listener.onCheatingPositiveClick(CheatingDialogFragment.this);
}
})
.setNegativeButton(R.string.cheating_dialog_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Send the negative button event back to the host activity
listener.onCheatingCancelClick(CheatingDialogFragment.this);
}
});
return builder.create();
}
}
Here's the exception Logcat shows:
2021-06-17 08:45:04.952 7095-7095/com.example.se2_gruppenphase_ss21 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.se2_gruppenphase_ss21, PID: 7095
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.se2_gruppenphase_ss21.networking.AvailableRoom.getName()' on a null object reference
at com.example.se2_gruppenphase_ss21.menu.RoomFragment.onCreateView(RoomFragment.java:86)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2698)
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:320)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1187)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1356)
at androidx.fragment.app.FragmentManager.moveFragmentToExpectedState(FragmentManager.java:1434)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1497)
at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2625)
at androidx.fragment.app.FragmentManager.dispatchActivityCreated(FragmentManager.java:2577)
at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:247)
at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:541)
at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:210)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1435)
at android.app.Activity.performStart(Activity.java:8024)
at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3475)
at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:221)
at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:201)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:173)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)

NullPointerException Context errors on code moved from one working source into a Main application

Context is not a strong point of mine, I keep getting this error this is part of code i have moved over from another application and works in there just fine, however i am trying to transplant the code from the smaller app to this main app, as adding it as a library was causing headaches which are best sorted out another day.
So the error i receive is:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.app, PID: 12564
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at androidx.localbroadcastmanager.content.LocalBroadcastManager.getInstance(LocalBroadcastManager.java:107)
at com.app.TManager.startUpdatingTrace(TManager.java:229)
at com.app.activities.ui.routeaction.RouteActionFragment$2.onFinish(RouteActionFragment.java:128)
at android.os.CountDownTimer$1.handleMessage(CountDownTimer.java:127)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
So this is the relevant code in TManager:
public class TManager extends AppCompatActivity implements Serializable {
BroadcastReceiver sensorReceiver;
BroadcastReceiver locationReceiver;
ExecutorService executorService = Executors.newFixedThreadPool(20);
public static Intent locationIntent;
public static Intent sensorService;
public LocalBroadcastManager localBroadcastManager;
public static MutableLiveData<Integer> status = new MutableLiveData<Integer>();
//Empty constructor
public TManager(){}
#RequiresApi(api = Build.VERSION_CODES.O)
public void startUpdating() {
status.setValue(0);
//register for sensorBroadcast
sensorReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
TCIMUEvent tcimuEvent = (TCIMUEvent) intent.getSerializableExtra("imuevent");
// Log.d(TAG, "In Motion Received "+ tcimuEvent.getTime());
Runnable provideDM = new Runnable() {
#Override
public void run() {
//traceCWrapper.provideDeviceMotion(tcimuEvent, Status, 0, RotationMode.Undetermined);
}
};
executorService.execute(provideDM);
}
};
localBroadcastManager.getInstance(MyApplication.getAppContext()).registerReceiver(
sensorReceiver, new IntentFilter("imuCreated")
);
//register for locationBroadcast
locationReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
TCLocationEvent tcLocationEvent = (TCLocationEvent) intent.getSerializableExtra("locationevent");
Runnable provideLoc = new Runnable() {
#Override
public void run() {
traceCWrapper.provideLocation(tcLocationEvent);
}
};
executorService.execute(provideLoc);
}
};
LocalBroadcastManager.getInstance(context).registerReceiver( //Error Here <-----
locationReceiver, new IntentFilter("locationCreated")
);
isRunning = true;
//Start the Services
AsyncTask as1 = new AsyncTask() {
#Override
protected Object doInBackground(Object[] objects) {
startUpdatingLocation();
return null;
}
}.execute();
AsyncTask as2 = new AsyncTask() {
#Override
protected Object doInBackground(Object[] objects) {
startUpdatingSensors();
return null;
}
}.execute();
}
}
This is just one example i keep getting these errors all through the code which was copied in another example error:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.AssetManager android.content.Context.getAssets()' on a null object reference
It seeems to especially be where is use
MyApplication.getAppContext......
MyApplication just returns as below:
public class MyApplication extends Application {
private static Context context;
public void onCreate() {
super.onCreate();
MyApplication.context = getApplicationContext();
}
public static Context getAppContext() {
return MyApplication.context;
}
}
How do i resolve these issues? The whole classes have been moved over it is not code taken from one class dumped into another. So not sure why context should have changed.
As i was using the MyApplication static context class in some places i needed to add this line to my Manifest file within the tag
android:name="com.yourapp.app.yourapp.MyApplication"
and make sure the application class is placed in the top level main/java/com.yourapp.app.yourapp/
This worked for me and solved the issue throughout the App. I would pay attention to the comments made as this may well not be the best way to be using Context, however this solved my issue at the moment.

Sinch Service not starting in Android

I was trying out the sample programs provided by Sinch and was getting a NullPointerException. I traced the code and found that it was caused by my device not connecting to the SinchService.
The code is as follows
public class LoginActivity extends BaseActivity implements SinchService.StartFailedListener {
private Button mLoginButton;
private EditText mLoginName;
private ProgressDialog mSpinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
mLoginName = (EditText) findViewById(R.id.loginName);
mLoginButton = (Button) findViewById(R.id.loginButton);
mLoginButton.setEnabled(false);
mLoginButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
loginClicked();
}
});
}
#Override
protected void onServiceConnected() {
mLoginButton.setEnabled(true);
getSinchServiceInterface().setStartListener(this);
}
#Override
protected void onPause() {
if (mSpinner != null) {
mSpinner.dismiss();
}
super.onPause();
}
#Override
public void onStartFailed(SinchError error) {
Toast.makeText(this, error.toString(), Toast.LENGTH_LONG).show();
if (mSpinner != null) {
mSpinner.dismiss();
}
}
#Override
public void onStarted() {
openPlaceCallActivity();
}
private void loginClicked() {
String userName = mLoginName.getText().toString();
if (userName.isEmpty()) {
Toast.makeText(this, "Please enter a name", Toast.LENGTH_LONG).show();
return;
}
if (!getSinchServiceInterface().isStarted()) {
getSinchServiceInterface().startClient(userName);
showSpinner();
} else {
openPlaceCallActivity();
}
}
private void openPlaceCallActivity() {
Intent mainActivity = new Intent(this, PlaceCallActivity.class);
startActivity(mainActivity);
}
private void showSpinner() {
mSpinner = new ProgressDialog(this);
mSpinner.setTitle("Logging in");
mSpinner.setMessage("Please wait...");
mSpinner.show();
}
}
I could see that since the service is not connecting I am not getting a correct output when I call getSinchServiceInterface(). It always returns null. My device is connected to the internet and the backend app in the Sinch dashboard seems to be working fine too.
LogCat:
12-22 17:43:38.432 2301-2301/com.login_signup_screendesign_demo E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.login_signup_screendesign_demo, PID: 2301
java.lang.NullPointerException
at calling.LoginActivity.loginClicked(LoginActivity.java:78)
at calling.LoginActivity.access$000(LoginActivity.java:15)
at calling.LoginActivity$1.onClick(LoginActivity.java:32)
at android.view.View.performClick(View.java:4463)
at android.view.View$PerformClick.run(View.java:18770)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5292)
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:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
What could be the cause of this error and how to solve it?
UPDATE:
I exactly copy pasted the android code downloaded from this page. I am using sinch-rtc-sample-calling app from that file. I compiled and ran the app separately and it was working fine. Then I copy pasted all the java and xml from that app into the one which I am working and it is not working. Why is this happening. This might be the reason for the NullPointerException. After copy pasting I found that the login button is disabled. That means the onServiceConnected() is not executing. I tried calling it manually and that is resulting in the NPE, but that is happening correctly in the standalone app. I am getting these kind of problems only upon integration.
PS : I updated the manifest and gradle as per the new files.
Have had the same issue over the past few days.
In my case it is because I hadn`t added the following in the manifest under application node
<service android:name=".SinchService"/>
Make sure that the setting is in your application manifest. That solved it for me.
everything looks fine, uncomment the commented part because there is one condition which is being checked and it returns
private boolean isStarted() {
return (mSinchClient != null && mSinchClient.isStarted());
}
before getting SinchService and Also check your
private static final String APP_KEY = "app_key";
private static final String APP_SECRET = "app_secret";
private static final String ENVIRONMENT = "sandbox.sinch.com";
in SinchService.java, are the correct or not.

Android Retrofit "Attempt to invoke virtual method on a null object reference"

Hi first of all i searched some similar questions like mine but unfortunately i couldn't find the similarity of my code to them so please here me out
I have a Main Activity Class
public class MainActivity extends AppCompatActivity {
public ProgressDialog loading;
public String[] itemer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RetrofitHandler handler = new RetrofitHandler();
handler.getContacts(MainActivity.this);
}
public void getter(String[] response, int size) {
String[] itemer;
itemer = new String[size];
if (response != null) {
itemer = response;
Toast.makeText(MainActivity.this, itemer[0], Toast.LENGTH_SHORT).show();
}
}
And a Handler for my result
public class RetrofitHandler {
public String[] item;
public static final String ROOT_URL = "http://api.androidhive.info";
public List<Contacts> contacts;
// final MainActivity main = new MainActivity();
public void getContacts(final Context context) {
final ProgressDialog loading = ProgressDialog.show(context, "Fetching Data", "Please wait...", false, false);
RestAdapter adapter = new RestAdapter.Builder().setEndpoint(ROOT_URL).build();
ContactsAPI api = adapter.create(ContactsAPI.class);
api.getContacts(new Callback<Contacts>() {
#Override
public void success(Contacts contacts, Response response) {
loading.dismiss();
MainActivity update = new MainActivity();
List<Contact> contactList = contacts.getContacts();
item = new String[contactList.size()];
int size = contactList.size();
for (int i = 0; i < contactList.size(); i++) {
item[i] = contactList.get(i).getName();
}
update.getter(item, size);
}
#Override
public void failure(RetrofitError error) {
Toast.makeText(context, "Error Occured", Toast.LENGTH_LONG).show();
}
});
}
But I get an error on my response in the main activity here is my log
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.content.ContextWrapper.getResources(ContextWrapper.java:87)
at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:81)
at android.support.v7.app.AppCompatActivity.getResources(AppCompatActivity.java:542)
at android.widget.Toast.<init>(Toast.java:102)
at android.widget.Toast.makeText(Toast.java:259)
at com.exist.kelvs.retrofit2.MainActivity.getter(MainActivity.java:55)
at com.exist.kelvs.retrofit2.RetrofitHandler$1.success(RetrofitHandler.java:41)
at com.exist.kelvs.retrofit2.RetrofitHandler$1.success(RetrofitHandler.java:28)
at retrofit.CallbackRunnable$1.run(CallbackRunnable.java:45)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
I maked sure that the handler item where not null tested it with toast but when i pass it to getter it gives me the error where did i do wrong? :(
MainActivity update = new MainActivity();
Never instantiate activities with new. They are not initialized to be useful.
Instead, you can pass your activity as a reference where needed. Change
public void getContacts(final Context context)
to e.g.
public void getContacts(final MainActivity mainActivity)
and use mainActivity where you need an activity Context (such as with Dialogs) and when you need to invoke a method on MainActivity.
Note that generally passing activity references to async operations can be prone to significant memory leaks, and you need to take activity lifecycle into account - the activity might not be active when the async operation finishes.
try to delete the toast in your main activity or replace Mainactivity.this to getApplicationContext() .
from :
Toast.makeText(MainActivity.this, itemer[0], Toast.LENGTH_SHORT).show();
to :
Toast.makeText(getApplicationContext(), itemer[0], Toast.LENGTH_SHORT).show();

Android: Redirect to another Activity after delay

So I am developing a simple app for a college project, And I have been able to integrate a Facebook login using fragments.
But I now am stuck trying to redirect the user after they login. I simply want to redirect them to the second activity page
Here is my code for the Facebook login success
private FacebookCallback<LoginResult> mCallback=new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
if (profile != null) {
display.setText("Welcome: " + profile.getFirstName());
//Redirect to Second Activity
}
}
To make a delayed transition use Handler class's postDelayed(Runnable r, long delayMillis) method, for example:
Java
Runnable r = new Runnable() {
#Override
public void run() {
// if you are redirecting from a fragment
// then use getActivity() as the context.
startActivity(new Intent(CurrentActivity.this, TargetActivity.class));
}
};
Handler h = new Handler();
// The Runnable will be executed after the given delay time
h.postDelayed(r, 1500); // will be delayed for 1.5 seconds
Kotlin with Anko
val someThread = Runnable {
startActivity(intentFor<TargetActivity>())
}
Handler().postDelayed(someThread, 1500)
Simply call a new activity through intent:
Intent i = new Intent(LoginActivity.this, HomeActivity.class);
startActivity(i);
finish();
Check this:-
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i=new Intent(CurrentActivity.this,Next.class);
startActivity(i);
}
}, 3000);
A Handler allows you to send and process Message and Runnable objects
associated with a thread's MessageQueue. Each Handler instance is
associated with a single thread and that thread's message queue. When
you create a new Handler, it is bound to the thread / message queue of
the thread that is creating it -- from that point on, it will deliver
messages and runnables to that message queue and execute them as they
come out of the message queue.
You can use Handler postDelayed Method easily .
Handler hd = new Handler();
hd.postDelayed(new Runnable() {
#Override
public void run() {
// Add Your Intent
}
}, 2000); // Time Delay ,2 Seconds
}
In Kotlin;
val r = Runnable {
startActivity(Intent(this, AuthorActivity::class.java))
}
val h = Handler()
h.postDelayed(r, 10)

Categories