I have created the class:
public playlists(int ID, String nam, int lengt, int movi) {
// TODO Auto-generated constructor stub
playlistID = ID;
name = nam;
length = lengt;
movieID = movi;
}
The data-field movieID of object playlists needs to store multiple values. I was wondering how I could do this.
As some comments already say: Use an ArrayList or an Array
Use ArrayList to store as many objects as you wish (theoretically)
Use Array if you know the exact number ob objects you want to store
ArrayList<Integer> musicIDs= new ArrayList();
public playlists(int ID, String nam, int lengt, int movi) {
// TODO Auto-generated constructor stub
playlistID = ID;
name = nam;
length = lengt;
movieIDs.add(movi);
}
My codeblock just makes sense if you add some musicids later on to this class.
If you create a new instance of this class and still want all musicids you should use static:
static ArrayList<Integer>...
EDIT:
Thats how i would do it :
public class Main()
{
private Playlist playlist = new Playlist();
public void main(String[] args)
{
MovieInf omi = new MovieInfo(1,"a",2,3);
playlist.add(mi);
mi = new MovieInfo(2,"b",3,4);
playlist.add(mi);
System.out.println(Playlist.getSizeOfList()); // prints "2"
}
}
public class MovieInfo()
{
private int ID,length,movi;
private String name;
public MovieInfo(int ID, String nam, int lengt, int movi) {
this.ID= ID;
this.name= name;
this.length= length;
this.movi= movi;
}
}
public class Playlist()
{
private ArrayList<MovieInfo> movies = new ArrayList();
public void add(MovieInfo mi)
{
movies.add(mi);
}
public int getSizeOfList()
{
return movies.size();
}
}
Related
I wanted to create an employeeID automatically whenever I create a new employee object. I am implementing OOP concept for my assignment. My problem is I wanted to use getter and setter to create for the id. However, since the id should be generated automatically so I can't put any value for the parameter when creating instance. How can I solve this?
private String employeeID;
public void setEmployeeID(String employeeID){
Random rand = new Random();
int randint = rand.nextInt(100000);
char subId = 'E';
employeeID = subId + String.valueOf(randint);
this.employeeID = employeeID;
}
public String getEmployeeID(){
return employeeID;
}
To keep it simple:
You need or want to use public void setEmployeeId(String id) and its a basic requirement.
But if so, the idea of having such a method means that the class Employee should have any logic of id generation, instead by declaring such a method you say to the programmer that will use the Employee class: "Look, this class doesn't have an id, but you can create it and set".
If these are your intentions, then extract the logic of the id generation outside the employee class and use the "pure" setter:
main:
String id = generateId(...) // in this method there will be all the code with Random
Employee emp = new Employee();
emp.setId(id);
.....
class Employee {
private String id;
public void setId(String id) {this.id = id;}
}
Otherwise, if you do think that the Employee should generate an id by its own, you don't need a setter. In this case you can either call the generation code in constructor (not really recommended, but will work) or create an "init" method that will set the initial state of id to the employee object. In this case, whoever creates an Employee, will have to call this method:
public class Employee {
private String employeeId;
public class Employee(...) {...}
public void init() {
setupId();
}
private void generateEmpId() {
Random rand = new Random();
int randint = rand.nextInt(100000);
char subId = 'E';
employeeID = subId + String.valueOf(randint);
this.employeeID = employeeID;
}
}
Then in the main:
main:
Employee e = new Employee();
e.init(); // otherwise id won't be generated
This is not really convenient because whoever uses creates the Employee object will have to call init on it. In this case you might consider a factory method:
public class Employee {
private final String name;
private String empId;
private Employee(String name) {
this.name = name;
}
public static Employee create(String name) {
Employee emp = new Employee(name);
emp.init();
}
private void init() {
setupId();
}
private void generateEmpId() {
Random rand = new Random();
int randint = rand.nextInt(100000);
char subId = 'E';
employeeID = subId + String.valueOf(randint);
this.employeeID = employeeID;
}
}
Notice that the constructor is private now, which means that the only way to create Employee from main is using the create method. The init method also went private:
main:
Employee emp = Employee.create("John");
// the id is created - no need to remember to call "init" like in the previous example
Employee class should look like:
public class Employee {
private String employeeID;
public Employee() {
}
public void setEmployeeId(String employeeID){
this.employeeID = employeeID;
}
public String getEmployeeId(){
return employeeID;
}
}
From the class you want to assign new id, use the following:
public String generateId(String subId) {
Random rand = new Random();
int randint = rand.nextInt(100000);
return subId.concat(String.valueOf(randint));
}
Employee employee = new Employee();
employee.setEmployeeId(generateId('E'));
public class Emp {
private String id;
public Emp(){
id=getRandomId();
}
public void setId(String x){
id=new String(x);
}
public String getId(){
return new String (id);
}
public static String getRandomId(){
Random rand = new Random();
return "E"+rand.nextInt(100000);
}
}
getRandomId will return a random id.
I am using a copy constructor and Inheritance in a class called 'Department' to call the information from class 'Teacher' which is a sub-class of 'Person'. After creating my set/get methods, I get the above error. Anyone have any insight as to why this is occurring?
Code from 'Department' class:
public class Department {
private String deptName;
private int numMajors;
private Teacher[] listTeachers; //inherits from Person class
private Student[] listStudents; //inherits from Person class
// First constructor for Department
public Department(String dn, int nm, Teacher[] listTeachers, Student[] listStudents) {
this.deptName = dn;
this.numMajors = nm;
this.listTeachers = new Teacher[listTeachers.length];
for (int i = 0; i < this.listTeachers.length; i++)
{
this.listTeachers[i] = new Teacher (listTeachers[i]);
}
//set method for Teachers Array
public void setListTeachers (Teacher[] other) {
this.listTeachers = new Teacher[other.length];
for (int i = 0; i < listTeachers.length; i++) {
this.listTeachers[i] = new Teacher (other[i]);
}
}
//get method for Teachers Array
public Teacher[] getListTeachers() {
Teacher[] copyTeachers = new Teacher[listTeachers.length];
for (int i = 0; i < copyTeachers.length; i++) {
copyTeachers[i] = new Teacher(this.listTeachers[i]);
}
return copyTeachers;
}
Here are the lines giving me errors:
1) this.listTeachers[i] = new Teacher (listTeachers[i]);
2) this.listTeachers[i] = new Teacher (other[i]);
3) copyTeachers[i] = new Teacher(this.listTeachers[i]);
Code from 'Teacher' class:
public class Teacher extends Person {
private String id;
private int salary;
private int num_yr_prof;
//Constructor for use in Teacher main method.
public Teacher(String n, int a, String s, boolean al, String i, int sal, int numyr) {
super(n, a, s, al);
this.id = i;
this.salary = sal;
this.num_yr_prof = numyr;
}
//Copy constructor for use in Department class.
public Teacher (String n, int a, String s, boolean al, Teacher other) {
super(n, a, s, al);
if (other == null) {
System.out.println("Fatal Error!");
System.exit(0);
}
this.id = other.id;
this.salary = other.salary;
this.num_yr_prof = other.num_yr_prof;
}
Your copy constructor might look like this:
public Teacher(Teacher teacher) {
this( teacher.n, teacher.a, teacher.s, teacher.al,
teacher.id, teacher.salary, teacher.num_yr_prof );
}
Since you do not show the code for the Person class, I have used the variable names n, a, s, and al here. They should be replaced by whatever those variables are named in the Person class. This, of course, assumes that those variables are either public or protected. If they are private, you need to use the getters for those variables (preferred even if they are public or protected).
You need to to your Teacher class a constructor that accepts a Teacher:
public Teacher(Teacher teacher) {
// do something
}
I am creating a simple program which reads data from a text file and displays it in the console. The data that I am displaying is information regarding a student - name, id, subject, marks etc
The program reads the text file, and creates a student object for each user found. I am running into a problem when trying to store these students in a linked list. It seems to create a new list each time and overrides the previous one, so I always just end up with one student in the list.
How can I get it store them without overriding previous lists? Here is some of my code below:
public static boolean readFile(String filename) {
File file = new File(filename);
try {
Scanner scanner = new Scanner(file);
while(scanner.hasNextLine()){
String[] words = scanner.nextLine().split(",");
int id = Integer.parseInt(words[0]);
String firstName = words[1];
String lastName = words[2];
int mathMark1 = Integer.parseInt(words[3]);
int mathMark2 = Integer.parseInt(words[4]);
int mathMark3 = Integer.parseInt(words[5]);
int englishMark1 = Integer.parseInt(words[6]);
int englishMark2 = Integer.parseInt(words[7]);
int englishMark3 = Integer.parseInt(words[8]);
addStudent(id,firstName,lastName,mathMark1,mathMark2,mathMark3,englishMark1,englishMark2,englishMark3);
}
scanner.close();
} catch (FileNotFoundException e) {
System.out.println("Failed to read file");
}
return true;
}
private static void addStudent(int id, String firstName, String lastName,int
mathsMark1, int mathsMark2, int mathsMark3, int englishMark1, int englishMark2,
int englishMark3) {
LinkedList<Student> student = new LinkedList<>();
student.add(new Student(id,firstName,lastName));
LinkedList<AssignmentMarks> mathematicsMarks = new LinkedList<>();
mathematicsMarks.add(new AssignmentMarks("Mathematics",mathsMark1,mathsMark2,mathsMark3));
LinkedList<AssignmentMarks> englishMarks = new LinkedList<>();
englishMarks.add(new AssignmentMarks("English",englishMark1,englishMark2,englishMark3));
}
This code above is in my Main class. The code below is from my Student class:
public class Student {
private int id;
private String firstName;
private String lastName;
private AssignmentMarks mathMarks;
private AssignmentMarks englishMarks;
public Student(int id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
public String getFullName() {
return firstName;
}
}
Any help would be appreciated thanks guys!
This variable
LinkedList<Student> student = new LinkedList<>();
needs to declared outside of the method, as a field, or within readFile and passed in as a parameter, otherwise it will be created everytime that you call addStudent
Declare your LinkedList as a member of the class, because here every time you call addStudent() you are creating a new list.
You should instead do something like :
public class Test {
private LinkedList<Student> student = new LinkedList<>();
public static boolean readFile(String filename) {
// ...
addStudent(id,firstName,lastName,mathMark1,mathMark2,mathMark3,
englishMark1,englishMark2,englishMark3);
}
private static void addStudent(int id, String firstName, String lastName,int
mathsMark1, int mathsMark2, int mathsMark3, int englishMark1, int englishMark2,
int englishMark3) {
// ...
// this will now add it to the only instance of the list
student.add(new Student(id,firstName,lastName));
}
}
I am creating a database for which i am following the given procedure , but i need to insert bulk amount of data in differ differ columns ,for which do i have to add the values in Array and then should insert them to database ?? if yes then how ?? and by doing the same how i'll match/retrieve them with other table's data as i am having more tables.
Any kind of help/suggestions will truly appreciated.
Adding the value to table is like :
public void addMidSemQuestions(MidSemQuestions midSemQuestions)
{
openWritable();
m_sqLiteDatabase.beginTransaction();
try {
ContentValues values = new ContentValues();
values.put(KEY_SEM_ID, midSemQuestions.getId());
values.put(KEY_SUBJECT, midSemQuestions.getSubject());
values.put(KEY_QUESTION_ID, midSemQuestions.getQuestion_id());
values.put(KEY_QUESTION, midSemQuestions.getQuestion());
// Notice how we haven't specified the primary key. SQLite auto increments the primary key column.
m_sqLiteDatabase.insertOrThrow(MID_SEM_QUESTION_TABLE, null, values);
m_sqLiteDatabase.setTransactionSuccessful();
}catch (Exception e)
{
Log.d(LOG,"Error while trying to add mid sem questions to database");
}finally {
m_sqLiteDatabase.endTransaction();
}
}
and my model class is like :
public class MidSemQuestions
{
public int id;
public int sem_id;
public int sub_id;
public int marks_id;
public int question_id;
public String subject;
public String question;
public MidSemQuestions() {
}
public MidSemQuestions(int sem_id, int sub_id, int marks_id, int question_id, String subject,String question) {
this.sem_id = sem_id;
this.sub_id = sub_id;
this.marks_id = marks_id;
this.question_id = question_id;
this.subject=subject;
this.question = question;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public int getSub_id() {
return sub_id;
}
public void setSub_id(int sub_id) {
this.sub_id = sub_id;
}
public int getSem_id() {
return sem_id;
}
public void setSem_id(int sem_id) {
this.sem_id = sem_id;
}
public int getMarks_id() {
return marks_id;
}
public void setMarks_id(int marks_id) {
this.marks_id = marks_id;
}
public int getQuestion_id() {
return question_id;
}
public void setQuestion_id(int question_id) {
this.question_id = question_id;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
and i need to fill the data so for that i am doing like :
public void prepareDatabase()
{
final CDataSource cDataSource= new CDataSource(this);
if(cDataSource.getMidSemQuestionCount()==0)
{
//sem_id=1,sub_id=1,marks=2,
//que_id should be an array of 1 to 90,
//subject must be an array of strings,
//question also should be an array of strings
cDataSource.addMidSemQuestions(new MidSemQuestions(1,1,2,1,"C Programming","What are the data types?"));
//sem_id=1,sub_id=1,marks=5,que_id should be an array of 1 to 90,subject must be an array of strings,question also should be an array of strings
cDataSource.addMidSemQuestions(new MidSemQuestions(1,1,5,11,"C Programming","Difference b/w call by value?"));
//sem_id=1,sub_id=1,marks=10,que_id should be an array of 1 to 90,subject must be an array of strings,question also should be an array of strings
cDataSource.addMidSemQuestions(new MidSemQuestions(1,1,2,1,"C Programming","What are the data types?"));
}
}
suppose your have arraylist this fields,which contain all values, which
you want to insert in database using model class.
List<String> sem_id=new ArrayList<>();
List<String> String sub_id=new ArrayList<>();
List<String> String marks_id=new ArrayList<>();
List<String> String question_id=new ArrayList<>();
List<String> Strubg subject=new ArrayList<>();
List<String> String question=new ArrayList<>();
For saving into database,suppose, databasehelper.addData() is your database object to add data into database
for(int i=0;i<sem_id.size();i++{
databasehelper.addData(new CDataSource(this).addMidSemQuestions(
new MidSemQuestions(sub_id.get(i),
marks_id.get(i),question_id.get(i),
subject_id.get(i),question.get(i))));
}
and for fetching from Database bulk data, your database should return in
List format,
Here midsem list will get all values from Database
List<MidSemQuestions> midsem=new ArrayList<MidSemQuestions>();
midsem=database.getAllFieldsFromDatabase();
for(MidSemQuestions values:midsem){
String sub_id=values.getSub_id();
String sem_id=values.getSem_id();
String marks_id=values.getMarks_id();
String question_id=values.getQuestion_id();
String subject_id=values.getSubject_id();
String question=values.getQuestion();
//if you want array list then, put it in arraylist
//or anything you like
}
I have custom class that implements Parcelable and I use it as custom arraylist.
When I use putParcelableArrayListExtra and 400 rows it works fine, but 1000 rows it does not. I have black screen and app locks up. What is wrong?
EDIT:
I sent it here and I don't use it in another Activity.
Intent intent = new Intent().setClass(getApplicationContext(), ArtActivity.class);
intent.putParcelableArrayListExtra ("mylist", list);
startActivityForResult(intent, SECONDARY_ACTIVITY_REQUEST_CODE);
My array:
ArrayList<Piece> list = new ArrayList<Piece>();
It is my Class:
public class Piece implements Parcelable {
private String id;
private String name;
private int type;
private String text;
private String mp3;
public Piece (String id,String name,int type)
{
this.id=id;
this.name=name;
this.type=type;
}
public Piece(Piece ele)
{
this.id=ele.id;
this.name=ele.name;
this.type=ele.type;
this.text=ele.text;
}
public Piece (Parcel in)
{
id = in.readString ();
name = in.readString ();
type = in.readInt();
text= in.readString();
mp3=in.readString();
}
public static final Parcelable.Creator<Piece> CREATOR
= new Parcelable.Creator<Piece>()
{
public Piece createFromParcel(Parcel in)
{
return new Piece(in);
}
public Piece[] newArray (int size)
{
return new Piece[size];
}
};
public void makeText(String text)
{
this.text=text;
}
public void makeMp3(String mp3)
{
this.mp3= mp3;
}
public String getMp3()
{
return this.mp3;
}
public String getId()
{
return id;
}
public String getName()
{
return name;
}
public int getType()
{
return type;
}
public String getText()
{
return text;
}
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
// TODO Auto-generated method stub
dest.writeString (id);
dest.writeString (name);
dest.writeInt(type);
dest.writeString (text);
dest.writeString (mp3);
}
}
I do not believe you should be using parcelable in this case. I would either access the data statically (if you only intend to have one persistent instance of the data), or use a caching system to hold onto the data.
This is an example of a publicly available static variable:
public static List<Piece> list;
It is accessible from everywhere in your app that has visibility of the class.
However, doing this is very messy and is considered a bad practice. Alternatively, you can create an object to manage the data for you as a static class or singleton:
public class MyListManager {
private static List<Piece> mList;
public static List<Piece> getMyList() {
return mList;
}
public static void setList(List<Piece> list) {
mList = list;
}
}
Alternatively, you can implement some kind of a caching system to manage your data.