I have been trying to use WeakReference
in my Android projects and I have never had any success. Now I really need it as I am dealing with old devices and I have to keep the memory clean as much as I can.
Anyway, I have an array which has about 1000 list of different strings in it. I need to load it then find a string in it.
This is how I am currently using it:
String[] campaignList = context.getResources().getStringArray(R.array.campaignList);
WeakReference<String[]> weakCampaignList = new WeakReference<String[]>(campaignList);
Is this the correct way of using WeakReference
?
If yes then what I don't understand is the array is getting hydrated at String[]
and then I pass it to the WeakReference
. So doesn't this mean I have 2 spots on the memory allocated to one array? Or I am completely misunderstanding the WeakReference
concept?
A very good resource that I found among all the resources is this one:
http://neverfear.org/blog/view/150/Strong_Soft_Weak_and_Phantom_References_Java
Edit:
My code works with no issue. Just need to know if I am doing it correct in terms of performance.
for (int i = 0; i < weakCampaignList.get().length; i++) {
Log.d(TAG,"weakCampaignList: "+weakCampaignList.get()[i]);
}
My Entire Method
public static String getTheCampaign(String country, Context context) {
String campaign = "";
campaign = "annual_subscription_" + country;
String[] campaignList = context.getResources().getStringArray(
R.array.campaign_list);
ArrayList<WeakReference<String>> weakCampaignList = new ArrayList<WeakReference<String>>();
for (String s : campaignList) {
weakCampaignList.add(new WeakReference<String>(s));
}
if (country.equals("") || country.isEmpty()) {
campaign = "annual_subscription_us";
} else {
for (int i = 0; i < weakCampaignList.size(); i++) {
if (weakCampaignList.get(i).get().contains(campaign)) {
campaign = weakCampaignList.get(i).get();
return campaign;
}
}
}
return campaign;
}