i working on an android application, i have an api object that initialised to null in the main activity, i initilise it in another activity, and when i finish i call back my main activity like this:
startActivity(new Intent(this, MainActivity.class));
when i come back to the main activity, it set up my api object to null;
i don't know how i do to keep my api object set up, when i come back to the main
i tried use static and protected but it's still not work
Would someone have a solution to avoid this problem?
your mistake is that you start MainActivity again, you can just finish second activity.
if you want to send data from second activity to MainActivity you can use onActivityResult method
check this to read more link
Related
I have four activity for my application, Main Activity -> second Activity-> Third Activity -> Fourth Activity. Each Activity contains the onBackPressed method implemented. Every time when the onBackPressed method called, it sends an intent to the previous activity. For Example, in Fourth Activity onBackPressed method, it contains an intent to go to the previous Activity, which is the Third Activity. This works fine upto the MainActivity. When I press on the back button on the MainActivity it must exit the application. However, it just starts the next activity, which is the second Activity. What causes this bug???
Here is some relevant code.
From the fourth activity:
#Override
public void onBackPressed() {
Intent intent = new Intent(this,third.class);
intent.putExtra("id",FinalID);
intent.putExtra("Image Item", categoryItem);
startActivity(intent);
}
From the third activity:
#Override
public void onBackPressed() {
Intent intent2 = new Intent(this, second.class);
intent2.putExtra("Image Item", categoryItem);
Toast.makeText(this, "theFinalActivity=" + categoryItem.getId(), Toast.LENGTH_SHORT).show();
startActivity(intent2);
}
The second activity looks like the following.
#Override
public void onBackPressed() {
next = false;
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
And finally the code in the MainActivity:
#Override
public void onBackPressed() {
System.exit(0);
}
Android System internally handles the backstack for the activities. You don't need to explicitly handle going back if you're not supposed to override the default behavior. In your case, On pressing back, you're not popping the current activity, instead you're pushing a new one into the backstack. This will result in ambiguous behavior of your back button.
First, the onBackPressed function is not required to be implemented only if you are caring about taking care of the activity stack (i.e. finishing up your third activity will bring back the second and finishing the second activity will bring up the first one and so on). The activity stack is already taking care of it.
Secondly, if you want to pass the data to a caller activity from the activity that you have opened from the caller, this is not the ideal way to do so. I would like to recommend you to read this documentation where it explains how to pass such intents in a graceful manner using the life-cycle functions provided by Android.
Just to give you a heads up, here are three steps for you to pass the data between activities in a backward direction.
You need to start the second activity from the first activity using startActivityForResult instead of startActivity with a request code passed along with it (so that you can differentiate between different request codes from other activity if there is any).
Then in your second activity, if you need to pass something to your caller activity (i.e. the first activity), you need to use setResult to pass the desired data back to the caller and finish() the second activity.
In the first activity, you need to implement onActivityResult function to get the data back from the second activity.
Here is a nice example of the overall implementation where you can take a look too.
I know that you are expecting that the system.exit(0) should kill the application whatever the situation is. However, in Android, it does not work in the way that you have expected I think. I am quoting from this answer on StackOverflow to explain how the system.exit(0) works.
System.exit(0) - Restarts the app with one fewer activity on the
stack. So, if you called ActivityB from ActivityA, and System.exit(0)
is called in ActivityB, then the application will be killed and
started immediately with only one activity ActivityA.
I hope that helps!
I have an Activity A which is listening to some websocket message, when it receive certain message, it will navigate to Activity B by startActivity().
Things works fine when App is on foreground, but when it's on background, the startActivity() will cause the App bring to front automatically.
How can I "sliently" startActivity() in background without bringing
the app to foreground?
You can't. What you can do is set a flag, then in onResume call startActivity for the next activity if the flag is set.
Or use fragments instead of activities.
It is not directly possible to do so, However you can try something like minimizing the app as soon as the activity gets started.
In the onCreate method of your activity use the following statement:
YourActivity.this.moveTaskToBack(true);
Of course you will need to use some flags and extras to prevent it from being minimized in other cases too.
as #Gabe said, You can do this by setting a flag, same as we do open login or main activity by checking user object in SharedPreference.
if(SharedPreference Message count > 0){
startActivity(new Intent(this, YourChattingActivity.class));
}
Also you will need to set message count in SharedPreference.
Using below link you are able to achieve what you want:
Here is the solution to check activity status and handle according to that.
I have two Activities in one application.
First one updates its TextViews every 3 seconds. It works fine.
When the keyguard (lock screen) is activated the first activity launches the second activity which appears over the lock screen (in order to show data even if the screen is locked). It also works fine.
I would like the TextViews of the second activity to be updated periodically by the first activity. I have played hours with this and tried a lot of suggestions I found with Google but none of them worked for me. The second activity always crashes with NullPointerException at the moment when the TextView.setText() is called.
What is the best practice for doing this?
Thanks in advance for any help.
I don't think there is a good way to do this, as your first activity could get collected by the system, and you generally don't want to do work after onPause has been called.
I would move that logic that updates the views into a service that runs in the background. Since it sounds like you only need this service while the application is running I would create a bound one.
http://developer.android.com/guide/components/services.html
You can pass the data on calling another activity as :
Intent intent =new Intent(FirstActivity.this, SecondActivity.class);
intent.putStringExtra("TextName","Value");
startActivity(intent);
As Ashish said you could use EventBus.
Add the library to your app and in your Second Activity register your activity in the EventBus in onCreate method:
EventBus.getDefault().register(this);
Create a new class in your project to define an event type:
public class TestEvent {
public TestEvent() {}
}
So in your second activity create a method to receive the event:
public void onEvent(TestEvent event) {
//stuff to do
}
Now, in your first activity you just have to "fire" the event in the method executed each 2 seconds:
EventBus.getDefault().post(new TestEvent());
Each time you execute post method, the onEvent of your second activity will be run.
A way to do it is by defining a Singleton object that holds the value to be displayed on the TextView, for instance, a Integer or a String.
Both activities have access to read/write into this object. So when you come back to the second activity, maybe on the onResume() method..you can the following:
public void onResume() {
super.onResume();
textview.setText(""+ MySingleton.getInstance().getValue());
}
On the other activity:
public void updateMethod() {
int newValue = .....;
MySingleton.getInstance().setValue(newValue);
}
This will make sure that whenever you come back to this activity (as onResume() is called), the value will be updated into the TextView. Of course, assuming that you are updating the value from the other activity accordingly.
Note this is the simplest solution you can do, professionally, I would do an event driven solution, where the observer gets notified when the value is changed. For that you can play with http://square.github.io/otto/ library.
I am making a game for Android, but I never really found a good way to change the activities, or the content views. I have 1 main menu activity now, whose content view receives MotionEvents and dispatches them to my custom buttons. Another Activity has a simple contentView which just paints the screen in one color. All contentViews have the same base class and activity 2 is derived from activity 1.
The problem is, that the app just crashes if a try to change the activity. It takes about 20 seconds, then the error message appears that says the app isnt responding.
In logcat, theres also a message keyDispatchingTimedOut sending to activity2
Below is the code for activity change:
public void changeActivity() {
Log.d("changing", "activity");
Intent i=new Intent(this, Activity_Level.class);
startActivity(i);
}
Any ideas?
You have to use context of your activity in method
Intent i=new Intent(Youar_Activity_Name.this, Activity_Level.class);
^^^^^^^^^^^^^^^^^^^^^^
Use above code in your changeActivity() method.
if the app isn't responding , it's because you do a long operation on the UI thread . maybe after calling this function you continue to do something else ?
if , as people said , the activity isn't opened (and you can check it by writing to the log inside the onCreate method) , check the manifest.
in any case , if you want to have better control of activities , you can check the possible flags to use for the intents , and you can also use fragments (when possible) , just like google recommends .
Without seeing the logcat message, I bet you forgot to add the activity in AndroidManifest.xml
I sense that you didn't add all the activities to the manifest.xml file. Try to add all the activities there, and give it a run.
I have a main activity which calls a child one via
Intent I = new Intent(this, Child.class);
startActivityForResult(I, 0);
But as soon as Child becomes visible the main activity gets its onStop and immediately after that onDestroy method triggered. And as soon as I call finish() within the Child activity or press the back button, the Child activity closes and the home screen shows (instead of the main activity).
How can I prevent the main activity from being destroyed? :\
If you launch a child Activity from which you expect return data, you'll probably want to use startActivityforResult instead.
You may want to check this question: Child Activity in Android as it seems to be the same problem.
Edit:
As for what's happening here, you could place code in the onStop() and/or onDestroy() methods to investigate - at least a call to isFinishing() to check why the Activity is being destroyed.
You should also use adb logcat from your host machine to check the logcat in case it holds more information - and maybe use Log.d() (the result goes into logcat as well) instead of toasts to make sure you don't miss them.
I used Dialog instead of an Activity and everything worked well so I'm leaving it like that.
check androidmanifest nohistory=true and that made the OS destroy the activity before the result. that might be one of the reason for your problem.