How to properly do a global onBackPressed() override? - android

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
}

Related

How to implement an interface in Fragment from a non parent Activity?

I have not found a clear solution anywhere on stack for this.
Here's my basic set up
public class Activity1 extends AppCompatActivity
{
private OnAttributesUpdatedListener onAttributesUpdatedListener;
public interface OnAttributesUpdatedListener
{
public void onAttributesUpdated();
}
public void setTargetFragment(Fragment fragment)
{
this.onAttributesUpdatedListener = (OnAttributesUpdatedListener) fragment;
}
private void whenFinishedSomethingCallback()
{
onAttributesUpdatedListener.onAttributesUpdated();
}
}
public class Fragment1 extends Fragment implements Activity1.OnAttributesUpdatedListener
{
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view) {
if(rivalButtonClick == 0)
{
Activity1 activity1 = new Activity1();
activity1.setTargetFragment(Fragment1.this);
startActivity(new Intent(getActivity(), activity1.getClass()));
}
}
});
}
I get a null pointer exception and crashes on : onAttributesUpdatedListener.onAttributesUpdated(); because for some reason my listener never gets set properly. What's the proper way to do this?
You need to set the listener at start of the fragment onCreatView() or in onActivityCreated() only if the Desired Activity is a parent Activity of that particular fragment. Below is an example .
public class Activity1 extends AppCompatActivity {
private OnAttributesUpdatedListener onAttributesUpdatedListener;
public interface OnAttributesUpdatedListener {
public void onAttributesUpdated();
}
public void setListener(OnAttributesUpdatedListener onAttributesUpdatedListener) {
this.onAttributesUpdatedListener = onAttributesUpdatedListener;
}
private void whenFinishedSomethingCallback() {
if(onAttributesUpdatedListener!=null)
onAttributesUpdatedListener.onAttributesUpdated();
}
}
public class Fragment1 extends Fragment implements Activity1.OnAttributesUpdatedListener
{
#Override
public void onAttributesUpdated() {
// Do your stuff here
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
((Activity1)getActivity()).setListener(this);
}
}
Read about fragment Life cycle to make use of getActivity(). also remove the listener when fragment is destroyed .
Use LocalBroadcastManager for communicating between in case the Fragment exists in other Activity.
At first create an Interface like this:
public interface Listener{
void doSomething() }
Then implement this interface in your activity.
And also add
Listener listener
In your fragment
And in onAttach method in fragment use this
listener=(Listener)activity
Then call listener whenever you need .

onBackPressed with extend Fragment

I have an Activity with android studio which extends to AppCompatActivity:
public class Act_1 extends AppCompatActivity {
And the onBackPressed event works great.
#Override
public void onBackPressed() {
}
This same event I wish to use in an activity that extends to Fragment:
public class Act_2 extends Fragment{
But when I write the code, there is an error message about #Override that says:
"Method does not override method from its superclass"
Is there a solution to this problem?
Thanks
The Act_2 is not an Activity, is a Fragment and the onBackPressed() method is an Activity's method, so you cannot override it in your Fragment. To fix this issue change your Act_2 to extend AppCompatActivity or Activity.
onBackPressed is under Activity not Fragment. What you can do is override the method in Activity.
Like this::
android.support.v4.app.FragmentManager fragmentManager =
getSupportFragmentManager();
int count = fragmentManager.getBackStackEntryCount();
if (count > 0) {
getSupportFragmentManager().popBackStack();
} else {
if (this instanceof HomeActivity) {
//additional code
} else {
finish();
}
}

Android fragment lifecycle issue with actionbar

I want to realize the navigation of the fragments using the following code:
public abstract class BaseFragment extends Fragment {
private static String TAG = "BaseFragment";
private BaseFragmentActions baseFragmentActions;
#Override
public void onAttach(Context context) {
super.onAttach(context);
Activity activity = null;
if (context instanceof Activity){
activity = (Activity) context;
}
Log.i(TAG, "onAttach = ");
try {
baseFragmentActions = (BaseFragmentActions)activity;
} catch (ClassCastException e) {
}
Log.i("onAttach",""+(getBackStackCount()!=0));
baseFragmentActions.resetToolbarNavigation(getBackStackCount()!=0);
}
#Override
public void onDetach() {
super.onDetach();
Log.i("BaseFragment", "onDestroy = " + (getBackStackCount() - 1));
baseFragmentActions.resetToolbarNavigation((getBackStackCount() - 1) != 0);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
private int getBackStackCount() {
int b = getActivity().getSupportFragmentManager().getBackStackEntryCount();
Log.i("getBackStackEntryCount", "====== "+b);
return b;
}
public interface BaseFragmentActions {
public void resetToolbarNavigation(boolean backNavigationEnabled);
}
}
All my fragments extend this Base Activity. And inside my main activity i implement BaseFragmentActions, and implemented this method:
#Override
public void resetToolbarNavigation(boolean backNavigationEnabled) {
Log.i("BaseActivity", "reset " + backNavigationEnabled);
getSupportActionBar().setDisplayHomeAsUpEnabled(backNavigationEnabled);
if (backNavigationEnabled) {
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.i("resetToolbarNavigation", "setNavigationOnClickListener");
onBackPressed();
}
});
} else {
initNavigation();
syncState();
}
}
Everything works fine but when I change the screen orientation we obtain error that getSupportActionBar = null.
This is because of what I call going to attach. How can I fix this error? I tried to make checking whether getSupportActionBar is not zero. I'm not getting an error, but "up" Arrow replaced hamburger...
Advise what you can do in this case. Also share links to navigate the implementation of such fragments. Sorry if something wrong written, or I made a grammatical error)).
Hi sorry for the delay in the answer, the problem you're having is because when onAttach is called the getSupportActionBar() is not set yet, instead you need to make sure the Activity is already created when interacting with Activity components, so just put your call inside the onActivityCreated method of your Fragment like this:
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
baseFragmentActions.resetToolbarNavigation(getBackStackCount()!=0);
}

how to override onBackPressed inside an if statement?

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

How to start a method in a mainactivty using receiver?

I'm using BOOT_UP_COMPLETE BroadcastReceiver in my program.
I need to start a method from my MainActivity (I found only to start an Activity or Service from a BroadcastReceiver).
In my code below, I need to start InitMorning method.
How to code it?
public class MainActivity extends Activity {
//private Context mContext;
public static int isMasterThreadRunning = 0;
Intent intent = null;
private boolean isActivityExitInProgress = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.e("MainActivity : onCreate : Enter");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(isMasterThreadRunning == 1)
{
SetButtonTitle("Stop Monitoring");
}
else
{
isMasterThreadRunning = 0;
}
Log.e("MainActivity : onCreate : Exit");
}
/** Called when the user clicks the Send button */
public void startMonitoring(View view) {
if(isActivityExitInProgress == false)
{
if(isMasterThreadRunning == 0) {
InitMonitoring();
}
else if(isMasterThreadRunning == 1) {
stopMonitoring();
isActivityExitInProgress = false;
}
}
}
public void SetButtonTitle(String buttonTitle)
{
Button start_monitoring_button = (Button)findViewById(R.id.button_start_monitoring);
start_monitoring_button.setText(buttonTitle);
if(buttonTitle == "Stop Monitoring")
{
start_monitoring_button.setEnabled(false);
}
}
public void InitMonitoring()
{
Log.e("MainActivity : startMonitoring : Going to start master thread : Enter");
MasterThreadService.mContext = getBaseContext();
SetButtonTitle("Stop Monitoring");
intent = new Intent(this, MasterThreadService.class);
startService(intent);
isMasterThreadRunning = 1;
this.moveTaskToBack(true);
Log.e("MainActivity : startMonitoring : Going to start master thread : Exit");
}
public void stopMonitoring()
{
Log.e("MainActivity : stopMonitoring : Enter");
isActivityExitInProgress = true;
SetButtonTitle("Start Monitoring");
Log.e("MainActivity : startMonitoring : Calling exitFromApp");
// Make a call to exit and clean everything : exitFromApp
MasterThreadService.exitFromApp();
if(intent == null)
{
Log.e("MainActivity : stopMonitoring : NULL POINTER ACCESS NEED TO INVESTIGATE");
}
else
{
stopService(intent);
}
isMasterThreadRunning = 0;
Log.e("MainActivity : stopMonitoring : Exit");
}
#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;
}
}
As I can read on it, you need to attach your Activity in your BroadcastReceiver.
You must to create your BroadcastReceiver dynamically. Then, use setMainActivityHandler(MainActivity) method in your Activity when you define and call the BroadcastReceiver and attach your Activity inside the receiver class with setMainActivityHandler(MainActivity mainactivity) method. Finally, call your Activity method with the following: mainactivity.methodInActivity();. This should do the trick.
You can find how do this on Call an activity method from a BroadcastReceiver class and you have another example on Call activity method from broadcast receiver.
Hope this helps.
Try making a static reference. Change
public void InitMonitoring()
To
public static void InitMonitoring()
Then call the method from your service like:
MainActivity.InitMonitoring();
This is how I would do it. Don't know if it's the best way though.

Categories

Resources