onBackPressed() doesn't work for me - java

I have a problem, which is also discussed here:
onBackPressed never gets called
I'm trying to cancel a CountDownTimer when pressing the native back button from an android phone. So I would like to overrite the onBackPressed method, to cancel the timer and return to another activity, but only once. (to return to the main activity, like a home button).
This is a part of the code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
if (getResources().getConfiguration().orientation== Configuration.ORIENTATION_LANDSCAPE){
ImageView und1=(ImageView)findViewById(R.id.undita1);
ViewGroup.LayoutParams params = (ViewGroup.LayoutParams) und1.getLayoutParams();
params.height=150;
und1.setLayoutParams(params);
ImageView und2=(ImageView)findViewById(R.id.undita2);
ViewGroup.LayoutParams params2 = (ViewGroup.LayoutParams) und2.getLayoutParams();
params2.height=150;
und2.setLayoutParams(params2);
ImageView und3=(ImageView)findViewById(R.id.undita3);
ViewGroup.LayoutParams params3 = (ViewGroup.LayoutParams) und3.getLayoutParams();
params3.height=150;
und3.setLayoutParams(params3);
}
mProgressBar=(ProgressBar)findViewById(R.id.progressBar);
mProgressBar.setProgress(0);
mCountDownTimer=new CountDownTimer(90000,1000) {
int i=0;
#Override
public void onTick(long millisUntilFinished) {
Log.v("Log_tag", "Tick of Progress" + i + millisUntilFinished);
i++;
mProgressBar.setProgress(i); }
#Override
public void onFinish() {
i++;
mProgressBar.setProgress(i);
Intent in = new Intent(getApplicationContext(), MyActivity2.class);
startActivity(in);
}
};
mCountDownTimer.start();
android.view.Display display = ((android.view.WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
Bundle b;
b = getIntent().getExtras();
nivel= b.getInt("level");
TextView niv=(TextView) findViewById(R.id.Nivel);
niv.setText("Level: "+ nivel);
generare_3_diferente(nivel);}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.my, menu);
return true;}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) { //Back key pressed
mCountDownTimer.cancel();
Intent in = new Intent(getApplicationContext(), MyActivity2.class);
startActivity(in);
mCountDownTimer.cancel();
return true;
}else{
return super.onKeyDown(keyCode, event);
}
}
#Override
public void onBackPressed(){
mCountDownTimer.cancel();
Intent in = new Intent(this, MyActivity2.class);
startActivity(in);
super.onBackPressed();
}
}

the onBackPressed should be in the main activity class
Also try to specify the parent and child activities in the manifest file of the app e.g
android:parentActivityName
and try to use something like this and rebuild your App
#Override
public void onBackPressed() {
super.onBackPressed();
i = new Intent(CurrentActivity.this, NextActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
}
if it still doesn't work try to make a new application and import your files

Related

How to implement the saving of night mode in multiple activities?

I tried using an Inflater to check whether the Switch responsible for activating and deactivating night mode in my Settings activity is enabled or not. The MainActivity doesn't remember the night mode state after relaunching the app.
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private Switch night_mode_sw;
public static final String MyPREFERENCES = "nightModePrefs";
public static final String KEY_ISNIGHTMODE = "isNightMMode";
SharedPreferences sharedpreferences;
#SuppressLint("SetTextI18n")
#Override
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.getOverflowIcon().setColorFilter(16777215, PorterDuff.Mode.SRC_ATOP);
setSupportActionBar(toolbar);
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.activity_settings, null);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
night_mode_sw = findViewById(R.id.night_mode);
checkNightModeActivated();
view.findViewById(R.id.night_mode);
night_mode_sw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if (isChecked) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
saveNightModeState(true);
recreate();
}
else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
saveNightModeState(false);
recreate();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
private void saveNightModeState(boolean nightMode) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean(KEY_ISNIGHTMODE, nightMode);
editor.apply();
}
public void checkNightModeActivated() {
if (sharedpreferences.getBoolean(KEY_ISNIGHTMODE,false)) {
night_mode_sw.setChecked(true);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
}
else{
night_mode_sw.setChecked(false);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.settings) {
Intent myintent = new Intent(MainActivity.this, Settings.class);
startActivity(myintent);
return false;
}
if (id == R.id.aboutapp) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("About this app")
.setCancelable(false)
.setNeutralButton("GOT IT", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
})
.setTitle("About this app")
.setMessage("awsd");
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
return super.onOptionsItemSelected(item);
}
}
Settings.java:
public class Settings extends AppCompatActivity {
private Switch night_mode_sw;
public static final String MyPREFERENCES = "nightModePrefs";
public static final String KEY_ISNIGHTMODE = "isNightMMode";
SharedPreferences sharedpreferences;
#Override
protected void onCreate(final Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
final Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.getOverflowIcon().setColorFilter(16777215, PorterDuff.Mode.SRC_ATOP);
setSupportActionBar(toolbar);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
night_mode_sw = findViewById(R.id.night_mode);
checkNightModeActivated();
night_mode_sw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if (isChecked) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
saveNightModeState(true);
recreate();
}
else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
saveNightModeState(false);
recreate();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
private void saveNightModeState(boolean nightMode) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean(KEY_ISNIGHTMODE, nightMode);
editor.apply();
}
public void checkNightModeActivated() {
if (sharedpreferences.getBoolean(KEY_ISNIGHTMODE,false)) {
night_mode_sw.setChecked(true);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
}
else{
night_mode_sw.setChecked(false);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu1,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.calculator) {
Intent myintent = new Intent (Settings.this, MainActivity.class);
startActivity(myintent);
return false;
}
if (id == R.id.aboutapp) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("About this app")
.setCancelable(false)
.setNeutralButton("GOT IT", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
})
.setTitle("About this app")
.setMessage("awsd");
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
return super.onOptionsItemSelected(item);
}
}
I'm not sure what the reason for this is.

Creating a reusable class

I have an application running in Android, i wanna create a Menu and repeat in some activities, that menu calls Intent for open others activities.
How can i do this?
Think maybe i can create a class, but i getting errors. Where can i create a class for that? Inside onCreate method or not?
And how can i reuse the menu in another activity?
Thanks!!
Here is my menu code:
menu_button = (Button) findViewById(R.id.menu_button);
menu_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu popupMenu = new PopupMenu(MainActivity.this, menu_button);
popupMenu.getMenuInflater().inflate(R.menu.popup_menu, popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.one:
Intent vista = new Intent(MainActivity.this, openCamera.class);
MainActivity.this.startActivity(vista);
}
return true;
/*
Toast.makeText(MainActivity.this, "" + item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
*/
}
});
popupMenu.show();
}
});
If the menu is always the same and you want to reuse it in more than one activity, you just define it like this:
public class TestMenu {
private final PopupMenu popupMenu;
public TestMenu(final Activity activity, View anchor) {
popupMenu = new PopupMenu(activity, anchor);
popupMenu.getMenuInflater().inflate(R.menu.popup_menu, popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.one:
Intent vista = new Intent(activity, openCamera.class);
activity.startActivity(vista);
}
return true;
}
});
}
public void show() {
popupMenu.show();
}
}
And then use it in your activity like this:
public class TestActivity extends Activity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button menu_button = (Button) findViewById(R.id.menu_button);
TestMenu myMenu = new TestMenu(this, menu_button);
menu_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myMenu.show();
}
});
}
}

onSupportNavigateUp() is not fired anymore after I override onOptionsItemSelected(MenuItem item)

(Sorry for changing the whole question as I found the actual problem after troubleshooting)I have my activity as followed:
public class MyAppActivity extends AppCompatActivity{
#Override
protected void onCreate(...)
{
//...
this.setContentView(contentViewResID);
Toolbar toolbar = (Toolbar) this.findViewById(toolbarResID);
this.setSupportActionBar(toolbar);
this.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
protected void onPause() {...}
#Override
protected void onResume() {...}
#Override
public boolean onSupportNavigateUp() {
Log.d("onSupportNavigateUp()", "pressed");
finish();
return super.onSupportNavigateUp();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {...}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {...}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item == menuAddFood) {
Intent intent = new Intent(this, ActivityAddFood.class);
this.startActivity(intent);
}
if (item == menuSettings){
Intent intent = new Intent(this, ActivitySetting.class);
this.startActivity(intent);
}
if(item == menuUsername){
}
return true;
}
}
EDIT:
After my troubleshooting, I found out after override the onOptionsItemSelected(), onSupportNavigateUp() no longer fired anymore when I pressed the top left BACK / UP / HOME button. I want to do finish() inside onSupportNavigateUp() How to solve this?
You have to override the method in your current Activity and call the super:
public class ActivityExample extends MyAppActivity {
Context context = this;
AppCompatActivity activity = this;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.createMyView(R.layout.activity_log_in, R.id.toolbar);
// ...
}
#Override
public boolean onSupportNavigateUp() {
finish();
return true;
}
}
Also, if you override onOptionsItemSelected, then onSupportNavigateUp will not be called.
//DONT OVERRIDE THIS METHOD
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
break;
}
return true;
}

dont know where to put this code in my java file

I'm confused where to put this code so that the user will not go to the other page until he selected a radiobutton.
This is the code where I don’t know to put:
if(rda.isChecked() == true)
{
butNext.setEnabled(true);
}
if(rdb.isChecked() == true)
{
butNext.setEnabled(true);
}
if(rdc.isChecked() == true)
{
butNext.setEnabled(true);
}
else
{
butNext.setEnabled(false);
}
This is my whole code or MainAct.java:
List<Question> quesList;
int score=0;
int qid=0;
Question currentQ;
TextView txtQuestion;
RadioButton rda, rdb, rdc;
Button butNext;
RadioGroup radioGroup1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_page);
DBase db=new DBase(this);
quesList=db.getAllQuestions();
currentQ=quesList.get(qid);
txtQuestion=(TextView)findViewById(R.id.textView1);
rda=(RadioButton)findViewById(R.id.rda);
rdb=(RadioButton)findViewById(R.id.rdb);
rdc=(RadioButton)findViewById(R.id.rdc);
butNext=(Button)findViewById(R.id.button1);
setQuestionView();
butNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
RadioGroup grp=(RadioGroup)findViewById(R.id.radioGroup1);
RadioButton answer=(RadioButton)findViewById(grp.getCheckedRadioButtonId());
Log.d("yourans", currentQ.getANSWER()+" "+answer.getText());
if(currentQ.getANSWER().equals(answer.getText()))
{
score++;
Log.d("score", "Your score"+score);
}
if(qid<10)
{
currentQ=quesList.get(qid);
setQuestionView();
}
else
{
Intent intent = new Intent(MainAct.this, activity.class);
Bundle b = new Bundle();
b.putInt("score", score); //Your score
intent.putExtras(b); //Put your score to your next Intent
startActivity(intent);
finish();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void setQuestionView()
{
txtQuestion.setText(currentQ.getQUESTION());
rda.setText(currentQ.getOPTA());
rdb.setText(currentQ.getOPTB());
rdc.setText(currentQ.getOPTC());
qid++;
rda.setChecked(false);
rdb.setChecked(false);
rdc.setChecked(false);
//butNext.setEnabled(false);
}
if(rda.isChecked()||rdb.isChecked()||rdc.isChecked()){
RadioGroup grp=(RadioGroup)findViewById(R.id.radioGroup1);
RadioButton answer=(RadioButton)findViewById(grp.getCheckedRadioButtonId());
Log.d("yourans", currentQ.getANSWER()+" "+answer.getText());
if(currentQ.getANSWER().equals(answer.getText()))
{
score++;
Log.d("score", "Your score"+score);
}
if(qid<10)
{
currentQ=quesList.get(qid);
setQuestionView();
}
else
{
Intent intent = new Intent(MainAct.this, activity.class);
Bundle b = new Bundle();
b.putInt("score", score); //Your score
intent.putExtras(b); //Put your score to your next Intent
startActivity(intent);
finish();
}
}
or inOnCheckChanged:
radioGroup1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup arg0, int arg1) {
// TODO Auto-generated method stub
if(rda.isChecked()||rdb.isChecked()||rdc.isChecked()){
butNext.setEnabled(true);
}else{
butNext.setEnabled(false);
}
}
});
You can simply call it OnCheckedChangeListener() method of your RadioGroup.
radioGroup1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup arg0, int arg1) {
// TODO Auto-generated method stub
if(rda.isChecked()||rdb.isChecked()||rdc.isChecked()){
butNext.setEnabled(true);
}else{
butNext.setEnabled(false);
}
}
});
For your query you simply need to start Intent only when this Radio button has been clicked.
For Ex: Use condition check which will insure that your radio box has been checked..
i.e
if( radio_b.ischecked()){
// start Intent over here
}else{
// Toast a message to user to select same
}
I hope this clears your doubt.
As far placing code is concerned then you can place same in onCreate(); Method only. That actually depends upon your need.
Cheers!

How don't kill process after onStop?

Simple code:
public class ZSEEActivity extends TabActivity {
private WebView webview ;
private WebView webviewtwo;
private TabHost mTabHost;
private int a;
protected void onStart() {
super.onStart();
// The activity is about to become visible.
}
protected void onStop() {
super.onStop();
// The activity is about to become visible.
}
protected void onRestart() {
super.onRestart();
}
protected void onDestroy(){
super.onDestroy();
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Activity activity = this;
mTabHost = getTabHost();
mTabHost.addTab(mTabHost.newTabSpec("tab_test1").setIndicator("Zastępstwa").setContent(R.id.tab1));
mTabHost.addTab(mTabHost.newTabSpec("tab_test2").setIndicator("Plan Lekcji").setContent(R.id.tab2));
mTabHost.addTab(mTabHost.newTabSpec("tab_test3").setIndicator("O programie").setContent(R.id.tab3));
webview = (WebView) findViewById(R.id.webView1);
webviewtwo = (WebView) findViewById(R.id.webView2);
final WebSettings webviewtwoSettings = webviewtwo.getSettings();
if (savedInstanceState != null){
webview.restoreState(savedInstanceState.getBundle("stateone"));
webviewtwo.restoreState(savedInstanceState.getBundle("statetwo"));
webviewtwoSettings.setTextSize(TextSize.LARGER);
mTabHost.setCurrentTab(savedInstanceState.getInt("CURRENT_TAB"));
}
else{
webview.loadUrl("http://zsee.bytom.pl/ogloszenia.php");
webviewtwo.loadUrl("http://zsee.bytom.pl/plannew/index.html");
webviewtwoSettings.setTextSize(TextSize.LARGER);
mTabHost.setCurrentTab(0);
}
webview.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
String summary = "<html><body><meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" ><center>Coś się zepsuło :(</center></body></html>";
webview.loadData(summary, "text/html","utf-8");
Toast.makeText(activity, "O nie! " + description, Toast.LENGTH_SHORT).show();
}
});
webviewtwo.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
String summary = "<html><body><meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" ><center>Coś się zepsuło :(</center></body></html>";
webviewtwo.loadData(summary, "text/html","utf-8");
webviewtwoSettings.setTextSize(TextSize.NORMAL);
Toast.makeText(activity, "O nie! " + description, Toast.LENGTH_SHORT).show();
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
protected void onSaveInstanceState(Bundle outState) {
Bundle outStateone = new Bundle();
Bundle outStatetwo = new Bundle();
webview.saveState(outStateone);
webviewtwo.saveState(outStatetwo);
outState.putBundle("stateone", outStateone);
outState.putBundle("statetwo", outStatetwo);
outState.putInt("CURRENT_TAB", mTabHost.getCurrentTab());
}
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.item1:
final AlertDialog alertdialog= new AlertDialog.Builder(this).create();
alertdialog.setTitle("O Programie");
alertdialog.setMessage("Zmiany w 1.0.1: \n-Obsługa planu z dnia 17.10.2011\n-Drobne Poprawki");
alertdialog.setButton("Fajno", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
alertdialog.cancel();
}
});
alertdialog.show();
return true;
case R.id.item2:
finish();
case R.id.item3:
if(mTabHost.getCurrentTab() == 0){
webview.loadUrl("http://zsee.bytom.pl/ogloszenia.php");
}
else if(mTabHost.getCurrentTab() == 1)
{
webviewtwo.loadUrl("http://zsee.bytom.pl/plannew/index.html");
}
default:
return super.onOptionsItemSelected(item);
}
}
}
Now My problem. After i press back button onStop() code is executed and onDestroy. How i can don't kill app ? I wanna this app in background. Now when i press back button and open app, all data is again downloaded and loaded to webview. Soo how make this process work in background ?
Sorry for my haotic english :)
Sierran
Use Android service for doing something in Background rather then Activity.
And use Broadcast receiver to invoke your Activity from service. When something your background work finished.
Android - Service
And if you want to do some little then just override onKeyDown()
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK)
{
// put your stuff here or just block the back button for perticular activity
return true;
}
return super.onKeyDown(keyCode, event);
}
I would recommend using a Service if you want to do something in the background and need it to be running more or less all the time. Check out the Service documentation here:
http://developer.android.com/reference/android/app/Service.html
An alternative in your case would be to create local caches of the websites.

Categories