mercredi 18 février 2015

how to clone an object java

ok i try to make a DBManager to allow connections to the DB, so, here is the context.


I have an abstract class Entitie, that has, the structure for every entitie in the DB, the important things in this case are the table name, the id, and an abstract method (setContentValues) that get the values from a Cursor and put them in variables (the method is abstract, beacause the variables changes dependig of what entitie is).


In the DBManager i have a method getAll, I pass a dummyEntitie that only has the id, and obviously, the class by default, has the table name.


So i try to build an arraylist of the same class entitie that the method recieve. So, i have the idea, to clone the dummyEntitie, call the setContentValues, and add it to the arraylist. But every time i tried to call the method .clone, i have an error on the IDE, so i don't know what is wrong, or how to clone the object.


here is the code:



public ArrayList<Entitie> getAll(Entitie dummyEntitie){
ArrayList<Entitie> entities = new ArrayList<Entitie>();

String selectQuery = "SELECT * FROM " + dummyEntitie.getTableName(); // Select All Query

db = getWritableDb();

Cursor cursor = db.rawQuery(selectQuery, null);

// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
try {
dummyEntitie = dummyEntitie.clone();
} catch (Exception e) {
e.printStackTrace();
}
dummyEntitie.setID(Integer.parseInt(cursor.getString(0)));
dummyEntitie.setContentValues(cursor);
entities.add(dummyEntitie);
} while (cursor.moveToNext());
}

// return contact list
return entities;
}

Aucun commentaire:

Enregistrer un commentaire