Checking condition before starting an activity - android

I want to check some condtiton before the main activity starts and based on test result i have to either start a new activity or continue the same activity. How to do this?

you can check it in your OnCreate() method. It is called when your activity start.
onCreate(...){
....
if(want this){
//continue;
}else{
// start new activity
}
}

The default Activity to start is set in the manifest, so a better approach to your problem would be to use fragments. Keep in mind that fragments are faster/lighter, so instead of using Application as a "decision" class to start activities (bad practice), use your main activity. In your onCreate() method, check for your condition and attach the needed fragment.

I am using java annotation to handle this case:
Create the Annoation class
Create CustomContext.java with a startActivity method in it
Create the Interceptor.java
Create a class which implement Interceptor like this (named DemoInterceptor.java here)
Declare a static variable of DemoInterceptor in your activity. and the demo Activity should like this then, start the activity via the custom startActivity in step #2
enjoy and let me know if you have any further question.

#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(startNewActivity) {
// TODO Fire off intent to start new activity
finish(); // Closes the current activity
return;
}
// TODO Code for current activity.
}
startNewActivity is a boolean indicating whether to launch a new activity or not. It should be assigned a value depending on your condition.

Related

Finish the activity using component name in android

I am trying to finish one activity from another.
For that purpose I am having only the component name of that activity.
How can i finish that ?
1.Make your activity A in manifest file: launchMode = "singleInstance"
2.When the user clicks new, do FirstActivity.fa.finish(); and call the new Intent.
3.When the user clicks modify, call the new Intent or simply finish activity B.
FIRST WAY
In your first activity, declare one Activity object like this,
public static Activity fa;
onCreate()
{
fa = this;
}
now use that object in another Activity to finish first-activity like this,
onCreate()
{
FirstActivity.fa.finish();
}
SECOND WAY
While calling your activity FirstActivity which you want to finish as soon as you move on, You can add flag while calling FirstActivity
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
But using this flag the activity will get finished evenif you want it not to. and sometime onBack if you want to show the FirstActivity you will have to call it using intent.
You can do it in very simple way.
First create a static instance of your activity e.g. MainActivity, whom you want to finish like,
public static MainActivity act=MainActivity.this;
and now in another actvity e.g. MainActivity2 just call this line,
MainActivity.act.finish();
Try extending that activity and override the finish method
public class ma extends MainActivity{
#Override
public void finish()
{
super.finish();
}
}
You want to exit application after log out.
that time to user this
i.addCategory(Intent.CATEGORY_HOME);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
or try to another way like
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
moveTaskToBack(true);
finish();
}

How can i make a relation between an image button and a function or activity?

I must write a program with android which can find ssid and show it. My problem is how can i make a relation between an image button in first page and an activity or function in other page.
Buy the way i'm beginner and download the code of searching method because of that i can not recognize which one is the main method or function for pass it to setonclick method that i write for image button in first page?
please answer as soon as you can i need it immediately.
If you are trying to call another activity's method from your existing activity then you should use these steps.
First save the context or instance of the callee activity; for this you can use a class that holds your global data. In this class make the object of this activity.
FirstActivity first = null;
When the callee activity is first created, initialize this instance.
public void setFirstActivity(FirstActivity factivity)
{
first = factivity;
}
And when you do need to call this callee activity's method then access this instance from this global class and with the help of this instance, you will have access to the methods of the callee activity.
public FirstActivity getFirstActivity() {
return first ;
}
use it to get access to the methods or instances of the activity.
Click on the ImageButton, and add the name of the function in the On Click property (Simply the name, like myFunction)
In your code, copy-paste this function and replacemyFunction by the name of the function you chosed
public void myFunction(View v)
{
String ssid = ((EditText)findViewById(R.id.EditTextID)).getText().ToString();
Intent intent = new Intent(this, SecondView.class);
intent.putExtra("SSID_KEY", ssid);
startActivity(intent);
}
And replace SecondView by the class that displays your second page and EditTextName by the ID of your EditText.
In the OnCreate function of your second class, you can get your ssid using the following code
#Override
protected void onCreate(Bundle savedInstanceState) {
String ssid = getIntent().getStringExtra("SSID_KEY");
//Do other work here.
}
Also, on top of the class containing the ImageView, don't forget to add these lines:
import android.view.View;
import android.widget.EditText;

Why do OnCreate should be called only once on the start of Activity?

I would like to know, why OnCreate() is called only once at the start of an activity?
Can we call OnCreate() more than once in the same activity?
If yes, than how can we call it? can anyone give an example?
Thanks a lot!!!
Why would you want to called it again? unless the activity is reconstructed, which is called by system. You cannot call OnCreate manually , it is the same reason why you won't call setContentView() twice. as docs:
onCreate(Bundle) is where you initialize your activity. Most
importantly, here you will usually call setContentView(int) with a
layout resource defining your UI, and using findViewById(int) to
retrieve the widgets in that UI that you need to interact with
programmatically.
Once you finish init your widgets Why would you?
UPDATE
I take some words back, you CAN do this manually but I still don't understand why would this be called. Have you tried Fragments ?
Samplecode:
public class MainActivity extends Activity implements OnClickListener {
private Button btPost;
private Bundle state;
private int counter = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
state = savedInstanceState;
btPost = (Button) findViewById(R.id.btPost);
btPost.setOnClickListener(this);
Toast.makeText(getBaseContext(), " " + counter, Toast.LENGTH_LONG)
.show();
}
#Override
public void onClick(View v) {
counter++;
this.onCreate(state);
}
}
onCreate() method performs basic application startup logic that should happen only once for the entire life of the activity .
Once the onCreate() finishes execution, the system calls the onStart() and onResume() methods in quick succession.
The initialization process consumes lot of resources and to avoid this the activity once created is never completely destroyed but remains non visible to user in background so that once it is bring back to front , reinitialization doesn't happen .
Where you want to call onCreate manually.
Then just do this.
finish();
Intent intent = new Intent(Main.this, Main.class);
startActivity(intent);
finish() calls the current stuff.
And if you are doing somethong getExtra in this activity then do this,
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putString("key",your_variable);
super.onSaveInstanceState(outState);
}
And add this to your onCreate()
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
if(savedInstanceState != null)
{
your_variable= savedInstanceState.getString("key");
}
}
Why would you want to call onCreate more than once? You will be re-creating the activity. If this is what you need for whatever reason then finish the activity and use an intent to create a new instance of that activity. Otherwise, you have two instances of the activity at the same time. Hope that helps but if that doesn't make sense then add more information as to what you want so we have context
OnCreate is basically use to create your activity (UI). If you have already created your activity then you need not create it again as you have already created.
It is basically used to initialize your activity and to create user interface of your activity. Activity is a visual part which you can use again and again so.. I think your problem is not to recreate activity but to reinitialize all components of your activity. For that purpose you can create a method initialize_act() and call it from anywhere...
#OnCreate is only for initial creation, and thus should only be called once.
If you have any processing you wish to complete multiple times you should put it elsewhere, perhaps in the #OnResume method.
Recently i realized that onCreate is called on every screen orientation change (landscape/portrait). You should be aware of this while planning your initialization process.
Recreation can be suppressed in AndroidManifest.xml:
<activity
android:configChanges="keyboardHidden|orientation"
android:name=".testActivity"
android:label="#string/app_name"></activity>

How to go back from second screen to first screen

How to switch layouts? First, I have a class Main where is onCreate (setContentView(R.layout.main);) and then I call, another class with command:
setContentView(secondClass);
In this class, I draw with Canvas and this work just fine. I also create button to go back in first "class" (R.layout.main), but I don't know how to do it.
Now my program is basic a graph shower. In first class you type your function and them second class draw it. But how to go back in first class to type another function. This "back" button or arrow witch every Android phone have, send me out of program not back on insert part.
In secondClass I can't create onCreate method, but I also tried the following and they didn't work:
Intent abc = new Intent("bla.bla.bla.FIRSTCLASS");
startActivity(abc);
and
Intent abc = new Intent(SecondClass.this,FirstClass.class);
startActivity(greNaPrvoOkno);
If you want to use a custom view (as I understood, you are extending the View class), you can do it in the following way;
Consider you are showing the second class from your Main activity like this;
setContentView(new SecondClass(getApplicationContext(), MainActivity.this));
And you Second class is this (suppose);
// I am using onClickListener to go back to main view. You do whatever you like.
public class SecondClass extends View implements OnClickListener {
// This is needed to switch back to the parent activity
private Activity mParentActivity = null;
public SecondClass(Context context, Activity parentActivity) {
super(context);
mParentActivity = parentActivity;
setOnClickListener(this);
}
#Override
public void onClick(View v) {
// Set the Main view back here.
mParentActivity.setContentView(R.layout.main);
}
}
Disclaimer: This code will do what you have asked for, but may cause other problems.
As advised by #Mudassir, you should use two different activities for two screens. It will give you better control, and your code will be easy to understand and maintain.
On the Onclick event of the button you have to write finish(); that's it..
Both of your classes are Activities yes? IF so then in your second activity you will simply call finish() and your activity will close revealing your first activity again.
When I have used multiple intents in my android application, I have created a new activity through:
Intent abc = new Intent(this, SecondClass.class);
startActivity(abc);
When the button is pressed in your second class, I would then either call finish(); on the class, or create a new intent like so:
Intent abc = new Intent(this, FirstClass.class);
startActivity(abc);
However, this method has the disadvantage that if a user wanted to use the back button, they may have to scroll through many layers of activities.
You should create another activity for your second class but not just set the main activity to a new view setContentView(secondClass).
For an easier modification, You could try to set the view back to setContentView(R.layout.main) first.
You still need to configure the widgets(e.g. TextView) on it when you set it back.
You don't have to startActivity again to go back.
Just call finish() in your second activity when you want to finish the current activity and go back:
e.g. When user press the back button in your second activity
mButtonBack.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
finish();
}
}

Finishing current activity from a fragment

I have a fragment in an activity that I am using as a navigation drawer. It contains buttons that when clicked start new activities (startActivity from a fragment simply calls startActivity on the current activity).
For the life of me I can't seem to figure out how I would finish the current activity after starting a new one.
I am looking to achieve something like this in the fragment:
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
if (view == mButtonShows) {
Intent intent = new Intent(view.getContext(), MyNewActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
}
But it seems Fragment.class does not implement finish() (like it implements startActivity(...)).
I would like the activity backstack cleared when they launch the 2nd activity. (so pressing back from the new activity would technically drop them back to the launcher)
When working with fragments, instead of using this or refering to the context, always use getActivity(). You should call
Java
getActivity().finish();
Kotlin
activity.finish()
to finish your activity from fragment.
Well actually...
I wouldn't have the Fragment try to finish the Activity. That places too much authority on the Fragment in my opinion. Instead, I would use the guide here: http://developer.android.com/training/basics/fragments/communicating.html
Have the Fragment define an interface which the Activity must implement. Make a call up to the Activity, then let the Activity decide what to do with the information. If the activity wishes to finish itself, then it can.
As mentioned by Jon F Hancock, this is how a fragment can 'close' the activity by suggesting the activity to close. This makes the fragment portable as is the reason for them. If you use it in a different activity, you might not want to close the activity.
Code below is a snippet from an activity and fragment which has a save and cancel button.
PlayerActivity
public class PlayerActivity extends Activity
implements PlayerInfo.PlayerAddListener {
public void onPlayerCancel() {
// Decide if its suitable to close the activity,
//e.g. is an edit being done in one of the other fragments?
finish();
}
}
PlayerInfoFragment, which contains an interface which the calling activity needs to implement.
public class PlayerInfoFragment extends Fragment {
private PlayerAddListener callback; // implemented in the Activity
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
callback= (PlayerAddListener) activity;
}
public interface PlayerAddListener {
public void onPlayerSave(Player p); // not shown in impl above
public void onPlayerCancel();
}
public void btnCancel(View v) {
callback.onPlayerCancel(); // the activity's implementation
}
}
You should use getActivity() method in order to finish the activity from the fragment.
getActivity().finish();
This does not need assertion, Latest update in fragment in android JetPack
requireActivity().finish();
In Fragment use getActivity.finishAffinity()
getActivity().finishAffinity();
It will remove all the fragment which pushed by the current activity from the Stack with the Activity too...
Every time I use finish to close the fragment, the entire activity closes. According to the docs, fragments should remain as long as the parent activity remains.
Instead, I found that I can change views back the the parent activity by using this statement:
setContentView(R.layout.activity_main);
This returns me back to the parent activity.
I hope that this helps someone else who may be looking for this.
Very simple...
1- just grab activity by getActivity() in the fragment
2- then call finish();
So just getActivity().finish(); will finish the parent activity.
Try this. There shouldn't be any warning...
Activity thisActivity = getActivity();
if (thisActivity != null) {
startActivity(new Intent(thisActivity, yourActivity.class)); // if needed
thisActivity.finish();
}
You have two options for Java and Kotlin. However, logic of both ways are same. You should call activity after call finish() method.
Answer for Kotlin,
If your activity cannot be null, use Answer_1. However, if your activity can be null, use Answer_2.
Answer_1: activity!!.finish()
Answer_2: activity?.finish()
Answer for Java,
getActivity().finish();
To finish activity in a Fragment use:
getActivity().finish();
Simple solution:
activity?.finish()
yes Fragment.class does not implement finish()
When working with fragments, instead of using this or refering to the context, always use getActivity(). You should call

Categories

Resources