I'm using public static strings for keeping values into my apk.
Example in my Class:
public class Login
{
public static string UserName;
}
In my activity:
Login.UserName="SomeText"
For Some reason which i dont know, all public static strings has been reseted suddenly.(All values has returned on null)
Is there possibility for injection in my code? 'Or' android applications can create a problem like this??
All static variables will be reset and equal to null when you close the application. If you want persistent data then look into android preferences.
Related
Yes I'm really new to android and I'm wokring on a very simple app.
On my mainActivity I'm creating and array, and want to access the array from a different activity.
public class Activity extends {
MyAreas[] myArea;
#Override
protected void onCreate(Bundle savedInstanceState) {
myArea= new MyAreas[2];
myArea[0] = new MyAreas(33, 44, "Location ", "active");
myArea[1] = new MyAreas(32, 434, "Location 2", "active");
Class
public class MyAreas{
public double val;
public double val2;
public String name;
public String status;
public MyAreas(double val, double val2, String name, String status) {
this.val= val;
this.val2= val2;
this.name = name;
this.status = status;
}
I'm trying to access myarea array from my activity2.java, I tried this but didn't work.
private ArrayList<MyAreas> mMyAreasList;
Using Parcelable to pass data between Activity
Here is answer which should help.
In regular Java you can use getters to obtain objects or any variable from a different class. Here is a good article on encapsulation.
In Android, there is a class called Intent that lets you start one activity from another and pass any necessary information to it. Take a look at the developer docs and this other answer which should help you.
For your begginer level, rather than using intents, just set the array object public and static, like that:
public static MyAreas[] myArea;
By that way you can access it from any activity in your app..
Then, go to the activity2.java wherever you want to access it.
MyAreas area = Activity.myArea[0];
The problem with this approach is that you do not have complete control when and in what order the activities are created or destroyed. Activities are sometimes destroyed and automatically restarted in response to some events. So it may happen that the second activity is started before the first activity, and the data is not initialized. For this reason it is not a good idea to use static variables initialized by another activity.
The best approach is to pass the data via the intent. The intents are preserved across activity restarts, so the data will be preserved as well.
Another approach is to have a static field to keep the data, and initialize the data in an Application instance.
Hello i am trying to familiarize myself with Java by doing a very simple "bankaccount" application and it doesn't even save to db or something so it resets all data on rerun.
The problem i am trying to find a good way of doing is that i have an ArrayList of accounts that i want to be able to access from any class so that during runtime for example after an deposit if i access that account later when i want to get balance i get an that account from the ArrayList and it is updated to the deposit value.
When googling i found this solution but i dont like it since it uses static ArrayList. is there any more elegant way than this for an applicaiton that only saves the state/data during runtime.
Simple class that adds the test accounts and so on where first value is acountId and second is balance
public class AccountsModel {
private ArrayList<AccountModel> listOfAccounts;
public AccountsModel() {
listOfAccounts = new ArrayList<AccountModel>();
listOfAccounts.add(new AccountModel(1,0));
listOfAccounts.add(new AccountModel(2,0));
listOfAccounts.add(new AccountModel(3,0));
listOfAccounts.add(new AccountModel(4,0));
}
public ArrayList<AccountModel> getListOfAccounts(){
return listOfAccounts;
}
}
Then in my main class i just do this
static AccountsModel accounts = new AccountsModel();
public static ArrayList<AccountModel> listOfAccounts = accounts.getListOfAccounts();
this "works" as i can get the same list from anywhere within the application. But is there any simple and elegant way of doing this some other way?
You said you dislike the static solution but to me "It needs to be accessed by many classes" screams static variables.
Basically, you create a wrapper for your ArrayList which carries out operations:
class AccountsModel {
private static ArrayList<AccountModel> singleton;
// a static constructor also wouldn't be a bad idea here
public static void init() {
/* add a bunch of AccountModels here*/
}
public static ArrayList<AccountModel> getAccounts() {
return singleton;
}
}
An example of a main method:
public static void main(String[] args) {
ArrayList<AccountModel> accounts = AccountModels.getAccounts();
}
I'm making a quiz app, there is main activity and it contains fragments which are questions like (Radio Button, Checkbox, Drag and drop questions) . How to collect the Score from all the fragments.
Hold the score variable in the Main Activity
private int score=0;
write public functions to get and set the score in the activity
public void setScore(int score){
this.score=score;
}
public int getScore(){
return this.score
}
Now in the fragments you can get and set score using
score=((MainActivity)getContext()).getScore()
((MainActivity)getContext()).setScore(score)
There are multiple ways to do that.
You can add Set/Get method in Your activity and fetch that from
fragment when you need them.
Create static variable in Activity class and you can access with 'ActivityClassName'.
Use Shared Preference and get access of that data anywhere. You can reset when you need and update from any class.
You can use as your app requires.
Just keep the variable static in which your are storing your score .
for eg : public static int score=0
by writing static it will have reference in memory and will be available until the
activity is running .
Create a Java class and name it as DataHolder. Define score variable as a global variable. Create getter & setter method as static. When you get score, set the values using set method. when you want to get score, use get method. Its simple java. Best thing is you can get and set score from any activity or any fragment using this method. Try below code.
DataHolder.java
public class DataHolder {
private static String Score="";
public static void set_Score(String s){
DataHolder.Score = s;
}
public static String get_Score(){
return DataHolder.Score;
}
}
To set score in DataHolder class, use below code from any fragment or activity.
String Score = ""; //get Score to this variable
DataHolder.set_Score(Score);
try using public static final key word if your value is not going to be changed through out the app else use public static before the var type that will remain accessible in all files with out instantiation and value could be initialized at any instance .
Example:
public static int score;
public static final int score=5;
Second way is by using sharedprefrences , you can get help from here .
I'm doing some big refactoring operations relative to some performance improvements in an android app which is using a class with lot of static variables and even static activity references which are then use through the app ! So I was looking for some best practices in Android to store data and give to these data a global access in my app.
First I removed all the activity references to avoid any memory leak, but I'm still looking to know what is the best practice regarding static variables which need to be used anywhere in the android app.
I read many times (example1, exemple2) : using static variables is not necessary a good practices and it's better/cleaner to use one singleton class with getter and setter to have access to my global variables whatever the activity where I am. So what I've started to think is a class which could looks like this one :
public class AppSingleton extends Application {
private static AppSingleton appInstance;
// different stored data, which could be relative to some settings ..
private String setting1;
private String setting2;
private AppSingleton() {
super();
appInstance = new AppSingleton();
}
public static AppSingleton getAppInstance() {
if (appInstance == null) {
appInstance = new AppSingleton();
}
return appInstance;
}
// Getter and Setter for global access
public String getSetting1() {return setting1;}
public void setSetting1(String setting1) {this.setting1 = setting1;}
public String getSetting2() {return setting2;}
public void setSetting2(String setting2) {this.setting2 = setting2;}
}
Then I can use for example :
// Get the application instance
AppSingleton appS = (App) getApplication();
// Call a custom application method
appS.customAppMethod();
// Call a custom method in my App singleton
AppSingleton.getInstance().customAppSingletonMethod();
// Read the value of a variable in my App singleton
String var = AppSingleton.getInstance().getCustomVariable;
For me AppSingleton sounds good because this singleton which restrics ths instantiation of this class to one object, also this class is not destroyed until there are any undestroyed Activity in the application so it means I can keep my global data in the current lifecycle of my app for example from a 'Log in'. But also I can maintain the state of my global variables from my getters/setters.
But then I also had a look on the official android documentation about Performance Tips which say it's good to use static variable it's faster and don't forget to avoid internal getter and setter it's too expansive !
I'm a bit confused about all of these and I'm really keen to learn more about that topic. What is the best practices about using one class to provide an access to some variables which are needed in different part of my code ? Is the class above AppSingeleton is something which could be interesting to use in terms of architecture and performance ?
Is it a good idea to use a singleton pattern for managing global variables in android ?
those lines are completely wrong on your code:
private AppSingleton() {
super();
appInstance = new AppSingleton();
}
public static AppSingleton getAppInstance() {
if (appInstance == null) {
appInstance = new AppSingleton();
}
return appInstance;
}
you cannot instantiate new Application, the Android framework instantiates it. Change to this:
private AppSingleton() {
super();
appInstance = this; // keep ref to this application instance
}
public static AppSingleton getAppInstance() {
return appInstance;
}
Regarding the accessing of global variables. I believe it's more organized to have those singletons somewhere else on your application. The application class have different responsibilities you should not overload it with different tasks. That's OO clean coding.
Also, sometimes there's not that much reason in an Android app to have getters/setters for everything, because u don't need as much access control as in bigger projects. But this should be considered case-by-case about the necessity and not be used a general rule.
So you could for example have it like:
public class Globals {
private static final Globals instance = new Globals();
public static Globals get() { return instance; }
public String value1 = "Hello"
public int value2 = 42;
}
then on your code call as needed:
Log.d(TAG, Globals.get().value1);
Globals.get().value1 = "World";
Log.d(TAG, Globals.get().value1);
Log.d(TAG, "Value2 = " + Globals.get().value2);
i am on the creation of an app in android. its a calculator app. the main activity is where the user could input the equation, and the second activity is where the user can add/edit/delete variables. so i made a new class in another file named Global.java. then i extended it to application, imported everything i need, made s private string, made some public functions, edited the manifest, and initialized it right on my main activity. everything works fine while im only using a string to be passed by the functions but when i started adding what i need, an ArrayList, and made some functions so i could access the list then run it, the app closes. i think its because the arraylist is not allowed to be passed to different classes? am i right or am i just missing something?
please dont downvote my post if i didn't post something needed. i am using aide so there is no log output. code:
Global.java
...
import android.app.*;
import java.util.*;
public class Global extends Application
{
private String s;
public static ArrayList<String> sList;
public String getS() {
return s;
}
public void setS(String ss) {
s=ss;
}
public void add() {
sList.add(s);
}
}
MainActivity.java
...
String s;
...
global=(Global)getApplicationContext();
...
global.setS("jian"); //this one works
global.sList.add("jian"); // this one dont
...
Are you sure you initialized sList, like this:
sList = new ArrayList<String>();
If you didn't, you might want to change its declaration to include this initialization.
public static ArrayList<String> sList = new ArrayList<String>();
Just do
global.add("jian");
since you have an add function to take care of the addition of item to arraylist.
Also, try with this:
public void add(String ss) {
sList.add(ss);
}
You are not instantiating your arraylist.
public static ArrayList<String> sList = new Arraylist<String>();
Also you should read beginner tutorials on Java and android, using a public extension of application like this is a bad idea and you can get log outputs from different apps if Aide doesn't provide that, search play store