How to convert multiple string into arraylist? - java

I m new in android.I want to add these String variables to ArrayList, what I am doing now.
Suppose I have a four of String Variables.....
String number = "9876543211";
String type = "incoming";
String date = "1/1/2016";
String duration = "45 sec";
Here is my java code.......
while (managedCursor.moveToNext()) {
String number = managedCursor.getString(number1);
String type2 = managedCursor.getString(type1);
String date = managedCursor.getString(managedCursor.getColumnIndexOrThrow("date")).toString();
java.util.Date date1 = new java.util.Date(Long.valueOf(date));
String duration = managedCursor.getString(duration1);
String type = null;
String fDate = date1.toString();
int callcode = Integer.parseInt(type2);
sb.append("\nPhone Number:--- " + number + "");
sb.append(" \nCall Type:--- " + type + " ");
sb.append("\nCall Date:--- " + fDate + "");
sb.append("\nCall duration in sec :--- " + duration);
sb.append("\n----------------------------------");
}

As 4castle suggest, you should really have a custom class - which looking at the properties you are interested in, you might want to name "CallLogEntry" and then have properties for this class. Here is an example of such a custom class.
public class CallLogEntry {
String number;
String type;
String date;
String duration; //this should ideally be of type Long (milliseconds)
public CallLogEntry(){
//do stuff if necessary for no-params constructor
}
public CallLogEntry(String number, String type, String date, String duration){
this.number = number;
this.type = type;
this.date = date;
this.duration = duration;
}
//getters and setters go here..
getNumber(){ return this.number;}
setNumber(String number){ this.number = number;}
//...the rest of them...
}
Than it makes more sense to have an ArrayList of CallHistoryEntry items like this:
//...declare list of call-log-entries:
List<CallLogEntry> callLogEntryList = new ArrayList<CallLogEntry>();
//...add entries
CallLogEntry entry = new CallLogEntry(number, type, date, duration);
callLogEntryList.add(entry);
The advantage of doing it like this, especially in an Android app, is that later you may pass this list to some list-adapter for a list-view.
I hope this helps.

Create JavaBean Class as follows
public class DataBean {
String number;
String type;
String date;
String duration;
public DataBean(String number, String type, String date, String duration) {
this.number = number;
this.type = type;
this.date = date;
this.duration = duration;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
}
Now create Arryalist as follows
ArrayList<DataBean> dataBeanList = new ArrayList<>();
DataBean dataBean=new DataBean(number,type,date,duration);
dataBeanList.add(dataBean);//added bean object arrylist
For Retrieving data do as follow
// iterate through arraylist as follows
for(DataBeand d: dataBeanList ){
if(d.getName() != null && d.getDate()!=null)
//something here
}

Related

Null Pointer Exception in creating an instance [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I have an exception and I don't know how to solve it.
Person a = new Person();
Scanner in = new Scanner(System.in);
System.out.println("Please type name: ");
String name = in.nextLine();
It says there's an exception in the first line.
The following code is the default constructor.
Person(){
this.name = "No_Name";
this.surname = "No_Surname";
this.number = "No_Number";
this.personalCode = "No_personalCode";
this.dateOfBirth.set(Calendar.DAY_OF_MONTH, 1);
this.dateOfBirth.set(Calendar.MONTH, Calendar.JANUARY);
this.dateOfBirth.set(Calendar.YEAR, 1900);
}
Class person full code:
import java.util.Calendar;
public class Person {
String name;
String surname;
private String number;
private String personalCode;
private Calendar dateOfBirth;
Person(){
this.name = "No_Name";
this.surname = "No_Surname";
this.number = "No_Number";
this.personalCode = "No_personalCode";
this.dateOfBirth.set(Calendar.DAY_OF_MONTH, 1);
this.dateOfBirth.set(Calendar.MONTH, Calendar.JANUARY);
this.dateOfBirth.set(Calendar.YEAR, 1900);
}
Person(String name,String surname,String number,String personalCode,Calendar dateOfBirth){
this.name = name;
this.surname = surname;
this.number = number;
this.personalCode = personalCode;
this.dateOfBirth = (Calendar) dateOfBirth.clone();
}
Person setName(Person a, String name) {
a.name = name;
return a;
}
Person setSurname(Person a, String surname) {
a.surname = surname;
return a;
}
Person setNumber(Person a, String number) {
a.number = number;
return a;
}
Person setpersonalCode(Person a, String personalCode) {
a.personalCode = personalCode;
return a;
}
String getName(Person a) {
return a.name;
}
String getSurname(Person a) {
return a.surname;
}
String getNumber(Person a) {
return a.number;
}
String getPersonalCode(Person a) {
return a.personalCode;
}
Calendar getDateOfBirth(Person a) {
return a.dateOfBirth;
}
}
You are calling set() on a null field (dateOfBirth).
A possibile workaround:
Date date = new GregorianCalendar(1900, Calendar.FEBRUARY, 1).getTime();
this.dateOfBirth = date;

Compare long of Object in ArrayList

I'm trying to check if my arraylist has an object with long name with the following code:
public static boolean containsName(Collection<MyObject> c, long name) {
for(MyObject o : c) {
if(o != null && o.getName() == name) { //name is a long
return true;
}
}
return false;
}
MyObject:
public class MyObject extends SugarRecord {
Long fk_id_specs;
String url;
String timestamp;
int status;
int time;
public MyObject(Long fk_id_specs, String url, String timestamp,int status,int time) {
this.fk_id_specs = fk_id_specs;
this.url = url;
this.timestamp = timestamp;
this.status = status;
this.time = time;
}
I'm getting the collection from the database by a libary with:
List<MyObject> sp = MyObject.listAll(MyObject.class);
The list is filled properly, already checked that.
The problem is: it's always returning false, any suggestions?
Assuming that o.getName() is a String. You must compare Strings like this:
String o_name = o.getName();
String str_name = String.valueOf(name); // Convert the long to String
boolean is_equal = o_name.equals(str_name);

Why is useDelimiter not working java

So I my program reads a .txt file and I am using .useDelimeter to seperate the pets and put them in an arraylist:
try{
Scanner petReader = new Scanner(new File("pet3-dogs.txt"));
petReader.useDelimiter(",");
String line2 = petReader.nextLine();
while(petReader.hasNextLine()){ //the while loop stores each attribute in the appropriate variable and arraylist of petshops while there's another line.
petReader.useDelimiter(",");
String shop =petReader.next();
String type =petReader.next();
double price = Double.parseDouble(petReader.next());
Date date = df.parse(petReader.next());
String notes =petReader.nextLine();
String size =petReader.nextLine();
String neutered =petReader.nextLine();
petReader.useDelimiter(",");
pets.add(new Pet(shop, type, price, date, notes, size, neutered));
System.out.println(pets.toString());
}
} catch(Exception e){
JOptionPane.showMessageDialog(null, e); //if the program wasn't able to read the file, it will display a message dialog.
}
This is the output. Infact it gets the next petshops in the last two variables:
[Solly's Pet Store
Giant Schnauzer
£176.43
Wed Jul 07 00:00:00 BST 2010
,none,Medium,no
The Menagerie,Neapolitan Mastiff,293.73,29/08/2010,none,Medium,no
Obsborne Road Pet Store,Basenji,224.27,13/10/2010,none,Large,yes
]
My expected output is
Solly's Pet Store
Giant Schnauzer
£176.43
Wed Jul 07 00:00:00 BST 2010
none
Medium
no.
This is my Pet class:
public class Pet {
private String shop;
private String type;
private double price;
private Date dateAquired;
private String notes;
private String size;
private String neutered;
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public String getNeutered() {
return neutered;
}
public void setNeutered(String neutered) {
this.neutered = neutered;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public String getShop() {
return shop;
}
public void setShop(String shop) {
this.shop = shop;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public Date getDateAquired() {
return dateAquired;
}
public void setDateAquired(Date dateAquired) {
this.dateAquired = dateAquired;
}
public Pet(String pShop, double pPrice){
this.shop = pShop;
this.price = pPrice;
}
public Pet(String pShop, String pType, double pPrice, Date pDateAcquired, String pNotes, String pSize, String pNeutered){
this.shop = pShop;
this.type = pType;
this.price = pPrice;
this.dateAquired = pDateAcquired;
this.notes = pNotes;
this.size = pSize;
this.neutered = pNeutered;
}
#Override
public String toString(){
return getShop()+"\n"
+getType()+"\n"
+"£"+getPrice()+"\n"
+getDateAquired()+"\n"
+getNotes()+"\n"
+getSize()+"\n"
+getNeutered()+"\n";
}
}
This is the file it is reading from.
When you do:
String notes =petReader.nextLine();
It reads the whole line until it encounters \n, which contains the String:
,none,Medium,no
The rest of the line has been already read.
Then, in the next two lines, you again use nextLine(), and so, it again reads complete lines, and hence you get that output.
You must use:
String notes =petReader.next();
String size =petReader.next();
String neutered =petReader.next();

find highest of each type from Map in java

I am creating the ArrayList of Object, to insert information I use different constructors in that class but I have one type variable that I update with every constructor call. here is what i am doing
public class eProperty {
public String type = null;
public int marks;
public int code;
public String category
public String student_name = null;
public String employee_name = null;
public String o_name = null;
public eProperty(String type, String student_name, int marks) {
this.marks = marks;
this.type = type;
this.student_name = student_marks;
}
public eProperty(String type, String employee_name, int makrs, String category) {
this.marks = marks;
this.type = type;
this.employee_name = employee_name;
this.category = category;
}
public eProperty(String type, int code, int makrs, String o_name) {
this.marks = marks;
this.type = type;
this.mnc = code;
this.o_name = o_name;
}
}
I populate arraylist like this,
ArrayList<eProperty> allData;
eProperty data;
if(type.equals("Student")) {
data = new eProperty(type, "John", 45)
allData.add(data)
}
if(type.equals("Employee")){
data = new eProperty(type, "Vicky", 86, "Developer")
allData.add(data)
} ... other cases also handled like this
Now I want to retrive highest marks for each type and I am stuck here, any help
Thanks
Using loop (sorry for that...) and Predicate from Apache Commons
public static int getHighestMarkByType(ArrayList<eProperty> allData, String type) {
Predicate predicate = new Predicate() {
public boolean evaluate(Object data) {
if ((eProperty) data).getType().equals(type)) {
return true;
} else {
return false;
}
}
};
ArrayList<eProperty> filteredData = (ArrayList<eProperty>) CollectionUtils.select(allData,predicate);
int maxMarks = 0;
for (eProperty data : filteredData) {
if (data.getMarks() > maxMark) {
maxMarks = data.getMark();
}
}
return maxMarks;
}

Which utility class can be used to store and apply sort in Java

I'm a bit confused that which of the utility classes can be used for this type of problem:
I have a file Movies.txt containing info like: Id, Name, Director, Rating. Rating may or may not be present.
Sample:
1,ABC,Mr. xyz,4.5
3,GHI,Mr. mno
2,DEF,Ms. stu,3
I need to read and store this file to the memory and then apply sort by rating as well as by name and then write to the file later on.
Which utility class can best help me in this situation, so that it can be an ease to do this if possible. No more files to be used.
Start by defining a Object that describes the basic properties of a "Movie". Take make your life easier, it might be a good idea to implement Comparable<Movie> directly.
public class Movie implements Comparable<Movie> {
private int id;
private String name;
private String directory;
private double rating;
public Movie(int id, String name, String directory, double rating) {
this.id = id;
this.name = name;
this.directory = directory;
this.rating = rating;
}
public int getId() {
return id;
}
public String getDirectory() {
return directory;
}
public String getName() {
return name;
}
public double getRating() {
return rating;
}
#Override
public int compareTo(Movie o) {
int diff = (int) asInt(getRating()) - asInt(o.getRating());
if (diff == 0) {
diff = getName().compareTo(name);
}
return diff;
}
protected int asInt(double value) {
String text = Double.toString(value);
text = text.replaceAll("\\.", "");
return Integer.parseInt(text);
}
#Override
public String toString() {
return getId() + ", " + getName() + ", " + getDirectory() + ", " + getRating();
}
}
Create a List to hold the incoming movies
List<Movie> movies = new ArrayList<Movie>(25);
Read the contents of the and parse each line into their separate property elements (I'll leave that you), add each newly create Movie to the list...
movies.add(new Movie(...));
Use Collections.sort(movies) to sort them...
For example...
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class SortExample {
public static void main(String[] args) {
List<Movie> movies = new ArrayList<Movie>(5);
movies.add(new Movie(1, "ABC", "Mr. xyz", 4.5));
movies.add(new Movie(2, "GHI", "Mr. mno", 0));
movies.add(new Movie(3, "DEF", "Ms. stu", 3));
movies.add(new Movie(4, "AT1", "Mr. T", 3));
System.out.println("Before....");
for (Movie movie : movies) {
System.out.println(movie);
}
Collections.sort(movies);
System.out.println("After....");
for (Movie movie : movies) {
System.out.println(movie);
}
}
public static class Movie implements Comparable<Movie> {
private int id;
private String name;
private String directory;
private double rating;
public Movie(int id, String name, String directory, double rating) {
this.id = id;
this.name = name;
this.directory = directory;
this.rating = rating;
}
public int getId() {
return id;
}
public String getDirectory() {
return directory;
}
public String getName() {
return name;
}
public double getRating() {
return rating;
}
#Override
public int compareTo(Movie o) {
int diff = (int) asInt(getRating()) - asInt(o.getRating());
if (diff == 0) {
diff = getName().compareTo(name);
}
return diff;
}
protected int asInt(double value) {
String text = Double.toString(value);
text = text.replaceAll("\\.", "");
return Integer.parseInt(text);
}
#Override
public String toString() {
return getId() + ", " + getName() + ", " + getDirectory() + ", " + getRating();
}
}
}
You need to read this input file one line at a time, parse each line by splitting at ',', constructing a Movie object (that you define) and adding to some kind of array / map / set. Then sort your array / map / set according to the instructions, and write out the response file.
Do some research into:
reading lines from files
parsing strings using split
lists, maps
sorting (compare)
OK, an answer has been accepted, but I have the right not to have the same opinion.
Comparable should reflect the relationship between 2 objects based on their entire state(of course, ids and other irrelevant fields are skipped). If you want to order some objects by their partial state(a few fields) you should use a Comparator.

Categories