I need a way to store a json-string as for as long as the application is alive.
So to put this into other words :)
If the application changes orientation or gets paused or stopped i need to store my value/string..
But if the application gets forced killed for some reason I want the value to be removed/droped
Im trying to create a custom history-handler.. and this history handler is suppoed to keep history of actions with in my application for as long as the application process is actually running, but as soon as the process gets killed I need the history to get erased as well.
I have tried to store the value/string as a SharedPrefernce, and to simply remove it once isFinishing()== true
I have also tried using the onDestroy as well.. but there seems to be no "beforeProcessKilled"-event to listen for.. so maybe there is another option than using the SharedPreferences?
Thanks in advance!
Use a simple Java static data member. That value will live until the process is terminated, for whatever reason.
It's my way, maybe not the best.
You can create a class named "Global" or other...
Then declare inside something like this, some "static" variables :
public class Global_variables {
public static JSONArray test;
public static String test1;
}
Then, in your activity or other, import "Global_variables" and get your String or other like this:
String IwantTostore = Global_variable.test1;
If you change orientation, your Global_variable.test1 keep alive ;)
Hope this help
I usually do something like this
public class Globals extends Application {
private String jsonString;
public void jsonString(String string) {
jsonString = string;
}
public String jsonString() {
return jsonString;
}
}
then access it with something like
Globals myGlobal = (Globals)getApplication();
// get json string
String json = myGlobal.jsonString();
so on...
Related
I am new at developing Android .I have a question. How to pass object from one activity to another activity without using Intent.Can I do it by Interface ,if so how Could you please how can I hanle that
I think you have 2 options
In memory, save it to somewhere that all activities can reach, or make it static. This is not good idea though
Save it to disk, and use it, such as shared preferences
You can store it in SharedPreferences and then in another Activity
restore it.
You can store it in SQLite and then in another Activity restore it.
You can use static links
You can use service
save data in a singleton class model and get the same object from another activity
Create a class like this
public class SingletonModel {
private static SingletonModel instance;
public String textData = ""
public synchronized static SingletonModel getSingletonModel() {
if (instance == null) {
instance = new SingletonModel();
}
return instance;
}
private void SingletonModel(){}
}
From first activity do like this
SingletonModel.getSingletonModel().textData ="Your data goes here";
From second activity do like this
textView.setText(SingletonModel.getSingletonModel().textData);
If the data should persist, use a file. If not, use a singleton.
I'm a bit confusing on how to share global variables between activities in an android project that considered safe.
What is the best practice to do that? Extends Application class or make a custom singleton class?
An help is apprecciate, thanks in advance.
The problem with storing something in the application class is you cannot count on an activity being resumed from the same instance of the application object. For example an activity can be paused, the application killed (due to memory) along with any changes you made to object in the instance, and then the activity resumed with a new application instance.
Here is a very good BLOG post explaining how data stored in the application class can be lost:
http://www.developerphil.com/dont-store-data-in-the-application-object
I am not sure this is the very "Best" practice, but I think this is a good solution
I have a PersistData class holds application wide "globals". I use Dagger to inject instances of this singleton into any class that requires these variables.
The basic process it this:
When I save a value in this object via something like:
mPersistData.saveEmailId("me#example.com");
I first write it to an entry in SharedPreferences
I then save it to a member variable
In the constructor for the class, I initialize the member variables by reading them from SharedPreferences.
This way reads for the variable are "cached", ie they don't need to be read from SharedPreferences, and if the application is ever killed and restarted the member variables have the correct values. If you just hold the values in the application class, when the application is restarted the member variables will be invalid (not what you expect or even null).
Here is an example:
public class PersistData {
private String email;
public PersistData(MyApp app) {
mApp = app;
email = readEmailId();
}
public void saveEmailId(String emailToSave) {
writeEmailId(emailToSave);
email = emailToSave;
}
private void writeEmailId(String emailId) {
generalSettingsFileEditor.putString("USER_ID", emailId);
generalSettingsFileEditor.commit();
}
public String readEmailId() {
String emaiId = generalSettingsFile.getString("USER_ID","");
return(emaiId);
}
public String getEmail() {
return email;
}
}
In my application Dagger module I have this:
#Provides #Singleton
public PersistData providePersistData () {
System.out.println(String.format("mApp = %s", mApp));
return new PersistData(mApp);
}
Then whenever I need to access any of these variables I inject the singleton as so:
public class HomePresenter {
#Inject
PersistData mPersistData;
...
mPersistData.saveEmailId("me#example.com");
myEmail = mPersistData.getEmailId();
...
}
What is the best practice to do that? Extends Application class or
make a custom singleton class?
Think twice whether those variables are really global and they have to be shared between activities.
If the answer to first question is 'yes', then the best place would be to store them in Application.
You can implement a singleton too, but 1) it's slightly more difficult to test and b) if your global variables require Context, then again Application instance would fit the best.
I need to create a session and change it at times. In a specific activity should recover it and compare it to a different variable and modify the value of this session. I tried to create a class for this, but the change of activity, the value back to null. I need it to remain until the application is closed.
below:
import android.app.Application;
public class Util extends Application {
private static String idCorrente;
public void onCreate() {
super.onCreate();
idCorrente="0";
}
public static String getIdCorrente() {
return idCorrente;
}
public static void setIdCorrente(String id) {
Util.idCorrente = id;
}
}
I do not know exactly the right way to do it.
You need to store the data on the device somehow. I would recommend reading the Storage Options page of the Android Developers Guide.
Specifically, I think you will find SharedPreferences well-suited for your application.
I have many shared preference for my app (mostly relating to color customization) and I'm unsure what the best method is to store/use them at runtime.
Currently I am doing something like this (with more or less preferences depending on the view) in every activity/fragment:
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getActivity());
int buttonbg = settings.getInt("buttonmenu_bg", 0);
int buttontxt = settings.getInt("buttonmenu_txt", 0);
int headerclr = settings.getInt("header", 0);
And then using those to set the various colors in the display. This seems like a lot of overhead to have to call the PreferenceManager each time and go through all that.
So I started looking at creating an application class, reading the preferences in once and using static variables from the application class in the activities/fragment to set the display.
My question is, are there any drawbacks or gotchas to doing this that I should consider before I venture further down the Application class path?
If you are not using so many static variables so this may not affect your application.But the problem with static variable may arise when your app goes to background and the app running on front requires memory so it may clear your static data,so when you will go to your app you may find nothing (null) in place of static data.
The purpose of the Application class is to store global application state or data (in memory of course), so your approach is correct. I've used it multiple times and it works like a charm.
What I usually do is to create a Map member variable and provide methods for getting and putting values into it, looks like this:
package com.test;
...
...
public class MyApp extends Application{
private Map<String, Object> mData;
#Override
public void onCreate() {
super.onCreate();
mData = new HashMap<String, Object>();
}
public Object get(String key){
return mData.get(key);
}
public void put(String key,Object value){
mData.put(key, value);
}
}
Then from my activities, I just do ((MyApp) getApplication()).get("key") or ((MyApp) getApplication()).put("key",object). Also, don't forget to set the android:name attribute in your manifest file, under the application tag:
<application
...
...
android:name="com.test.MyApp">
</application>
Is there any particular reason why you are not setting the display colors in res/values/styles.xml?
If I initialize some static objects in an activity and then call finish(), do those objects still exist elsewhere in the application? Like say I want to access them later on in a service.
If not, are there any other solutions where I could initialize some static objects one time that other classes will have access to?
Yes, doing that is possible. But for the static objects to continue to exist, there should be at least one Activity/Service in the application to be running. What I normally do for such variables is to create a class to hold static methods and variables. Something like this:
public class Utils
{
public static String s;
public static int i;
public static initStatics()
{
s = "";
i = 0;
}
}
This you can call from your other Activity/Service like this:
public class CustomService extends Service
{
#Override
public void onStart()
{
Utils.initStatics();
}
}
So, these variables will be available as long as your app is running. Hope that helped. Good luck!
For things of that nature you can use static member variables on the Application object. You will have to clean up manually (since onDestroy is never called), and you will need to make sure there is at least one Activity/Service in the application running to prevent the app's process from being destroyed by the OS.