First of all I apologize if this question is inappropriate.
I am implementing a country picker feature in my Android application and I found a github project and it is a good start for me. The code works just fine and as expected.
I started by breaking it down to understand how it works.
This is the blurry part of code
@Override
protected ArrayList<Country> doInBackground(Void... params) {
ArrayList<Country> data = new ArrayList<Country>(233);
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(mContext.getApplicationContext().getAssets().open("countries.dat"), "UTF-8"));
// do reading, usually loop until end of file reading
String line;
int i = 0;
while ((line = reader.readLine()) != null) {
//process line
Country c = new Country(mContext, line, i);
data.add(c);
ArrayList<Country> list = mCountriesMap.get(c.getCountryCode());
if (list == null) {
list = new ArrayList<Country>();
mCountriesMap.put(c.getCountryCode(), list);
}
list.add(c);
i++;
}
} catch (IOException e) {
//log the exception
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}
//this code enables app to pick the right default country from the spinner
String countryRegion = PhoneUtils.getCountryRegionFromPhone(mContext);
int code = mPhoneNumberUtil.getCountryCodeForRegion(countryRegion);
final ArrayList<Country> list = mCountriesMap.get(code);
/*getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
for(int i = 0; i < list.size(); i++)
Toast.makeText(mContext, "ds: " + list.get(i).getName(), Toast.LENGTH_SHORT).show();
}
});*/
if (list != null) {
for (Country c : list) {
if (c.getPriority() == 0 || c.getPriority() == 1) {
mSpinnerPosition = c.getNum();
break;
}
}
}
return data;
}
This code reads a file in the asset
folder and add objects to a list.
After that it picks the country of the device and selects it from the spinner of all countries
In the while
loop, I think this line list.add(c);
makes no sense because the while loop will loop again and new list object is created. If I comment this line, mCountriesMap.get(code)
returns empty list even though mCountriesMap
isn't null.
So my question is why this behavior is happening? What list.add(c);
is doing here ?