单身人士的两个对象

时间:2015-04-26 07:49:25

标签: java android

我想从下面的类中创建两个对象,并且还存储了两个arraylist,事实上我想在单例中存储两个相同类型的变体

我叫它

CrimeLab.get(getActivity()).getCrimes();

在不同的活动中但由于引用同一个对象(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) {
        for (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;
        }
    }
}

先谢谢你

1 个答案:

答案 0 :(得分:1)

问题来自使用静态变量sCrimeLab。当您将其他getActivity()传递给CrimeLab.get时,您正在更新(更改)第一个对象。因为你没有解释为什么你需要这样做我将变换方法体提到:

public static CrimeLab get(Context c) {
    return new CrimeLab(c.getApplicationContext());
}

或者如果它必须保持原样,请改变你如何将这门课程改为:

CrimeLab crimeLab = new CrimeLab(getActivity());
crimeLab.getCrimes();