i have an Android application in which i use a class to store static data among activities, something like:
class Global
{
private static boolean mInitialized = false;
private static String mData = null;
public static void init()
{
mData = "something";
mInitialized = true;
}
public static boolean isInitialized()
{
return mInitialized;
}
public static String getData()
{
return mData;
}
}
So in the main activity onCreate i do:
if( Global.isInitialized() == false )
Global.init();
And then starts other activities, the action flow is:
MainActivity -> ActionActivity -> PluginActivity
Where Main is where i init the Global class, and Action & Plugin is where i use the getData() method of that class.
Now in some cases, i get really strange behaviour ... if something unepected happens in PluginActivity ( NullPointerException for instance ), the activity crashes and the application goes back to the ActionActivity which launched it, but, at this point, during the onCreate of the ActionActivity ( where the Global class is supposed to be initialized ) i get an exception because the getData() returns null ( and isInitialized() is false ) as the Global class was never initialized by the MainActivity.
So, can an object with static members like my Global class be deallocated/cleared/whatever if something like an unexpected exception occurs ?
In general, activities should be independent of each other. You should not depend on them being launched in any particular order, or at all.
Instead, if you need to share global state data between activities, i.e. not just parameter passing in intent extras or results via onActivityResult(), subclass Application, put the init code in its onCreate() and access it from activities using getApplication(). Also remember to declare the application class in your manifest. The system takes care that the application object is there when any of your activities are running.
In Android, whenever application crashes the static variable will be discarded. This is the reason why you are getting NullPointerException. Instead of making the object static create a Parcelable or Serializable class and get and set the fields and then pass that object with the intent. In another activity you can get that Parcelable or Serializable class and you can use its property.
Related
I have some major variables in my main activity that I retrieve their values from internet once the user log in. after that, there are multiple activities that can alter these values in the database but this doesn't reflect in the current loaded values until the user log out/in. (the process where I retrieve data from internet)
what is the best way to update these values in main activity from activity 2 directly without logging out/in?
is there a way to set these variables without making intent and putting the new values in extra bundle? ( I need to change the values without returning back to the activity)
You can perhaps try putting the variables in a custom Application class as static members and then access them from anywhere through Application.xyzStaticMember(). Here's an example:
public class MyTestApp extends Application {
private static List<Int> testList;
public static void setList(List<Int> l) {
testList = l;
}
public static List<Int> getList() {
return testList;
}
}
Then access the members: MyTestApp.setList(null); or MyTestApp.getList();. Oh, and don't forget to use the class in the AndroidManifest.xml file!
<application android:name="com.example.MyTestApp"
/* ...more stuffs */ />
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 want to pass a value from activity A to activity B without actually starting the activity B (therefore this rules out the use of Intents and putExtra). The activity B may or may not be started but when it does it needs to display the value passed to it by activity A.
I searched high and low but couldn't find any relevant solution to this seemingly simple question. Any help will be appreciated!
You can't find a solution, because it's something that goes against any logic.
Activity B can't do anything if not started and visible. Activity B might even already be destroyed by the system without you knowing.
You can use a lot of things to set some variables, which your Activity B can read such as in your Application, somewhere in your XML or simply any random class.
Still, you can not actually DO anything with any of these options, until you start Activity B and when you can, it will just effectively be the same as giving the extra data in the Intent.
Use global class like :
public class AppConfig {
Context context;
public AppConfig(Context mxt) {
context = mxt;
}
public static String filepath = null;
Then, in activity A before onCreate() :
AppConfig config;
Context context;
and in onCreate() method put this :
context = getApplicationContext();
config = new AppConfig(context);
And, in second Activity B before onCreate() :
AppConfig config;
Context context;
And, in onCreate() method put this :
context = getApplicationContext();
config = new AppConfig(context);
And set the value where you want. Hope this will help you.
You can use shared Preferences. Using this one Activity can set Value into it, and other activity can read from it.
So you need to keep a value for an activity . If it starts it means you have to use those values, otherwise you will discard those values. For this you can use a separate class with a variable of datatype that you want and you can create getter setter for that and you can use it.
Make use of the classes
public class GetSet {
public GetSet() {
super();
}
private static boolean passwordSet = false;
public static boolean isPasswordSet() {
return passwordSet;
}
public static void setPasswordSet(boolean passwordSet) {
GetSet.passwordSet = passwordSet;
}
}
You can access ths using GetSet.setPasswordSet(false);
and Boolean flag = GetSet.isPasswordSet();
Set the value as Global:
public class Global {
public static int mValue;
public static int getValue() {
return mValue;
}
public static void setValue(int mValue) {
Global.mValue = mValue;
}
}
I was looking for answers to that but I couldn't find it. So I found a way to do that.
First Activity
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("Flag" , true);
startActivity(intent);
Second Activity
boolean flag;
flag = getIntent().getBooleanExtra("Flag" ,false);
if(flag == true)
{
this.finish();
}
So now you may send any data you want it will open the Second Activity and then immediately close it after you wouldn't even realize it. You may use Shared prefences to save your data for after usage.
I have defined a function in MainActivity now I want to access the function from another class in my app. I have created an object of the MainActivity and with that object I have called the function. Although there is no error, it's not executing. Every time I try to execute, the app crashes.
Activity A should have a variable
static ActivityA activityA;
In onCreate state:
activityA = this;
and add this method:
public static ActivityA getInstance(){
return activityA;
}
In activity B, call
ActivityA.getInstance().myFunction(); //call myFunction using activityA
You cannot just create objects of Activities by using:
MyActivity activity = new MyActivity();
as you would with normal Java classes. All Activities in Android must go through the Activity lifecycle so that they have a valid context attached to them.
By treating an Activity as a normal Java class, you end up with a null context. As most methods in an Activity are called on its Context, you will get a null pointer exception, which is why your app crashes.
Instead, move all such methods which need to be called from other classes into a Utility class which accepts a valid context in its constructor, and then use that context in the methods to do the work.
Make the variable public and then create object in adapter like this:
public int i; // Variable in Activity class
((ActivityName) context).i // accessing in adapter
I know that stuff of calling the new activity and pass the object value from one activity to another by using putExtra and getExtra function. but i want to pass the value without calling and start the new activity. Is it possible ?
If yes then let me know how i can do it ?
You can also use the Application class for declaring global variables
class Globalclass extends Application {
private String myState;
public String getState(){
return myState;
}
public void setState(String s){
myState = s;
}
}
class TempActivity extends Activity {
#Override
public void onCreate(Bundle b){
...
MyApp appState = ((MyApp)getApplicationContext());
String state = appState.getState();
...
}
}
UPDATED :
Checkout this nice Tutorial about how to do that.
Application Class Using as Global
for this you can use static variable or SharedPreferences or if you heavy data then you can use SQlite.
You can take the help of database like SQLite or you may go for Constant class concept where you can make a public static variable and store your data in one activity and access in other activity.Hope this will help you.
There're a lot of ways to pass a value to an activity:
You can use an Intent with FLAG_ACTIVITY_REORDER_TO_FRONT. In this case onNewIntent() method will be called for already started activity.
You can use static fields or static methods to pass new data to your activity. But it's not a good method really because sometimes application is terminated even if it's foreground and all static data is lost.
You can send new data to an activity using broadcast messages. In this case the activity must register a BroadcastReceiver.
I think it's not very difficult to make up a few more ways to pass arguments.
You may want to use handler's handleMessage() and pass the object in a message .
Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
}
};
You can then call handler.handleMessage(msg), you can assign any object to msg.onj