how to override onBackPressed inside an if statement? - android

My aim is to override the code of my onBackPressed method..
I have overridden the onBackPressed inside my activity
#Override
public void onBackPressed() {
this.finish();
}
The code below is inside onCreate(), how can i override the onBackPressed to do something like go to another intent instead,
if(mode.equals("edit")){
//onBackPressed();
}
EDIT!!
sorry for unclear question,
What i want to know is, is there a way to override the method inside to onCreate method's if statement?

Just do this:
#Override
public void onBackPressed() {
// Check your mode in onBackPressed
if(mode.equals("edit")){
// Launch the intent
Intent editIntent = new Intent(MyActivity.this, EditActivity.class);
startActivity(editIntent);
// else call to the super class method, for default behavior
}else{
super.onBackPressed();
}
}
There is nothing stopping you from making an onBackPressed call from any method in your Activity class:
public class MainActivity extends AppCompatActivity {
private int editMode = 1;
private String mode = "edit";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// This is totally legal to do
if(editMode == 1){
onBackPressed();
}
}
}

Since the method onBackPressed() is a public method You can do this:
inside onCreate(){
if(mode.equals("edit")){
onBackPressed();
}
else
Log.d("dj","something else");
}
in onBackPressed, i did this for testing:
#Override
public void onBackPressed() {
Log.d("dj", "Yeah! on back pressed");
//super.onBackPressed();
}

I think you want to perform some operation based on the calling location,
for that I think you can follow the given below method:
onCreate(){
if(Edit){
performOperation(EDIT_OPERATION);
}
if(View){
performOperation(VIEW_OPERATION);
}
}
onBackPressed(){
performOperation(BACKP_RESSED);
}
performOperation(int operationType){
/*
* do operation
*/
}
I hope this is what you want

Related

How to keep intent for second activity?

I have a MainActivity with some cards which have different names. onClick, the title is passed as an intent via the adapter to the secondActivity and displayed as the header. From there, I can go to other activities. If I come back from one of these other activities (via the back button created by establishing second activity as the parent activity) the header is gone. How do I keep the header that was originally passed on as an intent or should I go about this completely different?
I have tried using onResume() and onStart() in the secondActivity to reassign the intent from a global variable.
The adapter class, where the card onClick method is written:
#Override
public void onBindViewHolder(final TripHolder tripHolder, final int position) {
Trip trip = trips.get(position);
tripHolder.setDetails(trip);
tripHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, SecondActivity.class);
TextView card_title = v.findViewById(R.id.TripNamecl);
intent.putExtra("card_title", card_title.getText().toString());
context.startActivity(intent);
}
});
}
The secondActivity where the header should be displayed:
public class SecondActivity extends AppCompatActivity {
String name;
TextView header;
static final String STATE_HEADER = "header";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
name = getIntent().getStringExtra("card_title");
header = findViewById(R.id.TripsHeader);
header.setText(name);
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putString(STATE_HEADER, name);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
name = savedInstanceState.getString(STATE_HEADER);
header.setText(name);
}
public void launchMapsActivity(View view) {
Uri gmmIntentUri = Uri.parse("geo:48.8566°,2.3522");
Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
if (mapIntent.resolveActivity(getPackageManager()) != null) {
startActivity(mapIntent);
}
}
public void launchTravelActivity(View view) {
Intent intent = new Intent(this, TravelActivity.class);
startActivity(intent);
}
public void launchPlansActivity(View view) {
Intent intent = new Intent(this, PlansActivity.class);
startActivity(intent);
}
}
SOLUTION:
The solution was to put android:launchMode="singleTop" into the manifest file for the secondactivity. It's described in more detail here: How can I return to a parent activity correctly?
In order to do it you should override onSavedInstanceState in your SecondActivity.
You can use something like that, obv adapt it to your needs:
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
//here you can save your variables
savedInstanceState.putString("myHeader", name);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
//here you can retrieve your variables
name = savedInstanceState.getString("myHeader");
}
Let me know if this worked! good luck
remove header.setText(name); from onResume and onStart methods
If you want to save data in first activity between lifecicle method calls you have to save your data in Bundle object.
Override method onSaveInstanceState(Bundle bundle) of your activity:
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("AStringKey", variableData);
outState.putString("AStringKey2", variableData2);
}
And also override Activity method onRestoreInstanceState(Bundle savedInstanceState):
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState){
super.onRestoreInstanceState(savedInstanceState);
variableData = savedInstanceState.getInt("AStringKey");
variableData2 = savedInstanceState.getString("AStringKey2");
setYourHeaderMethodExample(variableData2)
}
When coming back from third activity to second activity onStart() and onResume() method call executes. Try not using onStart() and onResume() for setting the header and use onCreate method for setting the header.
onCreate() method executes only once in its lifetime, but onStart() and onResume() will execute whenever the activity comes to screen. So when coming back from third activity we don't have any values in the intent.
In your second activity's onCreate method add:
getSupportActionBar().setHomeButtonEnabled(true);
and override the onOptionsItemSelected() method in the class and add the following code:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
You don't need to override the onStart() and onResume() methods.

Disable a button when an event occure in main activity

I have two activities named Main activity and Second Activity. Main activity has an event handler. I need to disable a button in second activity when an event occurs.
Main activity
public void myEventListener(int eventID){
switch (eventID) {
case : 0
// disable button of second activity here
break;
}
}
This is an easy one.
Use SharedPreference of changing data(boolean maybe) in MainAcitivity
Use SharedPreference.OnSharedPreferenceChangeListener in SecondActivity for listening to that specific data and changing button state at runtime in.
MainActivity.java
public class MainActivity extends AppCompatActivity {
SharedPreferences.Editor editor;
public void myEventListener(int eventID){
switch (eventID) {
case 0:
editor = getSharedPreferences("pref",MODE_PRIVATE).edit();
editor.putBoolean("event",true);
break;
}
}
}
SecondActivity
public class SecondActivity extends AppCompatActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
#Override
protected void onStart() {
super.onStart();
sharedPreferences=getSharedPreferences("pref",MODE_PRIVATE);
sharedPreferences.registerOnSharedPreferenceChangeListener(this);
}
#Override
protected void onStop() {
super.onStop();
sharedPreferences.unregisterOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if(key.equals("event") && sharedPreferences.getBoolean(key,false))
{
//add your code to disable your button or any action you want
}
}
}
It's very simple to disable a button. Follow the below steps to achieve your problem.
Define a global boolean value as "false"
In onClickEvent override, the boolean value as "true".
Then check with the boolean value as follows
private boolean isClicked = false;
if(isClicked){
button.disabled(true);
} else {
button.disabled(false);
}
Please let me know if you have any issues while applying.
In you First Activity make Boolean static variable.
Example:
FirstActivity
create a Boolean static global variable
public static Boolean clicked = false;
onFirstActivity if Event occurs.
event occurred => clicked = true; otherwise it is false
SecondActivity
in second activity get the value to static boolean from FirstActivity
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (FirstActivity.clicked){
//Do Nothing
}else{
//Perform action
}
}
});
first make reference of second activity and set button visibility GONE or INVISIBLE It's Work
SeconActivity sa; //reference of second activity
public void myEventListener(int eventID){
switch (eventID) {
case : 0
sa.btnofsecondactivity.setVisibilty(View.GONE);
break;
}
}
You can go with LocalBroadCastManager.
in MainActivity wherever you want to trigger the method
LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent("event-occured"));
in SecondActivity register the LocalBroadcastManager and receive it.
public class SecondActivity extends AppCompatActivity {
private BroadcastReceiver mainActivityReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
mainActivityReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// do whatever you want to do
Log.d("TAG", "broadcast received");
}
};
LocalBroadcastManager.getInstance(this).registerReceiver(mainActivityReceiver, new IntentFilter("main-activity-initialized"));
}
#Override
protected void onDestroy() {
super.onDestroy();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mainActivityReceiver);
}
Don't forget to unregister the listener in SecondActivity's onDestroy method. Taken reference from here.

Android implementing onBackPress on Fragment cause of disable exit from application

In my application i have some fragment and i can exit from application by click on back on phone without problem, but when i implementing onBackPress on that i can't exit from application
My code:
#Override
public void onResume() {
super.onResume();
if (getView() == null) {
return;
}
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
if (slider_call_phones.isOpened()) {
slider_call_phones.closeLayer(true);
}
return true;
}
return false;
}
});
}
I want to handle onBackPressed on fragment not Activities
Here's how I do it,
create an interface that would receive onBackPressed() in any class
that implements it and would return true if it's handling the method or false otherwise. This would make sure that your app would exit when your return false.
create a stack of these interfaces in your Activity, then add any of such interfaces to it.
override onBackPressed() in your activity, then anytime it's called, get a listener from the stack and call its own onBackPressed() if it returns true. If it returns false, then it's not handling onBackPressed() so Activity can take over and remove fragment or exit the application.
Here's a sample implementation.
In your Activity
public class MyActivity extends Activity {
//a stack of OnBackPressedListeners, stack one when you want it to receive onBackPressed() from
//this activity.
//PS used stack so that by LIFO, the last listener would be the first to be called.
private Stack<OnBackPressedListener> onBackPressedListeners = new Stack<>();
#Override
public void onBackPressed() {
if (!onBackPressedListeners.isEmpty()) {
if (onBackPressedListeners.peek().onBackPressed()) //if interface is handling onBackPressed(), return. Otherwise super would be called below.
return;
}
//if no listeners, then do super. This would ensure natural behaviour such as closing the app or popping a fragment when no listeners are using onBackPressed()
super.onBackPressed();
}
//listener interface
public static interface OnBackPressedListener {
/**
* #return true if you're handling onBackPressed, false otherwise to let super.onBackPressed() take over
*/
public boolean onBackPressed();
}
public void addOnBackPressedListener(OnBackPressedListener listener) {
onBackPressedListeners.add(listener);
}
public void removeOnBackPressedListener(OnBackPressedListener listener) {
onBackPressedListeners.remove(listener);
}
}
In your Fragment
//implement OnBackPressedListener in your fragment.
public class MyFragment extends Fragment implements OnBackPressedListener {
//find somewhere to add the listener to your Activity, most likely in onCreateView(...)
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
...
((MyActivity)getActivity()).addOnBackPressedListener(this);
...
return view;
}
//overide onBackPressed(), then return true if you're handling the onBackPressed(), false otherwise.
#Override
public boolean onBackPressed() {
if (slider_call_phones.isOpened()) {
slider_call_phones.closeLayer(true);
return true;
}
return false;
}
//lastly remember to remove the listener when your fragment is destroyed, so that it stops receiving callbacks,
//if you don't do this, you might get a NullPointerException.
#Override
public void onDestroy() {
super.onDestroy();
((MyActivity)getActivity()).removeOnBackPressedListener(this);
}
}
I mostly use a single Activity and a whole lot of Fragment's in my Android apps, this is exactly how I solve such problems you are having, for example closing a drawer in a Fragment if its open when the back button is pressed, or exiting the application if it's closed.
You should call onBackPressed() in the following manner in order to exit from the app:
public void onBackPressed(){
finishAffinity();
}

How to properly do a global onBackPressed() override?

I want to override onBackPressed() and I have this code in all my activities
int backpress=0;
public void onBackPressed(){
backpress = (backpress + 1);
if (backpress>1) {
this.finish();
}else{
Toast.makeText(getApplicationContext(), R.string.finish, Toast.LENGTH_SHORT).show();
}
}
But I only want to override the function one time if it's possible. Whats the proper way?
Create a Base activity and define this method there. Like
public class BaseActivity extends Activity {
private int backpress = 0;
#Override
public void onBackPressed() {
backpress = (backpress + 1);
if (backpress > 1) {
this.finish();
} else {
Toast.makeText(getApplicationContext(), R.string.finish,
Toast.LENGTH_SHORT).show();
}
}
}
And extend this BaseActivity instead of Activity ino your activity. Like
// Just override BaseActivity instead of Activity class.
public class MyActivity extends BaseActivity {
// Do you task
}

How to use a method of activity1 for activity1, calling this method from activity2?

I have a method in MainActivity. java
public void spinset(String[] a)
{
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, a);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin_main = (Spinner) findViewById(R.id.spinner);
spin_main.setAdapter(adapter);
spin_main.setPrompt("Член семьи");
spin_main.setSelection(0);
}
I need to call this method on onCLick event in Dialog_mem.java
...
MainActivity ma=new MainActivity();
...
public void onClick(View v) {
switch(v.getId())
{ case R.id.mem_btnOK:
datasource.open();
datasource.putrecord("Mem_Name", memname.getText().toString());
datasource.insertrecord("Members");
date=datasource.curspinner("Members", "Mem_Name");
datasource.close();
//HERE
ma.spinset(date);
default:
dismiss();}
}
But I need this method to work for my MainActivity, not for Dialog_mem.
Or is there a way to know in MainActivity that the button in Dialog_mem was clicked? Or Maybe you know another way to do this?
you can implement your own interfaces to give call back to previous activity this can be done as shown below
public interface myListener {
public void doMyWork(boolean success, Object message);
}
make your mainActivity implement this listener and override unimplemented methods:
public class MainActivity extends Activity implements myListener{
onCreate(Bundle savedInstanceState){
Dialog_mem dm = new Dialog_mem();
dm.setmyListener(this);
}
public void doMyWork(boolean success,Object message){
// your code here
// call spinset from here
}
}
create the setmyListener() method in Dialog_mem
public class Dialog_mem {
myListener listener;
public void setmyListener(myListener listener){
this.listener = listener
}
}
make a callback from Dialog_mem to MainActivity by calling this method when you want to do your work in spinset method.
public void onClick(View v) {
switch(v.getId())
{ case R.id.mem_btnOK:
datasource.open();
datasource.putrecord("Mem_Name", memname.getText().toString());
datasource.insertrecord("Members");
date=datasource.curspinner("Members", "Mem_Name");
datasource.close();
//HERE
listener.doMyWork(success,message);
default:
dismiss();}
}
start Dialog_mem by calling startActivityForResult and in case of ok send a result code.
In your MainActivity onActivityResult will be called when you come back from Dialog_mem here you can check the result code and call your function.

Categories

Resources