I have an Activity1 which launches Activity2. Activity2 has a list which shows some values from database.
When the Activity2 is launched for the first time the list shows the correct information, but if I press back button and then launch the Activity2 again it loads the information correctly from database but it's not displayed on the list.
The code to start Activity2 from Activity1:
final Intent int2 = new Intent(getActivity(), CombinationsManagerActivity.class);
MyActivity.insertSomeExtraInfoToTheIntent(int2, currentEmployee.id);
getActivity().startActivity(int2);
And the Activity2 list code is this (I call it when the activity is register with a server (after onResume)):
private void fillList() {
list = (ListView) findViewById(R.id.list_combinations);
ZKEmployeeLoginCombination combinations = ZKEmployeeLoginCombination.selectLoginCombinationsByEntityID(this, idEmployee);
LoginCombinationsListAdapter adapter = new LoginCombinationsListAdapter(this, combinations, enrolledTypes);
list.setAdapter(adapter);
}
Also, Activity2 manifest declaration:
<activity
android:name="com.blabla.android.app.employeemanagementv3.CombinationsManagerActivity"
android:label="#string/combinations_manager" >
</activity>
Any help would be appreciated.
Finally I found the bug on my code: For project requirements we keep some structures to act as listeners from server events. And registration was one of them.
The way to register the listeners from the activity was:
private static IncomingEventHandler eventHandler = new IncomingEventHandler();
...
if(eventHandler.get(this.name) == null){
eventHandler.add(this.name, this);
}
So I was keeping the reference from the previous activity, and then, when the activity receives a registration event we were doing in post:
referenceToActivity.doSomeStuffOnUIThreadAfterRegister();
This works well the first time, but in the second execution referenceToActivity were pointing to the first activity
You probably only ever want there to have one Activity2 alive in the app. If so, I suggest that you include the following in the manifest for Activity2
android:launchMode="singleTask"
That may solve your problem. For an explanation, see the android documentation.
Just give a try by putting this code snippet on your Activity2 class
#Override
public void onBackPressed() {
Intent startNewActivityOpen = new Intent(Activity2.this, Activity1.class);
startActivity(startNewActivityOpen);
}
Related
I have an Android Best Practice question. I have to following code, which is working nicely, but I think it is not so elegant. So, my question is: at which point of activity life cycle is nice to start another activity ?
public class LoginActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ParentPreferences parentPreferences = new ParentPreferences(getApplicationContext());
if (parentPreferences.isPassExists()) {
Intent i = new Intent(this, MainActivity.class);
startActivity(i);
} else {
setContentView(R.layout.login);
}
}
}
The task is about: if the parent has already made a password to protect the app, than we don't need to show the LoginActivity. I don't know, is it "healthy" for an Activity to give an intent to launch, when nor the onCreate nor the other lifecycle methods completed.
What are you thoughts guys ?
I think the better way is to create LauncherActivity, and start activitys from them:
For example:
public class LauncherActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ParentPreferences parentPreferences = new ParentPreferences(getApplicationContext());
Intent intent;
if (parentPreferences.isPassExists()) {
intent = new Intent(this, MainActivity.class);
} else {
intent = new Intent(this, LoginActivity.class);
}
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)
startActivity(i);
}
}
Updated:
Refering to Activity | Android Developer
onCreate is a first lifecycle method, сonsequently better to start activity B when A activity just started and does not inflate any layout
I would have the manifest start your MainActivity or whatever you call it. The MainActivity starts by checking if the user has logged in. If not, it starts your LoginActivity, which comes back in onActivityResult() with the result of the login.
It does depend on the requirement for the user to log in every time they start the app, or just once, or once in a while. If the use has to log in every time, than it's ok to start with LoginActivity. Otherwise, starting LoginActivity every time and passing to MainActivity (or whatever) seems just a waste. "Waste" not in the sense of performance, but of clarity of your app.
I think the best solution for you is to add a SplashScreen or like a "fake" screen.
Here you check if he's logged in already and based on it you start the correct activity.
Maybe the absolutely best way would be to do it with fragments, but you have to change a lot of your app.
About when to call it, the onCreate is perfect :)
I want to make a app quite similar to contacts app. In the first activity, I want to show my contact list and I have done this. First Activity consists of add new button in which on the click of that button, I want that user enter first and last name and upload an image for the same. I don't know how to navigate between activities so that i get the required answer. Can anyone please help me..??
See the first Activity at: http://postimg.org/image/996iwj5dp/9c92bd46/
and Second Activity at: http://postimg.org/image/wuscpv1tx/fe6f13c4/
on Second activity there is also a button which will make user able to choose a picture from Gallery and thats acts as 3rd Activity. I get confused in getting data from these activities.
You need to implement startActivityforResult() method in first activity.
Follow below steps to perform the operation:
1) On click of the Add new button in your First activity, instead of calling startActivity(), call startActivityforResult() using a unique activity code:
i.e: public static final int FIRST_ACTIVITY_CODE = 0;
In OnClickListener, you need to implement,
Intent m_data = (FirstActivity.this,SecondActivity.class);
m_data.putextra(//any extra data);
startActivityforResult(FIRST_ACTIVITY_CODE,data);
2) Now when you have added another user from the second activity and you want to pass some data from SecondActivity to FirstActivity, then follow below procedure:
Before you finish the SecondActivity after saving the data,
Intent m_data = getIntent();
m_data.putExtra(//data to pass in FirstActivty);
m_data.putExtra(//data to pass in FirstActivty);
.
.
.
setResult(RESULT_OK,m_data);
finish();
3) In the onActivtyResult() of the FirstActivty, do below procedure:
#Override
protected void onActivityResult(int p_requestCode, int p_resultCode, Intent p_data)
{
if(p_requestCode == FIRST_ACTIVITY_CODE && p_resultCode == RESULT_OK)
{
NewData = p_data.getExtras().get(//your data);
// update data
}
super.onActivityResult(p_requestCode, p_resultCode, p_data);
}
Hope this helps you.
I have a main activity that forks a second activity, I wanted to go back from second activity to the main activity without reinitialize it. In other words, I wanted to immediately show the main activity after second activity disappears, instead of re-rendering the first activity. I have tried methods like finish, onBackPressed, none of this goes back directly achieved the effect I desired. Rather it seems that they go back and re-render the activity , which feels like all your previous data that renders the view is lost, and it has to do it from scratch again.
So How can I go back directly without re-rendering again?
Thanks
----------------------Update--------------------
Clase MainActivity extends Activity{
public onCreate(Bundle savedInstanceState){
super.onCreate(SaveInstanceState);
setContentView(R.layout.mainview);
GoogleMap gmap = ...
Route route = ...
//draw a route in the google map
// now the map bears a route on it
Intent intent = new Intent(this, secondActivity.class)
}
}
Class SecondActivity extends Activity{
public onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.secondview);
Button backbut =(Button) findViewById(R.id.backbutton);
}
//backbut is associated with a call back onClick in the xml
private onClick(View){
finish();//after this the second activity disappears, but previously drawn route on google map also disappears, and it takes time to redraw them again. feels like onCreate in firstActivity is reentered again
}
}
You need to use this two flag to accomplish what you want:--
Intent.FLAG_ACTIVITY_CLEAR_TOP
Intent.FLAG_ACTIVITY_SINGLE_TOP
Just use this code:--
Intent intent = new Intent(SecondActivity.this,
MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
you should not call finish() on going second activity then the first activity is running on background and after calling finish() on second activity the first activity appears without re-initialize as privious state.
Hop this will help you.
MainActivity extends Activity{
Context context;
oncreate(){
context = this;
Intent intent = new Intent (context , SecondActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY);
/* here finish() method is not called, if called MaintActivity objects will destory*/
}
}
Guys thank you all for your kind help! I think I kinda solved my problem. They key is that I made the onClick method private so my xml cannot find my onClick and issues an Exception, which caused activity to destroy and re-render themselves. Hope this explanation makes sense
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();
}
}
I need help doing something that I am sure is simple, but I can't figure out how to do it. I have a counter down and when it gets to the last 60 seconds, it calls a 'lastminute' counter activity. The plan is to overlap the last 60 seconds over the actual application.
Here is the problem, how can I change the code to allow the two activities to start at the same time.
I have tried this;
public void onFinish() {
startActivity(new Intent ("eu.merso.phoneapp.LASTMINUTE"));
startActivity(new Intent ("eu.merso.phoneapp.DASHBOARD"));
onDestroy();
}
but this does not put both applications on the screen, what I want is DASHBOARD on the background and LASTMINUTE on top. LASTMINUTE is alreay a "transparency colour".
Thanks;
Ramón
It won't work the way you're currently trying to do it. There can only be one visible activity at a time.
You should first start the dashboard Activity and from there you should start lastminute.
Edit --
Use a Bundle object.
Bundle bundle = new Bundle();
// Use 0 when the activity is called by the button and
// 1 when it is called by the timer.
bundle.putInt("event_src", 0);
intentObject.putExtras(bundle);
// In your new activity you can then check whether to display
// the countdown or not
Int eventSrc = getIntent().getExtras().getInt("event_src")
You need to implement the lastminute functionality in a dialog that you create and show in the onCreate method of your dashboard activity.
EDIT:
To distinguish between which activity that starts the new activity, use intent extras:
//in your calling activity
Intent i = new Intent(A.this, B.class);
i.putExtra("from Activity", A.class.getSimpleName());
startActivity(i);
//in your receiving activity
String from = getIntent().getStringExtra();
if(from.equals(A.class.getSimpleName())){
//do something
}
else if(from.equals(C.class.getSimpleName())){
//do something
}
Try using android:theme="#android:style/Theme.Translucent.NoTitleBar in Activity attributes for LastMinute in AndroidManifest.xml. I hope it'll be productive.
I think using Android fragments will help u to show two separate activities in the context of another main activity.
try reading this:
http://developer.android.com/guide/components/fragments.html