Saving data in ArrayList of objects - java

Im trying to figure out how to save some data in ArrayList of objects, but I'm new in Java so I have had some trouble...
So lets say we have an ArrayList of this object:
public class AppListModel(){
private String AppName;
private String packageName;
public AppListModel(){
}
public String getAppName() {
return appName;
}
public String getPackageName() {
return packageName;
}
public void setAppName(String appName) {
this.appName = appName;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
}
and we have arrayList of this object in difrent file:
public class ProfilesList {
private ArrayList<AppListModel> profilesList = new ArrayList<AppListModel>();
public ProfilesList(){
}
public ArrayList<AppListModel> getProfilesList() {
return profilesList;
}
public void setProfilesList(ArrayList<AppListModel> profilesList) {
this.profilesList = profilesList;
}
public void addProfilesList(AppListModel appListModel) {
this.profilesList.add(appListModel);
}
}
Is it possible to store data in one file like:
AppListModel appList = new AppListModel();
appList.setAppName("ssss");
appList.setPackageName("ddddd");
ProfilesList list = new ProfilesList();
list.addProfilesList(appList);
and then access those data from another file like:
ArrayList<AppListModel> list = new ArrayList<AppListModel>();
ProfilesList profList = new ProfilesList();
list = profList.getProfilesList();
Does the ArrayList named list from last code sample now contain those previously created data?
If not, how can be something like that achieved? do I need use soma databases or something?
I want to use it to process ArrayList between different activities in android.
Thankyou!

If you want to access data from different parts of your app, I would suggest you use SharedPreferences. More information on this can be found here. SharedPreferences are more useful for key-value pairs, however.
In your case, an SQLite database would be more useful. See here. You would create an SQLite table that contains columns for each of your object's fields. For example, a table with columns named AppName, PackageName, etc.
You could simply pass the ArrayList to different parts of your app as an argument, but if you begin dealing with multiple lists, this can be cumbersome and ineffective. The SQLite database will be much more efficient as your app grows.

The "new" keyword creates a new instance of the object (in this case, being a collection, an empty one).
If you want to access the same instance you created before, you need to "pass" it to the point where it's needed. Say that your usage code is wrapped in a function:
void doSomething(ProfilesList profList) {
ArrayList<AppListModel> list = new ArrayList<AppListModel>();
list = profList.getProfilesList();
//do something with list...
}
Then you can call this code by doing something like:
AppListModel appList = new AppListModel();
appList.setAppName("ssss");
appList.setPackageName("ddddd");
ProfilesList list = new ProfilesList();
list.addProfilesList(appList);
doSomething(list);

The list you make here:
AppListModel appList = new AppListModel();
appList.setAppName("ssss");
appList.setPackageName("ddddd");
ProfilesList list = new ProfilesList();
list.addProfilesList(appList);
Won't be the same as the list here:
ArrayList<AppListModel> list = new ArrayList<AppListModel>();
ProfilesList profList = new ProfilesList();
list = profList.getProfilesList();
Anytime you make a new ProfilesList() it is not the same as any other.
public void anyMethod() {
//list1 is not the same as list2
ArrayList<AppListModel> list1 = new ArrayList<AppListModel>();
ArrayList<AppListModel> list2 = new ArrayList<AppListModel>();
//list3 will be same as list1
ArrayList<AppListModel> list3 = list1;
//adding an AppListModel to list1
AppListModel appList = new AppListModel();
list1.add(appList);
list1.getProfilesList().isEmpty(); //false because it has appList
list2.getProfilesList().isEmpty(); //true
list3.getProfilesList().isEmpty(); //false because it refers to list1 which has appList
}
The above shows the difference between the ArrayLists.

"new" will always create a new instance of the wanted object.
You want to look up SQLite. It's how you store data in android. http://developer.android.com/training/basics/data-storage/databases.html
Once it's saved on your local phone's database you can retrieve data whenever you want and add it to wanted array lists. However, any changes to the data needs to be committed to the database again for it to be stored permanently.

Does the ArrayList named list from last code sample contain those previously created data?
If you use this code:
ProfilesList profList = new ProfilesList();
ArrayList<AppListModel> list = profList.getProfilesList()
You will not get any previously saved data as you have created a new instance of a ProfilesList object. You'd need to use the same instance to get the data back
ProfilesList profList = new ProfilesList();
profList.addProfilesList(...);
//...
//This would then return the correct data
ArrayList<AppListModel> list = profList.getProfilesList();
I would suggest using a SQLite database if you require more persistent storage

Related

Creating ArrayList of objects containing ArrayLists as parameters - my code does not seem to create individual ArrayLists?

I am running into problem with a code for a text-based game. My class Locations is meant to load parameters from a "config" text file to create objects.
My current approach is:
I have created a public class with a constructor that will take the parameters of the object (location). It assigns them as this.xxx to private variables.
I have also created a public static class that parses the file, and once it has the necessary amount of parameters to create an object, it creates one by passing them to the constructor. Next, it adds that object to an ArrayList locations_list. Once all location objects were generated, the class returns the ArrayList locations_list
My static class parses the text file OK. However, when I run a test which iterates through locations_list and calls the getters for each element, the ArrayList parameters of objects are not individualized. All of the ArrayList elements return the same locations_characters.
The location_characters of all objects will have the same content, which is a list containing "characters" of all locations.
For example, if location 1 has characters 2 and 3 and location 2 has 6 and 7, my location_characters will print [2,3,6,7].
If I put a location_characters.clear(); after adding to location_list, the location_characters becomes empty for all objects.
Sample code snippets:
Public class with a constructor:
public class Locations {
private final int location_id;
private final String location_name;
private final String location_description;
private ArrayList <Integer> location_characters;
private ArrayList <Integer> location_items;
private final ArrayList <Integer> location_enter_from;
private final ArrayList <Integer> location_exit_to;
private String location_stage_name;
private final int location_stages;
private final ArrayList <String> location_stage_descriptions;
public Locations(int location_id,
String location_name,
String location_description,
ArrayList <Integer> location_characters,
ArrayList <Integer> location_items,
ArrayList <Integer> location_enter_from,
ArrayList <Integer> location_exit_to,
String location_stage_name,
int location_stages,
ArrayList <String> location_stage_descriptions) {
this.location_id = location_id;
this.location_name = location_name;
this.location_description = location_description;
this.location_characters = location_characters;
this.location_items = location_items;
this.location_enter_from = location_enter_from;
this.location_exit_to = location_exit_to;
this.location_stages = location_stages;
this.location_stage_descriptions = location_stage_descriptions;
}
... below are getters/setters....
Public static class for the loader:
public static ArrayList <Locations> load_locations() {
//These are used for parsing the text file
String line;
ArrayList <String> lines = new ArrayList<>();
//These are used to initialize local variables
int location_id = 0;
String location_name = null;
String location_description = null;
ArrayList<Integer> location_characters = new ArrayList<>();
ArrayList<Integer> location_items = new ArrayList<>();
ArrayList<Integer> location_enter_from = new ArrayList<>();
ArrayList<Integer> location_exit_to = new ArrayList<>();
String location_stage_name = null;
int location_stages = 0;
ArrayList<String> location_stage_descriptions = new ArrayList<>();
//This is used to initialize ArrayList of objects
ArrayList <Locations> location_list = new ArrayList<>();
//here goes the code for parsing the text files....
//below is a sample portion that loads i.e 2,3,4 split into ints,
//into the ArrayList location_characters....
case "location_characters":
String[] characters = values[1].split(",");
for (String character : characters) {
location_characters.add(Integer.parseInt(character));
}
i++;
break;
//continued...
//below I am passing the parameters into constructor,
//then adding the object to ArrayList location_list
}
Locations location = new Locations(location_id,
location_name,
location_description,
location_characters,
location_items,
location_enter_from,
location_exit_to,
location_stage_name,
location_stages,
location_stage_descriptions);
location_list.add(location);
i = 0;
}
}
reader.close();
}
catch (IOException e){
System.out.println("Problem reading file.");
}
return location_list;
}
I will appreciate insight and pointers to solution
Your code is incomplete, and the problem is in the code you're not showing: You're passing the same lists to all constructor calls, so all Locations objects are using the same lists for their fields.
This can be fixed by initializing Locations fields at their declarations, eg:
private List<Integer> location_characters = new ArrayList<>();
// repeat this pattern for all List fields
and not passing them lists through the constructor.
If you need to add to the list:
locationsInstance.getlocation_characters().add(foo);

Drools: Compare 2 Arraylists from the same Object

I have a Class and this Class constructs 7 ArrayLists:
public class Fruchtplanungsmodul {
private ArrayList<Crops> fruchtliste1F;
private ArrayList<Crops> fruchtliste2F;
private ArrayList<Crops> fruchtliste3F;
private ArrayList<Crops> fruchtliste4F;
private ArrayList<Crops> fruchtliste5F;
private ArrayList<Crops> fruchtliste6F;
private ArrayList<Crops> fruchtliste7F;
// Constructor
public Fruchtplanungsmodul() {
fruchtliste1F = new ArrayList<>();
fruchtliste2F = new ArrayList<>();
fruchtliste3F = new ArrayList<>();
fruchtliste4F = new ArrayList<>();
fruchtliste5F = new ArrayList<>();
fruchtliste6F = new ArrayList<>();
fruchtliste7F = new ArrayList<>();
}
functions for deleting Objects....
}
And I want to load Objects in this list with Drools-rules.
I do load the same Objecttyps into all Arraylists. For example, in this rule, I load 4 Objects Crops into the first ArrayList.
rule "Körnerlegmunosen: Planung erste Feldrigkeit"
when
//$grund: Grundbedingung(grundbedingung == 1)
$feld: Feldrigkeit(feldrigkeit1 == "Körnerleguminosen")
$m: Fruchtplanungsmodul()
then
Crops erbse = new Crops("Erbse", "Koernerleguminose","BF", "Hafer", "Silomais", "Sommerung", 6);
Crops ackerbohne = new Crops("Ackerbohne" , "Koernerleguminose", "BF", "Silomais", "Wintergerste", "Sommerung", 4);
Crops lupine = new Crops("Lupine", "Koernerleguminose", "BF", "Späte Kartoffel", "Winterroggen", "Sommerung", 4);
Crops sojabohne = new Crops("Sojabohne", "Koernerleguminose", "BF", "Futterrübe", "winterroggen", "Sommerung", 3);
insert(erbse);
insert(ackerbohne);
insert(lupine);
insert(sojabohne);
$m.addFrucht1(erbse);
$m.addFrucht1(ackerbohne);
$m.addFrucht1(lupine);
$m.addFrucht1(sojabohne);
end
In other rules, I load different Crops into other ArrayLists from the Class Fruchtplanungsmodul().
My Question is: Is there any way to compare Objects from different ArrayLists?
For example, ArrayList "fruchtliste2F" has 4 objects from the type Crops and the ArrayList "fruchtliste3F" also has 4 objects from the type Crops. Now I need to check with a rule if there is one Object with the same Name in both ArrayLists. If this is true, the rule should delete the object from the second list.
Thanks for your help!
Philipp
If the arrays you want to check are fixed (i.e. you always want to check array #2 with array #3), then you can do something like this:
rule "Delete duplicated"
when
$f: Fruchtplanungsmodul()
$c1: Crop() from $f.fruchtliste2F
$c2: Crop(name == $c1.name) from $f.fruchtliste3F
then
//If you want to remove the fact you have inserted too:
delete($c2);
//Remove the object from the array
$f.deleteFrucht3($c2);
end
If you want to check all the arrays, then you either create copies of the rule above, or create a way your java class to access the arrays by an index and create a generic rule to compare them all.
Hope it helps,

Convert a List of objects to a String array

I have the below pojo which consists of the below members so below is the pojo with few members in it
public class TnvoicetNotify {
private List<TvNotifyContact> toMap = new ArrayList<TvNotifyContact>();
private List<TvNotifyContact> ccMap = new ArrayList<TvNotifyContact>();
}
now in some other class i am getting the object of above class TnvoicetNotify in a method signature as parameter as shown below .. So i want to write the code of extraction from list and storing them in string array within this method itself
public void InvPostPayNotification(TnvoicetNotify TnvoicetNotify)
{
String[] mailTo = it should contain all the contents of list named toMap
String[] mailCC = it should contain all the contents of list named ccMap
}
now in the above class i need to extract the toMap which is of type list in the above pojo named TnvoicetNotify and i want to store each item if arraylist in a string array as shown in below fashion
for example first item in list is A1 and second is A2 and third is A3
so it should be stored in string array as
String[] mailTo = {"A1","A2","A3"};
similarly i want to achieve the same for cc section also as in above pojo it is in list i want to store in the below fashion
String[] mailCc = {"C1","C2","C3"};
so pls advise how to achieve this within InvPostPayNotification method
Pseudo code, because I don't know details for TnvoicetNotify:
public void invPostPayNotification(final TnvoicetNotify tnvoicetNotify)
{
final List<String> mailToList = new ArrayList<>();
for (final TvNotifyContact tv : tnvoicetNotify.getToMap()) { // To replace: getToMap()
mailToList.add(tv.getEmail()); // To replace: getEmail()
}
final String[] mailTo = mailToList.toArray(new String[mailToList.size()])
// same for mailCc then use both arrays
}
If you are using Java 8, you could simply use a one liner :
String[] mailCC = ccMap.stream().map(TvNotifyContact::getEmail).toArray(String[]::new);

Appending my sessionId to an arrayList

Each time a new session id is created i need to save them in an array or a list, to have it as a reference.
Correct me where am i wrong
public static void main(String args[]) {
//creating an arrayList
ArrayList<String> myList = new ArrayList<String>();
try {
// calculate the sessionId
String sessionId = "b03c0-000-5h6-" + uuid.substring(0,4) + "-000000000";
myList.add(sessionId);
} catch(Exception e){
e.printStackTrace();
}
}
the elements in my arrayList are getting replaced and not appended.
Where am i wrong
You are wrong.
The List interface is designed store the values with duplicates. So you will append. If you want only unique results use Set instead.
Collection<String> myList = new HashSet<String>();
Note that List and Set are math concepts that both represent collections. In Java Collection Framework those concepts ware reproduces as classes and interfaces.
The Collection<T> is the super interfaces of Set and List. This allow you to change the behavior of your program depending on implementation.
You should also avoid using class names in variables, to have that flexibility.
If you want to "tell" other developers that the session ids storage store only unique values use
Set<String> sessionsIDs = new HashSet<String>();
If you want to "tell", that storage is in form of list (that allow repetitions) use
List<String> sessionsIDs = new ArrayList<String>();
If you want to keep that detail of implementation hidden, use collection
Collection<String> sessionsID = crateSessionStorage();
private Collection<String> crateSessionStorage() {
boolean useUniqueStorage = isUniqueStorage();
if(UseUniqueStorage) {
return new HashSet<String>();
}
return new ArrayList<String>();
}
The creation/initialization of myList in your code results to undesired behavior.
Your ArrayList can be a static instance attribute of your class instead of getting created everytime the method is invoked.
String sessionId = "b03c0-000-5h6-" + uuid.substring(0,4) + "-000000000"; myList.add(sessionId); this put in loop other when you call main() it replace full arraylis
It is happening because you are creating every time new object
ArrayList<String> myList = new ArrayList<String>(); // creates an object evrytime whem main will be called.
try {
String sessionId = "b03c0-000-5h6-" + uuid.substring(0,4)
/* from where uuid is comming?? */
+ "-000000000";
myList.add(sessionId);
// thiss will add inside new arraylist not in previous,
// because everytime it is getting new object reference
} catch(Exception e){
e.printStackTrace();
}
}

How to use List<Data> in android?

How should I use List<Data> dat = new List<Data>(); to temporary store data in my software? "Data" is a class in my code with variables(mainly Strings). When I try that method it doesn't store data.
List is an interface, so you can't instantiate it (call new List()) as it does not have a concrete implementation. To keep it simple, use one of the existing implementations, for example:
List<Data> dat = new ArrayList<Data>();
You can then use it like this:
Data data = new Data();
//initialise data here
dat.add(data);
You would probably benefit from reading the Java Tutorial on Collections.
List<Data> lsData = new ArrayList<Data>();
for(int i=0;i<5;i++)
{
Data d = new Data();
d.fname="fname";
d.lname="lname";
lsData.add(d);
}
Your Data class (Always make a Bean class to manage data)
public class Data
{
public Data()
{
}
public String fname,lname;
}
you can also get your data of particular position
String fname = lsData.get(2).fname;
String lname = lsData.get(2).lname;

Categories