I have created Global Variables that are required at different steps in the entire Application Cycle. Below is the GlobalVariable.java created:
import android.app.Application;
public class GlobalVariable extends Application {
private String globalVariableOne;
public String getGlobalVariableOne() {
return globalVariableOne;
}
public void setGlobalVariableOne(String globalVariableOne) {
this.globalVariableOne = globalVariableOne;
}
}
Then I am easily able to Get and Set this Global Variable from any activity using the below code.
final GlobalVariable globalVariable = (GlobalVariable) getApplicationContext();
//To Set the globalVariableOne Value in an Activity
globalVariable.setGlobalVariableOne("My Value");
//To Get the globalVariableOne Value in a
String readGlobalVariableOne = globalVariable.getGlobalVariableOne();
Now I have an ArrayList localArrayList created by using the below code in my Activity.
List<String> localArrayList = new ArrayList<String>();
int maxLength = "10";
for (int i = 0; i < maxLength; i++) {
String valueOne = "Value "+i;
String valueTwo = "Value "+i;
localArrayList.add(valueOne));
localArrayList.add(valueTwo);
}
I want this ArrayList to be stored as a Global ArrayList accessible and editable by any Activity within my Application. I am not sure how to do it.
Can anyone help me in editing my GlobalVariable.java to define the Global ArrayList and guide me on how to Get and Set this Global ArrayList?
It should become like this:
public class GlobalVariable extends Application {
private String globalVariableOne;
private List<String> globalArrayList;
public String getGlobalVariableOne() {
return globalVariableOne;
}
public void setGlobalVariableOne(String globalVariableOne) {
this.globalVariableOne = globalVariableOne;
}
public List<String> getGlobalArrayList() {
return globalArrayList;
}
public void setGlobalArrayList(List<String> globalArrayList) {
this.globalArrayList = globalArrayList;
}
}
Then in you code you can do:
GlobalVariable myAppClass = (GlobalVariable)getApplicationContext();
//saving the list
myAppClass.setGlobalArrayList(/*put here the list to save*/);
//getting the list
List<String> globalArrayList = myAppClass.getGlobalArrayList();
But i really don't like this approach of putting every global variable inside the custom Application class...
Related
I was wondering how to reference an ArrayList a different method than it was declared in.
For example I am writing a program that allows me to create a playlist of songs, so in one method I have createAPlaylist and then another method I have shuffle().
In my playlist method I have created an ArrayList but I am having trouble using this arrayList in my shuffle method. There is some code below for context:
public static void createAPlaylist() {
try {
System.out.println("We have the following tracks:");
ArrayList<String> songs = new ArrayList<String>();
String firstSong = jukebox.allTracks.get(0).getTitle();
songs.add(firstSong);
for (int index = 0; index < count; index++) {
System.out.println(SPACES + (index + 1) + ". " + jukebox.allTracks.get(index).getTitle());
}
System.out.println("Select a track to add to the playlist: ");
int songNumber = input.nextInt();
String songSelected = songs.get(songNumber);
songs.add(songSelected);
input.nextLine();
} catch (Exception e) {
System.out.println("\nplease select a valid song number.");
}
}
This is what method parameters are for:
public static void createAPlaylist() {
ArrayList<String> songs = new ArrayList<>();
shuffle(songs);
}
public static void shuffle(ArrayList<String> songs) {
// Do stuff with your ArrayList here
}
You can the arraylist from the createAPlaylist method and pass that to shuffle method:
Like:
public static List<String> createAPlaylist() {
...
...
...
return songs;
}
/// and then in shuffle method receive that as parameter :
public static void shuffle(List<String> songs){
// access that songs list by
}
Or you could:
Instead of method variable declare that arraylist as class variable..
Like:
public class ClassName{
public static ArrayList<String> songs = new ArrayList<String>();
public static void createAPlaylist() {
...
...
...
// reset the songs.
songs = new ArrayList<String>();
...
}
/// and then in another method:
public static void suffle(){
// access that songs list by
List<String> createdSongs = ClassName.songs;
}
In Java, variables are only available within the context they are created - so if you create an ArrayList inside a method, you cannot access it outside of that method unless you store it in the method’s class, or you return the variable from the method it’s made it.
You can either declare the ArrayList outside of the method, as a class field, like so:
public class Foo {
private static ArrayList<String> arrayList = new ArrayList<String>();
public static void createAPlaylist() {
arrayList.add();
etc...
}
}
Or you could return the ArrayList from the method like so:
public class Foo {
public static void main(String[] args) {
ArrayList<String> arrayList = createAPlaylist();
}
public static ArrayList<String> createAPlaylist() {
ArrayList<String> songs = new ArrayList<String>();
// Your code here
// Note that you have to return the list from
// inside the catch block!
// I’d recommend creating the ‘songs’ ArrayList
// outside of the ‘try’ block, so that you can
// have a fallback if something fails in the ‘try’
return songs;
}
}
I don’t know if you intend to have this all static. I’d think it will work better as non static, but that’s a matter for another question, so I’ve left it as-is in the examples.
Sorry if this isn’t formatted perfectly - I’m on a mobile device and don’t have my IDE.
I'm attempting to code an app that takes the users numerical specifications from the main activity in the form of a TextEdit input, convert that to an integer and then use that specific value of the integer and use that value in a separate class file which I will use the result of the class in the main activity.
Is this possible? Here's what I've attempted in the global variables of the main activity:
deadzoneValue = findViewById(R.id.TextView_deadzoneInfo);
public EditText threshold, deadzone;
public String deadzoneString = deadzone.getText().toString(); //deadzone being the name of the
public int timeLimit = Integer.parseInt(deadzoneString);
public String thresholdString = threshold.getText().toString();
public static int thresholdLimit = Integer.parseInt(thresholdString);
I'm not sure how to use these in the Deadzone class, which I'm trying to take the specific value and use there.
EDIT: Deadzone.java isn't an activity but a class with functions that are called in the MainActivity.
Using of ClassicSingleton:
public class ClassicSingleton2 {
private static String instance = null;
protected ClassicSingleton2() {
}
public static String getInstance() {
return instance;
}
public static void setInstance(String instance) {
ClassicSingleton2.instance = instance;
}
}
You could change type of instance variable to int ...
And in target code you could get this data:
xRef = ClassicSingleton2.getInstance();
This is very simple.
2:
And using of put (putExtra)
Intent oI = new Intent((FirstActivity)this,SecondActivity.class);
oI.putExtra("XRefCaller",123);
And in target code(activity) :
Bundle oBundle = getIntent().getExtras();
if(oBundle != null){
oXRefCaller = oBundle.getString("XRefCaller",-1);
//checking with -1 if the parameter does not exist or is null
}
I have created a class named "Global Services" which I use to save my data globally and access them in a different activity. But when I am calling the set() method, instead of overview the existing data instead it is appending that data. Below is my code.
I have even tried to remove the instance but still, it is appending the new data instead of overwriting.
import java.util.ArrayList;
import java.util.List;
public class GlobalServices {
private static GlobalServices instance;
String partner, leadsResponse;
List<Leads> assignedList = new ArrayList<>();
List<Leads> unAssignedList = new ArrayList<>();
List<Inventory> listInventory = new ArrayList<>();
private GlobalServices() {}
public static GlobalServices getInstance() {
if (instance == null) {
instance = new GlobalServices();
}
return instance;
}
public static void destory() {
instance = null;
}
public String getPartner() {
return partner;
}
public String getLeadsResponse() {
return leadsResponse;
}
public List<Leads> getAssignedList() {
return assignedList;
}
public List<Leads> getUnAssignedList() {
return unAssignedList;
}
public List<Inventory> getListInventory() {
return listInventory;
}
public void setPartner(String partner) {
this.partner = partner;
}
public void setLeadsResponse(String leadsResponse) {
this.leadsResponse = leadsResponse;
}
public void setAssignedList(List<Leads> assignedList) {
this.assignedList = assignedList;
}
public void setUnAssignedList(List<Leads> unAssignedList) {
this.unAssignedList = unAssignedList;
}
public void setListInventory(List<Inventory> listInventory) {
this.listInventory = listInventory;
}
}
The problem is that you're just assigning new references to your lists in GlobalServices but not creating new lists. This means as soon as you modify this reference from another place in your code, it will be reflected in the GlobalServices list as well. All you have to do is:
public void setAssignedList(List<Leads> assignedList) {
this.assignedList = new ArrayList<>(assignedList);
}
public void setUnAssignedList(List<Leads> unAssignedList) {
this.unAssignedList = new ArrayList<>(unAssignedList);
}
public void setListInventory(List<Inventory> listInventory) {
this.listInventory = new ArrayList<>(listInventory);
}
This way a new copy will be created in memory for each list and the data will be overwritten.
Sorry if I was wrong, but your code here is not a problem.
The problem might come from other part of your application.
The data you set might be the data that extend your current data.
Example you have
GlobalServices instance = GlobalServices.getInstance()
List<Inventory> listInventory1 = new ArrayList<>();
listInventory1.add(new Inventory());
instance.setListInventory(listInventory1); // now your inventory have one item
// In some where else in your project
List<Inventory> listInventory2 = instance.getListInventory(); // lisInventorys.size() equals 1
// Then you add more data to listInventory2 by mistake
listInventory2.add(new Inventory()); // listInventory2.size() equals 2
// Then you set back listInventory2 to your global service
instance.setListInventory(listInventory2); // now your inventory have two item
So, the data had been actually overwrite, it data just been extended by accident.
Sorry for my title which is unclear, but I don't know how to say it differently.
I have an object "Rapport" which takes a couple of parameters (3 Strings and one Object). This Object "SortingParameter" takes a number of boolean arguments "boolean... args". My goal is to read lines in a text file, create an ArrayList made of these "Rapport" objects. For this, I loop through the lines:
for (String line : Files.readAllLines(Paths.get("myTxt.txt"),Charset.forName("ISO-8859-1"))) {
String[] split = line.split(";");
if(split.length>3){
rapports.add(new Rapport(split[0],split[1],split[2],new SortingParameter(PROBLEM)));
}else{
rapports.add(new Rapport(split[0],split[1],split[2]));
}
I would like to add the rest of my split[ ] tab in the object dynamically. Does anybody know how this could be cleanly done?
The rest of my code:
Rapport.java
package model;
import static model.Constant.RESSOURCES;
public class Rapport {
private String nomListe;
private String nomRessource;
private String categorie;
private SortingParameter param;
private boolean hasParameter;
public Rapport(String nomListe, String nomRessource, String categorie, SortingParameter param){
this.nomListe = nomListe;this.nomRessource = RESSOURCES + nomRessource;
this.categorie = categorie;this.param = param;
this.hasParameter = true;
}
public Rapport(String nomListe, String nomRessource, String categorie){
this.nomListe = nomListe; this.nomRessource = RESSOURCES + nomRessource;
this.categorie = categorie; this.param = null; this.hasParameter = false;
}
/** Getters **/
public String getNomListe(){return nomListe;}
public String getNomRessource(){return nomRessource;}
public String getCategorie(){return categorie;}
public boolean hasParameter(){return hasParameter;}
public SortingParameter getParam(){return param;}
}
And my SortingParameter.java:
package model;
import java.util.ArrayList;
public class SortingParameter {
private ArrayList<Boolean> paramList;
public SortingParameter(boolean... args){
paramList = new ArrayList<>();
for (boolean arg : args) {
paramList.add(arg);
}
}
public ArrayList<Boolean> getParamList(){return paramList;}
}
As you say, you want to add the rest of your split[]-tab to a Rapport-instance.
Just provide a String-Array as an attribute in your Rapport-class:
public class Rapport {
//some attributes...
private String[] eitherColumns;
//getters and setters and so on....
}
Then, when you read a line from the file, use a setter or another constructor to add the rest of the tabs to your Rapport-Instance.
You can also use a separate constructor which only gets the String-Array read from the file and let the class decide what to do with the array-elements which would be more convenient so separate your business logic from your data.
I am trying to save a custom class containing ArrayLists to SharedPreferences using GSON. Each time I rotate the screen, the activity starts over and the string generated by gson seems to append the ArrayList to the previous string, instead of replacing it.
The SimpleUserValues class is just a class to store user info, with an empty constructor and private ArrayLists together with their corresponding setters and getters.
The code in my activity is as follows:
SimpleUserValues simpleUserValues = SimpleUserValues.newInstance();
simpleUserValues.setTheBooleans(userValues.getTheBooleans());
Gson gson = new Gson();
Type classType = new TypeToken<SimpleUserValues>() {
}.getType();
String insertedJSON = gson.toJson(simpleUserValues, classType);
if (getSharedPreferences(myAppKey, MODE_PRIVATE).contains("JSON")) {
Log.e("insertedJSON ", getSharedPreferences(myAppKey, MODE_PRIVATE)
.getString("JSON", ""));
getSharedPreferences(myAppKey, MODE_PRIVATE).edit().remove("JSON")
.commit();
getSharedPreferences(myAppKey, MODE_PRIVATE).edit()
.putString("JSON", insertedJSON).commit();
} else {
getSharedPreferences(myAppKey, MODE_PRIVATE).edit()
.putString("JSON", insertedJSON).commit();
}
The output I see from Log.e is like this:
insertedJSON﹕ {"theBooleans":[true,true,true,true,true,true],...
insertedJSON﹕ {"theBooleans":[true,true,true,true,true,true,true,true,true,true,true,true],...
insertedJSON﹕ {"theBooleans":[true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true],...
insertedJSON﹕ {"theBooleans":[true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true],...
Any ideas / known issues ? I am even deleting the previously saved string before writing, so I cannot understand how this appending is coming from. The input into SimpleUserValues is always the same. Thanks in advance :)
EDIT: here it is the custom class SimpleUserValues:
public class SimpleUserValues {
private int theCurrentFragment;
private int theCurrentGraph;
private ArrayList<Boolean> theBooleans;
private ArrayList<Integer> theIntegers;
public SimpleUserValues() {
}
public static SimpleUserValues newInstance(){
return new SimpleUserValues();
}
public ArrayList<Boolean> getTheBooleans() {
return theBooleans;
}
public void setTheBooleans(ArrayList<Boolean> theBooleans_) {
theBooleans = theBooleans_;
}
public ArrayList<Integer> getTheIntegers() {
return theIntegers;
}
public void setTheIntegers(ArrayList<Integer> theIntegers_) {
theIntegers = theIntegers_;
}
public int getTheCurrentFragment() {
return theCurrentFragment;
}
public void setTheCurrentFragment(int theCurrentFragment_) {
theCurrentFragment = theCurrentFragment_;
}
public int getTheCurrentGraph() {
return theCurrentGraph;
}
public void setTheCurrentGraph(int theCurrentGraph_) {
theCurrentGraph = theCurrentGraph_;
}
}
I had a bug in the arrays I was saving, adding more rows instead of replacing. Oops. Thanks #Kane for your comment