Counter variable not updating when switching between views - android-studio

I am trying to create a counter that updates everytime you go back to the main view. The only issue is that everytime I go back to the main view, the counter is getting reset to 1.
package com.example.usingintent2;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private int counter = 0;
Button btn;
TextView txv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txv = (TextView) findViewById(R.id.counterText);
}
public void onClick(View view) {
startActivity(new Intent("com.example.usingintent2.SecondActivity"));
counter++;
txv = (TextView) findViewById(R.id.counterText);
txv.setText(Integer.toString(counter));
}
public void onStart(){
super.onStart();
counter++;
txv = (TextView) findViewById(R.id.counterText);
txv.setText(Integer.toString(counter));
}
public void onResume(){
super.onResume();
counter++;
txv.setText(Integer.toString(counter));
}
}

You have to use your saveInstanceState Bundle to save your value.
public TextView txv;
private static final String KEY_USERENTRY = "KEY_USERENTRY";
private int counter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txv = (TextView) findViewById(R.id.textView);
txv.setText(Integer.toString(counter));
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(KEY_USERENTRY, yourvalue);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
counter = savedInstanceState.getInt(KEY_USERENTRY);
}
}
yourvalue is the value you want to save.

Related

I am trying to start new activity through intent but facing this error

I am working on multiple Activities and i got this error while using
context - java.lang.NullPointerException: Attempt to invoke virtual
method
'java.lang.String android.content.Context.getPackageName()' on a null
object reference
public class myadapter extends FirebaseRecyclerAdapter<Asia, myadapter.myviewholder> {
private Context context;
Asia asiaData;
I have created the context constructer
public myadapter(#NonNull FirebaseRecyclerOptions<Asia> options, Context context, Asia asiaData) {
super(options);
this.context = context;
this.asiaData = asiaData;
}
public myadapter(#NonNull FirebaseRecyclerOptions<Asia> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull myviewholder holder, int position, #NonNull Asia asia) {
I got error on null reference on Context
final Asia temp = asiaData;
holder.tvName.setText(asia.getConName());
holder.tvCap.setText(asia.getCapital());
Glide.with(holder.img.getContext()).load(asia.getImg()).into(holder.img);
holder.img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(new Intent(context, MainActivityCountry.class));
intent.putExtra("name", temp.getConName());
intent.putExtra("capital", temp.getCapital());
intent.putExtra("desc", temp.getDesc());
intent.putExtra("img", temp.getImg());
context.startActivity(intent);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
});
}
#NonNull
#Override
public myviewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rv_item, parent, false);
return new myviewholder(view);
}
/* ******** VIEW HOLDER ********** */
class myviewholder extends RecyclerView.ViewHolder {
ImageView img;
TextView tvName, tvCap;
public myviewholder(#NonNull View itemView) {
super(itemView);
img = itemView.findViewById(R.id.img);
tvName = (TextView) itemView.findViewById(R.id.tvName);
tvCap = (TextView) itemView.findViewById(R.id.tvCap);
}
}
}
Here is the Activity where i have call the adapter
package com.example.recyclerview;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.FirebaseDatabase;
public class ActivityAsia extends AppCompatActivity {
RecyclerView rv;
Context context;
Button btn_addCountry;
myadapter adapter;
ImageView img;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
setTitle("Recycler View");
rv = findViewById(R.id.rView);
btn_addCountry = findViewById(R.id.btn_addCountry);
img =(ImageView)findViewById(R.id.img);
rv.setLayoutManager(new LinearLayoutManager(this));
FirebaseRecyclerOptions<Asia> options = new FirebaseRecyclerOptions.Builder<Asia>()
.setQuery(FirebaseDatabase.getInstance().getReference().child("Asia"), Asia.class)
.build();
adapter = new myadapter(options);
rv.setAdapter(adapter);
btn_addCountry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ActivityAsia.this, AddItemAsia.class);
startActivity(intent);
}
});
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
}
In your ActivityAsia activity call adapter like this
adapter = new myadapter(ActivityAsia.this,options);
rv.setAdapter(adapter);
and in your myadapter like this
public class myadapter extends FirebaseRecyclerAdapter<Asia, myadapter.myviewholder> {
private Context context;
FirebaseRecyclerOptions<Asia> options;
public myadapter(Context context,#NonNull FirebaseRecyclerOptions<Asia> options) {
super(options);
this.context = context;
this. options = options;
}
#Override
protected void onBindViewHolder(#NonNull myviewholder holder, int position, #NonNull Asia asia) {
final Asia temp = options;
holder.tvName.setText(asia.getConName());
holder.tvCap.setText(asia.getCapital());
Glide.with(holder.img.getContext()).load(asia.getImg()).into(holder.img);
holder.img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(new Intent(context, MainActivityCountry.class));
intent.putExtra("name", temp.getConName());
intent.putExtra("capital", temp.getCapital());
intent.putExtra("desc", temp.getDesc());
intent.putExtra("img", temp.getImg());
context.startActivity(intent);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
});
}
#NonNull
#Override
public myviewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rv_item, parent, false);
return new myviewholder(view);
}
/* ******** VIEW HOLDER ********** */
class myviewholder extends RecyclerView.ViewHolder {
ImageView img;
TextView tvName, tvCap;
public myviewholder(#NonNull View itemView) {
super(itemView);
img = itemView.findViewById(R.id.img);
tvName = (TextView) itemView.findViewById(R.id.tvName);
tvCap = (TextView) itemView.findViewById(R.id.tvCap);
}
}
}

Open new activity by Clicking button in a Fragment

I'm currently working on a mobile app as a final project for my course. I have these two fragments inside a ViewPager2 controlled by a TabLayout. There are buttons inside of these fragments.
The first frag contains 2 buttons. The other frag has only one button. I want them to open an activity but the problem is when I run the app, these buttons won't work. They didn't open the other activity.
Login Fragment
package com.example.biowit;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.blogspot.atifsoftwares.animatoolib.Animatoo;
public class LoginTabFragment extends Fragment {
EditText email, password;
Button btn_login, btn_forpass;
TextView textView;
float v=0;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.login_fragment, container, false);
email = root.findViewById(R.id.input_LI_email);
password = root.findViewById(R.id.input_LI_pass);
btn_forpass = root.findViewById(R.id.btn_FPass);
btn_login = root.findViewById(R.id.btn_LIn);
email.setTranslationX(800);
password.setTranslationX(800);
btn_forpass.setTranslationX(800);
btn_login.setTranslationX(800);
email.setAlpha(v);
password.setAlpha(v);
btn_forpass.setAlpha(v);
btn_login.setAlpha(v);
email.animate().translationX(0).alpha(1).setDuration(800).setStartDelay(300).start();
password.animate().translationX(0).alpha(1).setDuration(800).setStartDelay(300).start();
btn_forpass.animate().translationX(0).alpha(1).setDuration(800).setStartDelay(300).start();
btn_login.animate().translationX(0).alpha(1).setDuration(800).setStartDelay(300).start();
btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), HomeScreen.class);
startActivity(intent);
Animatoo.animateFade(getActivity());
getActivity().finish();
}
});
return root;
}
}
LoginScreen (where the fragment locates)
package com.example.biowit;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import androidx.viewpager2.widget.ViewPager2;
import android.os.Bundle;
import com.google.android.material.tabs.TabItem;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
public class
LoginScreen extends AppCompatActivity {
TabLayout tabLayout;
ViewPager2 viewPager;
float v=1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_screen);
tabLayout = findViewById(R.id.tab_layout);
viewPager = findViewById(R.id.view_pager);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
LoginAdapter login_adapter = new LoginAdapter(this);
viewPager.setAdapter(login_adapter);
new TabLayoutMediator(tabLayout, viewPager,
new TabLayoutMediator.TabConfigurationStrategy() {
#Override
public void onConfigureTab(#NonNull TabLayout.Tab tab, int position) {
switch (position){
case 0:
tab.setText("LOGIN");
break;
case 1:
tab.setText("SIGNUP");
break;
}
}
}).attach();
tabLayout.setAlpha(v);
}
}
Here's the error log(?)
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.biowit, PID: 18551
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.biowit/com.example.biowit.HomeScreen}: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.hide()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3754)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3912)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2319)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:239)
at android.app.ActivityThread.main(ActivityThread.java:8212)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:626)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1016)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.hide()' on a null object reference
at com.example.biowit.HomeScreen.onCreate(HomeScreen.java:22)
at android.app.Activity.performCreate(Activity.java:8119)
at android.app.Activity.performCreate(Activity.java:8103)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1359)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3727)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3912) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2319) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:239) 
at android.app.ActivityThread.main(ActivityThread.java:8212) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:626) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1016) 
HomeScreen (Activity that supposedly open when clicking the button)
package com.example.biowit;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
public class HomeScreen extends AppCompatActivity {
Button Chap1_btn, Achieve_btn, HowToPlay_btn, LogOut_btn, Settings_btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
getSupportActionBar().hide(); // hides the action bar.
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
Chap1_btn = findViewById(R.id.btn_Chap1);
Achieve_btn = findViewById(R.id.btn_Achievements);
HowToPlay_btn = findViewById(R.id.btn_HowToPlay);
LogOut_btn = findViewById(R.id.btn_Logout);
Settings_btn = findViewById(R.id.btn_Settings);
Chap1_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent open_Chap1 = new Intent(getApplicationContext(), LessonScreen.class);
startActivity(open_Chap1);
}
});
Achieve_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Intent open_Achievements = new Intent(getApplicationContext(), Achievements.class);
}
});
HowToPlay_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Intent open_HowToPlay = new Intent(getApplicationContext().HowToPlay.class);
}
});
LogOut_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
Settings_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent open_Settings = new Intent(getApplicationContext(), Settings.class);
startActivity(open_Settings);
}
});
}
}
getSupportActionBar().hide(); is what's causing the error. You have added it before
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
So it's trying to execute it before the activity is initialised.
Add it after the above 2 lines and it should work.

[Android App]Screen flickers when I switch dark mode

I'm currently creating my own application with Android Studio. In this app, I want to create a switch, that changes to dark mode and back.
In the MainActivity.java I'm using the following code
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Switch;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
public class MainActivity extends AppCompatActivity {
private Button button;
private Switch aSwitch;
public static final String MyPREFERENCES = "nightModePrefs";
public static final String KEY_ISNIGHTMODE = "isNightMode";
SharedPreferences sharedpreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button feed = findViewById(R.id.feed);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
aSwitch = findViewById(R.id.day_night);
checkNightModeActivated();
aSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> {
if (isChecked) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
saveNightModeState(true);
recreate();
}else{
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
saveNightModeState(true);
recreate();
}
});
feed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, Newsfeed.class));
}
});
}
private void saveNightModeState(boolean nightMode) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean(KEY_ISNIGHTMODE, nightMode);
editor.apply();
}
private void checkNightModeActivated() {
if(sharedpreferences.getBoolean(KEY_ISNIGHTMODE, false)) {
aSwitch.setChecked(true);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
}else{
aSwitch.setChecked(false);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
}
}
The problem is, that the switch will change the mode to dark when I've started the app. But then, the app beginns to flicker and does not longer responds.
Can soneone please tell me, what I'm doing wrong?
Kind regards
Kai
I've found a solution for my problem.
private Switch day_night;
day_night=findViewById(R.id.day_night);
day_night.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
else {
getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_YES);
}
}
});

How to use 2 public classes, protected void on creat functions in the same fragments?

How to put more than one class,overview,void in MainActivity java of Android Studio? I need to have both the button and a code to make the map of google have some restricions in the same page. What names of the classes should be changed for it to work. The codes work when put independently but not together.How to make them work good together?
package com.example.maps;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.MarkerOptions;
public class FirstFragment extends AppCompatActivity {
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFoodFragment();
}
});
}
public void openFoodFragment(){
Intent intent = new Intent(this, FoodFragment.class);
startActivity(intent);
}
}
public class MainACTIVITY extends FragmentActivity implements OnMapReadyCallback {
GoogleMap mapAPI;
SupportMapFragment mapFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mapFragment =(SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.mapAPI);
mapFragment.getMapAsync(this);
}
public void openFoodFragment(){
Intent intent = new Intent(this, FoodFragment.class);
startActivity(intent);
}
#Override
public void onMapReady(GoogleMap googleMap){
mapAPI = googleMap ;
LatLng one = new LatLng(-21.754812, -48.219451);
LatLng two = new LatLng(-21.787443, -48.113332);
LatLngBounds.Builder builder = new LatLngBounds.Builder();
//add them to builder
builder.include(one);
builder.include(two);
LatLngBounds bounds = builder.build();
//get width and height to current display screen
int width = getResources().getDisplayMetrics().widthPixels;
int height = getResources().getDisplayMetrics().heightPixels;
int padding = (int) (width * 0.20);
mapAPI.setLatLngBoundsForCameraTarget(bounds);
mapAPI.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, width, height, padding));
//set zoom to level to current so that you won't be able to zoom out viz. move outside bounds
mapAPI.setMinZoomPreference(mapAPI.getCameraPosition().zoom);
LatLng Kampai = new LatLng(-21.780985, -48.186859);
mapAPI.addMarker(new MarkerOptions().position(Kampai).title("Kampai"));
mapAPI.moveCamera(CameraUpdateFactory.newLatLng(Kampai));
}
}
Yes the can be in the same file but you have your mainACTIVITY inside your FirstFragment which cannot happen you need to remove the bottom most bracket and place it right above the start of your mainACTIVITY class, your FirstFragment's brackets need to close before you paste another class into the file.

AlertDialog inside checkbox in Android Studio

I am new to Android Studio. I want to create an AlertDialog, which contains a simple TextView, that appears at every lap of time (e.g. 5 min) inside the checkbox, so if the checkbox is clicked, the AlertDialog appears every 5 min. If it's not clicked, then nothing appears. Help me please.
After a bit of experimentation, I was able to create something similar to what I think you want. This is the small project I created, but you can take just the parts of the code that are needed for your project.
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity
{
TextView input;
long startTime = 0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
final LinearLayout ll = new LinearLayout(this);
setContentView(ll);
CheckBox cb = new CheckBox(getApplicationContext());
cb.setText("Checkbox");
ll.addView(cb);
cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if (isChecked)
{
startTime = System.currentTimeMillis();
timerHandler.postDelayed(timerRunnable, 0);
}
else
{
timerHandler.removeCallbacks(timerRunnable);
}
}
});
}
public void showDialog()
{
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Title");
alert.setMessage("Message");
input = new TextView (this);
alert.setView(input);
input.setText("Text");
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton)
{
// do stuff when Ok is clicked
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton)
{
// do stuff when Cancel is clicked
}
});
alert.show();
}
Handler timerHandler = new Handler();
Runnable timerRunnable = new Runnable()
{
#Override
public void run()
{
showDialog();
// Edit the second parameter to whatever time you want in milliseconds
timerHandler.postDelayed(this, 300_000);
}
};
#Override
public void onPause()
{
super.onPause();
timerHandler.removeCallbacks(timerRunnable);
}
}
Hopefully, this helps.

Resources