why sometime i get the cursor null or count equal to zero - uri

My apliction works fine ,it updates my spinner but sometime when I start my activity cursor becomes null and spinner list will be blank ,why?.It seems like my cursor is null or its count is zero. Though it works fine most of the time so there is no chance of cursor being null or emplty.very strange behavior
public class MainActivity extends Activity {
String[] data = { MediaStore.Video.Media.DATA };
ArrayList<String> path;
Spinner path_spinner;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.MainActivity);
path= new ArrayList<String>();
path_spinner = (Spinner) findViewById(R.id.folder_spinner);
Cursor cursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,data, null, null, null);
if(cursor != null && cursor.getCount() > 0)
{
cursor.moveToFirst();
do {
path.add(cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA))
} while (cursor.moveToNext());
}
ArrayAdapter<String> path_adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, path);
path_spinner.setAdapter(path_adapter);
}
}
Update
if any uri is accessd at this time it gives
ContentValues values = new ContentValues(4);
values.put(MediaStore.Audio.Media.TITLE,"audio" + audiofile.getName());
values.put(MediaStore.Audio.Media.MIME_TYPE, "audio/3gpp");
values.put(MediaStore.Audio.Media.DATA, audiofile.getAbsolutePath());
ContentResolver contentResolver = getContentResolver();
Uri base = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Uri newUri = contentResolver.insert(base, values);
07-24 15:52:22.300: E/AndroidRuntime(2583): Caused by: java.lang.UnsupportedOperationException: Unknown URI: content://media/external/audio/media
it was all working fine before the cursor problem .It seems like content provider is not accesible at the moment. why?

Related

Firebase Query not being updated

I want my firebase database link to be updated depending on what the user keys in inside the searchview but the link is not updated unless I open another activity and jump back to it.I have attacked my code in the bottom. So how do I refresh it automatically ?
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener()
{
#Override
public boolean onQueryTextSubmit(String query) {
query = sv.getQuery().toString();
Toast.makeText(MainMenu.this,query, Toast.LENGTH_SHORT).show();
makeItem();
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
public void makeItem ()
{
lv = findViewById(R.id.listView);
db = FirebaseDatabase.getInstance().getReferenceFromUrl("https://vsem-inventory.firebaseio.com/ItemList").orderByChild("ProductName").startAt(query).endAt(query+"\uf8ff");
FirebaseListOptions<ItemObject> options = new FirebaseListOptions.Builder<ItemObject>()
.setLayout(R.layout.content_main_menu_list)
.setQuery(db,ItemObject.class)
.build();
mAdapter = new FirebaseListAdapter<ItemObject>(options) {
#Override
protected void populateView(#NonNull View v, #NonNull ItemObject model, int position) {
final TextView tvAmount = v.findViewById(R.id.amount);
final TextView tvName = v.findViewById(R.id.name);
final TextView tvSerial = v.findViewById(R.id.serialNo);
final TextView tvSupplier = v.findViewById(R.id.supplierName);
final ImageView more = v.findViewById(R.id.more);
ImageView statusimg = v.findViewById(R.id.status);
Drawable paidIcon = v.getResources().getDrawable(R.drawable.succes);
Drawable lateIcon = v.getResources().getDrawable(R.drawable.late);
tvName.setText(model.getProductName());
tvSerial.setText(model.getSerialNo());
tvAmount.setText(model.getQuantity());
tvSupplier.setText(model.getModel());
final String Remarks = model.getRemarks();
final String cat = model.getCategory();
if(model.getQuantity().equals("0"))
statusimg.setImageDrawable(lateIcon);
else
statusimg.setImageDrawable(paidIcon);
more.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
String serialNo = tvSerial.getText().toString();
String itemName = tvName.getText().toString();
String quan = tvAmount.getText().toString();
String supplier = tvSupplier.getText().toString();
showMenu(itemName,more,serialNo,quan,supplier,cat,Remarks);
}
});
}
};
lv.setAdapter(mAdapter);
}
The standard way is to call notifyDataSetChanged() after setting your adapter to your list view
Notifies the attached observers that the underlying data has been changed and any View reflecting the data set should refresh itself.
mAdapter.notifyDataSetChanged();
Although I have seen some situations where only using this does not work and must be followed by these 2 commands.
lv.invalidateViews();
lv.scrollBy(0, 0);
And if all else comes to fail falling back on destroying and redrawing the list view might be your only viable option.
lv.destroyDrawingCache();
lv.setVisibility(ListView.INVISIBLE);
lv.setVisibility(ListView.VISIBLE);
EDIT : After looking at it a while more I just noticed you're missing listeners for your firebase. I assume you already have them somewhere as you already have the list but failing your refresh functions, what you can try is restarting the listeners whenever you're done with a query.
lv.setAdapter(mAdapter);
mAdapter.stopListening();
mAdapter.startListening();

How can i resolve the variable i was trying to pass to a cardviewadapter that i tried to extract from sqlite cursor

The ide tells me it cannot resolve the symbols that ive put in the ProjectsCardAdapter parameters. the symbols are variables inside a try block that contains string type from cursor
I tried to initialize the string array variables outside the try block but realized i need to getCount how many rows the cursor will have in order to initialize the string arrays.
public class ProjectsFragment extends Fragment {
public ProjectsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
RecyclerView projectsRecycler = (RecyclerView) inflater.inflate(
R.layout.fragment_projects, container, false);
try {
SQLiteOpenHelper projectsDBhelper = new ProjectsDBhelper(inflater.getContext());
SQLiteDatabase db = projectsDBhelper.getReadableDatabase();
Cursor cursor = db.query("PROJECTS",
new String[]{"PROJ_STAGE", "PROJ_BUDGET", "PROJ_LOC", "CLIENT_NAME"}
, null
, null, null, null, null);
int rowCount = cursor.getCount();
String[] projStage = new String[rowCount];
String[] projBudget = new String[rowCount];
String[] projLoc = new String[rowCount];
String[] clientName = new String[rowCount];
int i = 0;
Float floatBudget;
if (cursor.moveToFirst()) {
projStage[i] = cursor.getString(0);
floatBudget = cursor.getFloat(1);
projLoc[i] = cursor.getString(2);
clientName[i] = cursor.getString(3);
projBudget[i] = String.format("%,.2f", floatBudget.toString());
cursor.close();
db.close();
} catch (SQLiteException e) {
Toast exceptionToast = Toast.makeText(inflater.getContext(), "Database unavailable", Toast.LENGTH_SHORT);
exceptionToast.show();
}
//This is the ProjectsCardAdapter that couldnt resolve the symbol
ProjectsCardAdapter projectsCardAdapter = new ProjectsCardAdapter(projStage, projBudget, projLoc, clientName);
projectsRecycler.setAdapter(projectsCardAdapter);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
projectsRecycler.setLayoutManager(layoutManager);
return projectsRecycler;
}
}
i wanted to test a cardview displaying a set of texts using data from SQLite but the adapter cant take the variables from cursor
Your issue is that projStage, projBudget, projLoc and clientName are being declared in the try block and therefore only have scope within the the try block.
The following would increase the scope to be within the onCreateView method :-
public class ProjectsFragment extends Fragment {
public ProjectsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
RecyclerView projectsRecycler = (RecyclerView) inflater.inflate(
R.layout.fragment_projects, container, false);
String[] projStage;
String[] projBudget;
String[] projLoc;
String[] clientName;
try {
SQLiteOpenHelper projectsDBhelper = new ProjectsDBhelper(inflater.getContext());
SQLiteDatabase db = projectsDBhelper.getReadableDatabase();
Cursor cursor = db.query("PROJECTS",
new String[]{"PROJ_STAGE", "PROJ_BUDGET", "PROJ_LOC", "CLIENT_NAME"}
, null
, null, null, null, null);
int rowCount = cursor.getCount();
projStage = new String[rowCount];
projBudget = new String[rowCount];
projLoc = new String[rowCount];
clientName = new String[rowCount];
int i = 0;
Float floatBudget;
if (cursor.moveToFirst()) {
projStage[i] = cursor.getString(0);
floatBudget = cursor.getFloat(1);
projLoc[i] = cursor.getString(2);
clientName[i] = cursor.getString(3);
projBudget[i] = String.format("%,.2f", floatBudget.toString());
cursor.close();
db.close();
} catch (SQLiteException e) {
Toast exceptionToast = Toast.makeText(inflater.getContext(), "Database unavailable", Toast.LENGTH_SHORT);
exceptionToast.show();
}
//This is the ProjectsCardAdapter that couldnt resolve the symbol
ProjectsCardAdapter projectsCardAdapter = new ProjectsCardAdapter(projStage, projBudget, projLoc, clientName);
projectsRecycler.setAdapter(projectsCardAdapter);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
projectsRecycler.setLayoutManager(layoutManager);
return projectsRecycler;
}
}
Note, this is in-principle code. The code hasn't been tested or run and therefore may contain errors.

Codename One: Connecting and populating a drop-down menu with an SQLite database

I am trying to connect an SQLite database file to a picker component (accepting strings). This should act similar to a drop-down menu. I have tried to follow previous advice and examples, but without success.
As indicated in a previous post, I have saved the database file in the source folder of the application. View of the source folder where I have saved the database file (highlighted).
The code I have used to implement my app is as follows with the below layout.
//-----------------------
database code
//-----------------------
public class MyApplication {
private Form current;
private Resources theme;
public void init(Object context) {
theme = UIManager.initFirstTheme("/theme");
// Pro only feature, uncomment if you have a pro subscription
// Log.bindCrashProtection(true);
}
private Container Home() {
Container home = new Container(new BoxLayout(BoxLayout.Y_AXIS));
return home;
}
private Container AddItem() {
Container addItem = new Container(new BoxLayout(BoxLayout.Y_AXIS));
TextArea item = new TextArea("Add Item");
addItem.addComponent(item);
Picker selectItem = new Picker();
selectItem.setType(Display.PICKER_TYPE_STRINGS);
//----------------------------------------------------------------------------------
Database db = null;
Cursor cur = null;
try {
db = Display.getInstance().openOrCreate("FoodAndBeverage.db");
if(selectItem.getText().startsWith("Still Water")) {
cur = db.executeQuery(selectItem.getText());
int columns = cur.getColumnCount();
addItem.removeAll();
if(columns > 0) {
boolean next = cur.next();
if(next) {
ArrayList<String[]> data = new ArrayList<>();
String[] columnNames = new String[columns];
for(int iter = 0 ; iter < columns ; iter++) {
columnNames[iter] = cur.getColumnName(iter);
}
while(next) {
Row currentRow = cur.getRow();
String[] currentRowArray = new String[columns];
for(int iter = 0 ; iter < columns ; iter++) {
currentRowArray[iter] = currentRow.getString(iter);
}
data.add(currentRowArray);
next = cur.next();
}
Object[][] arr = new Object[data.size()][];
data.toArray(arr);
addItem.add(BorderLayout.CENTER, new Table(new DefaultTableModel(columnNames, arr)));
} else {
addItem.add(BorderLayout.CENTER, "Query returned no results");
}
} else {
addItem.add(BorderLayout.CENTER, "Query returned no results");
}
} else {
db.execute(selectItem.getText());
addItem.add(BorderLayout.CENTER, "Query completed successfully");
}
addItem.revalidate();
} catch(IOException err) {
Log.e(err);
addItem.removeAll();
addItem.add(BorderLayout.CENTER, "Error: " + err);
addItem.revalidate();
} finally {
Util.cleanup(db);
Util.cleanup(cur);
}
//---------------------------------------------------------------------------------------------
addItem.addComponent(selectItem);
TextField quantity = new TextField("", "Quantity (ml or g)", 4, TextArea.NUMERIC);
addItem.addComponent(quantity);
Button add = new Button("Add");
addItem.addComponent(add);
TextArea results = new TextArea("Results");
addItem.addComponent(results);
return addItem;
}
private Container Settings() {
Container settings = new Container(new BoxLayout(BoxLayout.Y_AXIS));
TextArea nutrients = new TextArea("Target");
settings.addComponent(nutrients);
TextField volume = new TextField("", "Volume (ml)", 4, TextArea.NUMERIC);
settings.addComponent(volume);
TextArea duration = new TextArea("Hydration Duration");
settings.addComponent(duration);
settings.add("Start:");
Picker start = new Picker();
start.setType(Display.PICKER_TYPE_TIME);
settings.addComponent(start);
settings.add("End:");
Picker end = new Picker();
end.setType(Display.PICKER_TYPE_TIME);
settings.addComponent(end);
Button save = new Button("Save");
settings.addComponent(save);
return settings;
}
public void start() {
if(current != null)
{
current.show();
return;
}
Form home = new Form("Hydrate", new BorderLayout());
Tabs t = new Tabs();
t.addTab("Home", Home());
t.addTab("Intake", AddItem());
t.addTab("Settings", Settings());
home.add(BorderLayout.NORTH, t);
home.show();
}
public void stop() {
current = Display.getInstance().getCurrent();
}
public void destroy() {
}
}
I would therefore appreciate any advice and guidance on exactly where I am going wrong and how to implement the suggested changes in my code.
I'm assuming the file under src does indeed end with the extension db as the Windows hidden extensions nonsense is turned on.
This code will NOT open a db placed in src:
db = Display.getInstance().openOrCreate("FoodAndBeverage.db");
You need to do something like this to implicitly initialize the DB the first time the app is installed:
String path = Display.getInstance().getDatabasePath("FoodAndBeverage.db");
FileSystemStorage fs = FileSystemStorage.getInstance();
if(!fs.exists(path)) {
try (InputStream is = Display.getInstance().getResourceAsStream(getClass(), "/FoodAndBeverage.db");
OutputStream os = fs.openOutputStream(path)) {
Util.copy(is, os);
} catch(IOException err) {
Log.e(err);
}
}
db = Display.getInstance().openOrCreate("FoodAndBeverage.db");
Notice that the code above doesn't check for updates of the DB so assuming the DB is read only you might want to update/merge it with app updates.
The above code doesn't work on Android device, this works only on simulator. I have tested multiple times in the android device. In the real android device ,the database is not loaded at all, shows sql exception error
"No such table sql exception".
Looks like preloaded sqlite .db file is never tested on real Android device.

Retaining fragment state after receiving activity result

I have an Activity A that consists of Fragment A. Inside Fragment A, I start Activity B with startActivityForResult(). When I receive the result from Activity B, all views values in Fragment A that had already been set before return to their default values. How to retain the all views values in Fragment A?
Below is the implementation:
public class MainFragment extends Fragment {
public MainFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_main, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
listView = (ListView) getActivity().findViewById(R.id.xlistview);
xItemArrayList = new ArrayList<XItem>();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.menu_item_add:
initialiseList();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void initialiseList(){
xListAdapter = new xListAdapter(getContext(), R.layout.item_list, xItemArrayList);
xListAdapter.setxListListener(new xListListener() {
#Override
public void onClickStart(View view) {
openAutocompleteActivity(Constant.VIEW_START);
}
});
xListView.setAdapter(xListAdapter);
}
private void openAutocompleteActivity(int selectedView) {
this.selectedView = selectedView;
try {
// The autocomplete activity requires Google Play Services to be available. The intent
// builder checks this and throws an exception if it is not the case.
Intent intent = new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN).build(getActivity());
startActivityForResult(intent, Constant.REQUEST_CODE_AUTOCOMPLETE);
} catch (GooglePlayServicesRepairableException e) {
// Indicates that Google Play Services is either not installed or not up to date. Prompt the user to correct the issue.
GoogleApiAvailability.getInstance().getErrorDialog(getActivity(), e.getConnectionStatusCode(), 0 ).show();
} catch (GooglePlayServicesNotAvailableException e) {
// Indicates that Google Play Services is not available and the problem is not easily resolvable.
String message = "Google Play Services is not available: " + GoogleApiAvailability.getInstance().getErrorString(e.errorCode);
Log.e(Constant.TAG_ERROR, message);
Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Check that the result was from the autocomplete widget.
if (requestCode == Constant.REQUEST_CODE_AUTOCOMPLETE) {
if (resultCode == Constant.RESULT_OK) {
// Get the user's selected place from the Intent.
Place place = PlaceAutocomplete.getPlace(getActivity(), data);
if (selectedView == Constant.VIEW_START){
start = place;
((TextView)xListView.getChildAt(0).findViewById(R.id.textview_start)).setText(start.getName());
}else if (selectedView == Constant.VIEW_LAST){
last = place;
((TextView)xListView.getChildAt(0).findViewById(R.id.textview_last)).setText(last.getName());
}
} else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
Status status = PlaceAutocomplete.getStatus(getActivity(), data);
Log.e(Constant.TAG_ERROR, "Error: Status = " + status.toString());
} else if (resultCode == Constant.RESULT_CANCELED) {
// Indicates that the activity closed before a selection was made. For example if
// the user pressed the back button.
}
}
}
There are two views in R.layout.item_list, R.id.textview_start and R.id.textview_last. On select each of the view, Activity B will start and on finish Activity B, the result will be displayed on the view itself. However, every time Activity B starts and finishes, previous values of the two views disappear and return to default. I have tried SavedInstanceState, but it does not work. It seems when Activity B returns to Activity A (with Fragment A in it), system goes to OnResume() of Fragment A without going to onCreatedView() of Fragment A.
You can use 2 method:
1st: use sharedpreferences to store the data. Now this data is accessible next time also the app is used. So after displaying the old data, just reset the data in sharepreferences to blank.
2nd: use bundle to transfer data to the activity and then just retrieve the same back.
Use a bundle to transfer data from one activity to another activity
Bundle bundle = new Bundle();
bundle.putString("KEY_NAME", "Abrakadabra");
Intent i = new Intent(this, MyActivityName.class);
i.putExtras(bundle);
startActivity(i) <-- new activity started
Then in the receiving activity: Put this code in the onCreate method
Bundle bundle = getIntent().getExtras();
String stringdata = bundle.getString("KEY_NAME");
To pass data from activity to fragment: Put this code anywhere
Bundle bundle = new Bundle();
bundle.putString("KEY_NAME", "Abrakadabra");
MyFragment myfragment = new MyFragment();
myfragment.setArguments(bundle);
Then in the onCreateView method of the fragment add this code
Bundle args = getArguments();
String stringdata = args.getString("KEY_NAME");
Since Fragment A is waiting for Activity B's result, Activity A (where Fragment A is) will go to pause state. When Activity B returns results, Fragment A will resumes without going through onActivityCreated(). Thus, saving instance state will not work. Currently, the only solution I can think of is as below.
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Check that the result was from the autocomplete widget.
if (requestCode == Constant.REQUEST_CODE_AUTOCOMPLETE) {
if (resultCode == Constant.RESULT_OK) {
// Get the user's selected place from the Intent.
Place place = PlaceAutocomplete.getPlace(getActivity(), data);
if (selectedView == Constant.VIEW_START){
start = place;
}else if (selectedView == Constant.VIEW_LAST){
last = place;
}
} else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
Status status = PlaceAutocomplete.getStatus(getActivity(), data);
Log.e(Constant.TAG_ERROR, "Error: Status = " + status.toString());
} else if (resultCode == Constant.RESULT_CANCELED) {
// Indicates that the activity closed before a selection was made. For example if
// the user pressed the back button.
}
}
if(start!=null)((TextView)xListView.getChildAt(0).findViewById(R.id.textview_start)).setText(start.getName());
if(last!=null)((TextView)xListView.getChildAt(0).findViewById(R.id.textview_last)).setText(last.getName());
}
All the views values are re-set in onActivityResult(). When Activity A/Fragment A goes into pause state, it retains global variables values. Thus, for this implementation to work, start and last must be declared as global variables in Fragment A. Please suggest a better solution, if any.

Android Loadermanager onloadfinished method was not called on Orientation Change when it is declared outside on create method

i am initializing the loader in action bar navigation list item callback method. By default first item will be selected in action bar navigation list. based on navitem selection i am initializing the loader. at the launch of application the loader call back methods are calling fine. but when i change the orientation the loader callback methods are not getting called.
but if i initialize the loader in oncreate method the loader callback methods are getting called after orientation change also.
My Code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_base);
getActionBar().setListNavigationCallbacks(adapter, new ActionBar.OnNavigationListener() {
#Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
if(itemPosition == 0 || itemPosition ==1)
{
Bundle b = new Bundle();
b.putString(Constatnts.Url, serviceurl +"/getgroups/"+shared.getString("StationID", "null")+"/0");
b.putInt(Constatnts.selection, itemPosition);
b.putString(Constatnts.xmlroles, session.getUserDetails().get(SessionManager.KEY_NAME).get(1));
getLoaderManager().initLoader(0, b, MainActivity.this);
}
else if(itemPosition == 2)
{
Bundle b = new Bundle();
b.putString(Constatnts.Url, serviceurl +"/getchanneldetails/"+shared.getString("StationID", "null")+"/1/0");
b.putInt(Constatnts.selection, itemPosition);
b.putString(Constatnts.xmlroles, session.getUserDetails().get(SessionManager.KEY_NAME).get(1));
getLoaderManager().initLoader(itemPosition, b, MainActivity.this);
}
else
{
Bundle b = new Bundle();
b.putString(Constatnts.Url, serviceurl+"/Getcategories/"+shared.getString("StationID", "null")+"");
b.putInt(Constatnts.selection, itemPosition);
b.putString(Constatnts.xmlroles, session.getUserDetails().get(SessionManager.KEY_NAME).get(1));
getLoaderManager().initLoader(itemPosition, b, MainActivity.this);
}
return true;
}
});
}
The loader callback methods are not getting called after orientation change with the above method.
*but if i place the below code outside the navigationlistcallbacks and inside oncreate method the loader callback methods are getting called *
Bundle b = new Bundle();
b.putString(Constatnts.Url, serviceurl +"/getgroups/"+shared.getString("StationID", "null")+"/0");
b.putInt(Constatnts.selection, itemPosition);
b.putString(Constatnts.xmlroles, session.getUserDetails().get(SessionManager.KEY_NAME).get(1));
getLoaderManager().initLoader(0, b, MainActivity.this);
how can i reload the data after orientation change if initloader is in setListNavigationCallbacks methods.
The callbacks are only invoked after the loader is initiated (initLoader)or restarted (restartLoader). With initLoader the cached result can be used after an orientation change but it has to be called explicitly to deliver the data in onLoadFinished. Hence, you have to call it in your onCreate method with the itemPosition as the loader id, but only if an itemPosition is already set.
I've stripped your example code to illustrate what I mean:
// static so that it survives orientation change.
private static int mSelectedItemPosition = -1; // -1 = Not selected
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (mSelectedItemPosition != -1) {
getLoaderManager().initLoader(mSelectedItemPosition, null, MainActivity.this);
}
getActionBar().setListNavigationCallbacks(adapter, new ActionBar.OnNavigationListener() {
#Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
if(itemPosition == 0 || itemPosition ==1) {
mSelectedItemPosition = 0;
Bundle b = ...
getLoaderManager().initLoader(mSelectedItemPosition, b, MainActivity.this);
}
else if(itemPosition == 2) {
mSelectedItemPosition = itemPosition;
Bundle b = ...
getLoaderManager().initLoader(mSelectedItemPosition, b, MainActivity.this);
}
else {
mSelectedItemPosition = itemPosition;
Bundle b = ...
getLoaderManager().initLoader(mSelectedItemPosition, b, MainActivity.this);
}
...
}

Resources