java - Two objects from singleton -
i want make 2 objects following class , have stored 2 arraylist well, matter of fact want store 2 variations of same type in singleton
i call
crimelab.get(getactivity()).getcrimes();
in different activities encounter problem due referring same object (arraylist)
public class crimelab { private static final string tag = "crimelab"; private static final string filename = "crimes.json"; private arraylist<crime> mcrimes; private criminalintentjsonserializer mserializer; private static crimelab scrimelab; private context mappcontext; private crimelab(context appcontext) { mappcontext = appcontext; mserializer = new criminalintentjsonserializer(mappcontext, filename); try { mcrimes = mserializer.loadcrimes(); } catch (exception e) { mcrimes = new arraylist<crime>(); } } public static crimelab get(context c) { if (scrimelab == null) { scrimelab = new crimelab(c.getapplicationcontext()); } return scrimelab; } public crime getcrime(int id) { (crime c : mcrimes) { if (c.getid() == (id)) return c; } return null; } public void addcrime(crime c) { mcrimes.add(c); savecrimes(); } public arraylist<crime> getcrimes() { return mcrimes; } public void deletecrime(crime c) { mcrimes.remove(c); savecrimes(); } public boolean savecrimes() { try { mserializer.savecrimes(mcrimes); return true; } catch (exception e) { return false; } } }
thank in advance
issue comes using static variable scrimelab. when pass other getactivity() crimelab.get updating (change) first object. cause not explain why need way sugest change method body to:
public static crimelab get(context c) { return new crimelab(c.getapplicationcontext()); }
or if has stay way is, change way how getting class to:
crimelab crimelab = new crimelab(getactivity()); crimelab.getcrimes();
Comments
Post a Comment