How to use List<Data> in android? - java

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;

Related

Serialize list of objects, keyed by attribute

Say I have a class:
public class Person {
String name;
Int age;
}
and a list of objects of this class:
List<Person> people = ...
Normally, running this through a serializer such as Jackson or Gson would result in this:
"[{'name':'John','age':42},{'name':'Sam','age':43}]
but I am looking to serialize to a single json object where each property is a list containing the attributes, like this:
"{'name':['John','Sam'],'age':[42,43]}"
Do any of the serialization libraries support this?
I'd create a sort of "wrapper" that takes in any amount of persons and stores the fields in a way that let them be serialized that way. So in this case, you would create a series of persons, create a wrapper containing those persons and then serialize that.
public class PersonWrapper {
private int[] ages;
private String[] names;
public PersonWrapper(Person... persons) {
ages = new int[persons.length];
names = new String[persons.length];
for (int i = 0; i < persons.length; i++) {
ages[i] = persons[i].getAge();
names[i] = persons[i].getName();
}
}
}
Transform your List<Person> to new object.
class NewClass {
List<String> name;
List<Integer> ages;
}
Then pass this object through the Serializer to get:
"{'name':['John','Sam'],'age':[42,43]}"
Serialization libraries are generally not designed for stuff like that.
What you're looking for is JSON tree transformation and you can easily implement it in both Gson and Jackson.
Here is a transformation example for Gson:
final class Transformations {
private Transformations() {
}
static JsonObject transposeShallow(final Iterable<? extends JsonElement> inArray) {
final JsonObject outObject = new JsonObject();
for ( final String name : scanAllNames(inArray) ) {
final JsonArray outSubArray = new JsonArray();
for ( final JsonElement inJsonElement : inArray ) {
if ( !inJsonElement.isJsonObject() ) {
throw new IllegalArgumentException(inJsonElement + " is not a JSON object");
}
outSubArray.add(inJsonElement.getAsJsonObject().get(name));
}
outObject.add(name, outSubArray);
}
return outObject;
}
private static Iterable<String> scanAllNames(final Iterable<? extends JsonElement> jsonArray) {
final ImmutableSet.Builder<String> allNames = new ImmutableSet.Builder<>();
for ( final JsonElement jsonElement : jsonArray ) {
if ( !jsonElement.isJsonObject() ) {
throw new IllegalArgumentException(jsonElement + " is not a JSON object");
}
allNames.addAll(jsonElement.getAsJsonObject().keySet());
}
return allNames.build();
}
}
The transformations above can be incorporated into serialization process, but this would affect the structure for your objects (e.g. how to indicate transposable collections for root objects and their fields? how to introduce a new "transposing" type and incorporate it in your data model type system? how to deserialize it properly if necessary?).
Once you get a JSON tree, you can transpose it on any nesting level.
Transposing the root element is the simplest way as long as you don't need to transform nested elements.
private static final Type peopleType = new TypeToken<Collection<Person>>() {}.getType();
public static void main(final String... args) {
System.out.println(gson.toJson(people, peopleType));
System.out.println(gson.toJson(Transformations.transposeShallow(gson.toJsonTree(people, peopleType).getAsJsonArray())));
}
that gives:
[{"name":"John","age":42},{"name":"Sam","age":43}]
{"name":["John","Sam"],"age":[42,43]}
The solution above can work with almost any types in your code, but is has a small penalty for building a JSON tree.
Something like PersonWrapper as suggested by Schred might be another option but this requires wrappers for all your types and they need to be updated once your wrapped classes change.
Also, you might also be interested in libraries like Jolt that are designed for JSON transformations (not sure if it's doable in Jolt though).

Create for element of a CSV a List in Java

I have a question regarding csv and java.
I have a csv file with a lot of data. There are for example three different ids, and per id around 5k data points.
The csv is like following:
ID, Data1(String), Data2(Long), Data3(Float), Data4(Float), Data5(Float)
I read the csv an store every column to another linked list, so that for ever linked list the index i is one row.
What I want to do is to have a per ID a list of the data.
I have done it so far like this:
LinkedList<String> new_id = new LinkedList();
LinkedList<String> new_data1 = new LinkedList();
LinkedList<String> new_data2 = new LinkedList();
....
....
for(int i = 0; i < id.size(); i++){
if(id.get(i).equals(String theidiwant){
new_id.add(id.get(i));
new_data1.add(data1.get(i));
....
....
}
So my question would be whether there is a simple solution to create for each id a list of those data.
I hope you understand what I am trying to ask.
Sorry for that complicated description.
Cheers!
You should start of by creating a class for the rows and have an object representing one row e.g.
public class Row{
public String id;
public String data1;
public long data2;
public float data3;
public float data4;
public float data5;
public Row(String id, String data1, long data2, float data3, float data4, float data5) {
//Enter constructor here e.g. this.id = id...
}
}
You can then filter the objects into a list with
... after parsing the data into List<Row> data;
List<Row> filteredList = data.stream().filter(
row -> row.id.equals(String theidiwant))
.collect(Collectors.toCollection(LinkedList::new));
If you want one list per id you can as SpaceCowboy said and create a map with lists
Map<String, List<Row>> mappedValues = new HashMap<>();
for(Row row : data) {
if(mappedValues.containsKey(row.id) {
List<Row> values = mappedValues.get(row.id)
values.add(row)
}
else {
List<Row> newValues = new ArrayList<>();
newValues.add(row)
mappedValues.put(row.id, newValues);
}
}
I am not sure why you want to create list of columns, list of rows make much more sense. Although, using java class to map the columns and creating a list of rows will be most appropriate.
You might want to try out using a Map.
Map<Integer, List<String>> myMap = new HashMap<Integer, List<String>>();
LinkedList<String> data = new LinkedList<>();
myMap.put([your_key],data);
You can then access the list with the id's like this:
if (myMap.containsKey([your_key])) {
List<String> list = myMap.get([your_key]);
}

How to create a DataFrame from a RDD containing list objects?

I would like to know if it is possible to create a DataFrame from a JavaRDD that contains Classes with a single List.
E.g. create a dataframe for RDDs containing objects of following class DataRecord:
public class DataRecord implements Serializable{
private List<Object> values;
public DataRecord(List<Object> values){
this.values = values;
}
}
Following the idea (not working)
JavaRDD<String> rdd= sc.textFile("hdfs//...").
.map( new Function<String, DataRecord>(){
#Override
public DataRecord call(String line) throws Exception{
String[] fields = line.split(",");
List<Object> values = new ArrayList<Object>();
for(int i=0; i<fields.length; i++){
values.add(field[i]);
}
return new DataRecord(values);
});
DataFrame schemaLogMessages = sqlContext.createDataFrame(rdd, DataRecord.class); //Does not work
schemaLogMessages.registerTempTable("rdd");
DataFrame df = sqlContext.sql("SELECT * FROM rdd");
Basically im looking for a generic approach to read any comma separated file and creating a dataframe out of it. So it does not necessarily have to be a list, but since the columns can vary I think that we need a list.
Regards

Saving data in ArrayList of objects

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

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);

Categories