I have a spinner whose elements are save in sharedPrefrences. When I choose any element from the spinner and clicks on save button it saves that element in sharedPref and whenever I come back to this activity the spinner is selected with the same element that I'd choosen and saved. The problem arises when I close my app and removes from currently running apps in my phone. In this case when I open my app and goes to that activity, spinner is selected with the 0th element. I'm getting the saved element from sharedPref but getPosition() is not being called. Why is it happening?
Here's my method:
public boolean setBranchIds(ArrayList<String> tdBrlist) {
try {
branchList = tdBrlist;
runOnUiThread(new Runnable() {
@Override
public void run() {
branchSpinner = new Spinner(Activity_Settings.this);
TableRow.LayoutParams tdpid_spinner_params = new TableRow.LayoutParams(
0, LayoutParams.WRAP_CONTENT, 3f);
branchSpinner.setLayoutParams(tdpid_spinner_params);
branchRow.addView(branchSpinner);
branchSpinner.setPrompt("Select Branch");
if (branchList.size() > 0) {
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(
Activity_Settings.this,
android.R.layout.simple_spinner_item,
branchList);
branchSpinner.setAdapter(spinnerAdapter);
String branch = mActivity.getSharedPreferences(
Utility.PREFERENCE_NAME, Context.MODE_PRIVATE)
.getString(Utility.BRANCH, "");
System.out.println("====branch===: "+branch);
if (!branch.equals("")) {
branchIndex = getIndex(branch);
System.out.println("=====positionbranch:
"+branchIndex);
branchSpinner.setSelection(branchIndex);
}
}
}
});
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
private int getIndex(String branch) {
for (int i = 0; i < branchList.size(); i++) {
if (branchList.get(i).equalsIgnoreCase(branch)) {
System.out.println("======i: "+i);
return i;
}
}
return -1;
}
LogCat values:
12-17 13:50:51.502: I/System.out(13229): ====branch===: B1
12-17 13:50:51.502: I/System.out(13229): ====branchlist===: [Select, B1, B2,
B3,B4]
12-17 13:50:51.502: I/System.out(13229): ======i: 1
12-17 13:50:51.502: I/System.out(13229): =====positionbranch: 1
LogCat values when I return back:
12-17 13:53:10.932: I/System.out(14895): ====branch===: B1
12-17 13:53:10.932: I/System.out(14895): ====branchlist===: [Select, B1, B2
, B3, B4]
12-17 13:53:10.932: I/System.out(14895): =====positionbranch: -1