ProgressBar dismissed when rotate device in AsyncTaskLoader - android

i decide to use AsyncTaskLoader for lifecycle aware when load data.
It successfully created, but i got one problem when rotate my device, my ProgressBar dismissed and not shown again.
I know it because Activity recreate it and execute onCreate() again.
But i don't know where to handle that, i think it already handled by initLoader
public class MainActivity extends AppCompatActivity implements
LoaderManager.LoaderCallbacks<String> {
public static final String TAG = MainActivity.class.getSimpleName();
public static final int LOADER_ID = 92;
public static final String SEARCH_VALUE = "java";
public static final String ARG_GITHUB_URL = "github_search_url";
#BindView(R.id.tv_results) TextView mResultTextView;
#BindView(R.id.pb_loading_indicator) ProgressBar mLoadingIndicatorProgressBar;
Bundle mBundle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
mBundle = new Bundle();
// Initiate Loader at the first time
// when onCreate called (rotate device)
URL searchUrl = NetworkUtils.buildUrl(SEARCH_VALUE);
mBundle.putString(ARG_GITHUB_URL, searchUrl.toString());
getSupportLoaderManager().initLoader(LOADER_ID, mBundle, this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int menuItemId = item.getItemId();
if (menuItemId == R.id.action_reload) {
loadGithubRepository();
}
return super.onOptionsItemSelected(item);
}
private void loadGithubRepository() {
Log.e(TAG, "loadGithubRepository: Start load github repository");
mResultTextView.setText("");
// URL searchUrl = NetworkUtils.buildUrl(repoName);
// new GithubRepositoryTask().execute(searchUrl);
LoaderManager loaderManager = getSupportLoaderManager();
if (null == loaderManager.getLoader(LOADER_ID)) {
getSupportLoaderManager().initLoader(LOADER_ID, mBundle, this);
} else {
getSupportLoaderManager().restartLoader(LOADER_ID, mBundle, this);
}
}
// Implement Loader Callback method
#Override
public Loader<String> onCreateLoader(int id, final Bundle args) {
return new AsyncTaskLoader<String>(this) {
#Override
protected void onStartLoading() {
mLoadingIndicatorProgressBar.setVisibility(View.VISIBLE);
if (args != null)
forceLoad();
}
#Override
public String loadInBackground() {
String response = null;
Log.d(TAG, "loadInBackground: " + (args != null));
if (args != null) {
try {
Log.d(TAG, "loadInBackground: " + args.getString(ARG_GITHUB_URL));
URL url = new URL(args.getString(ARG_GITHUB_URL));
response = NetworkUtils.getResponseFromHttp(url);
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
};
}
#Override
public void onLoadFinished(Loader<String> loader, String data) {
mLoadingIndicatorProgressBar.setVisibility(View.INVISIBLE);
if (data != null && !data.equals("")) {
mResultTextView.setText(data);
}
}
#Override
public void onLoaderReset(Loader<String> loader) {
// Do nothing...
}
}
How to handle that?

//inside your activity
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
// in manifest
<activity
android:name=".activities.YourActivity"
android:label="#string/title_activity"
android:configChanges="orientation|screenSize"
android:windowSoftInputMode="stateHidden|adjustResize" />
which not recreates activity layout.
may be helpful

It is happening because your layout is recreated and, as I understood, default ProgressBar is INVISIBLE. You have to save activity's loading state and set visibility for ProgressBar after restoring instance state.
More information about saving/restoring data in activity:
https://stackoverflow.com/a/151940/2504274

Related

Android: Save XWalkView - Crosswalk state

I am using XWalkView to show a mobile web site as an application. My problem is when application goes background and comes back it reloads the page it shows. I want to keep it state and continue from that state when it comes from background. Here is my code:
public class MainActivity extends AppCompatActivity {
static final String URL = "https://www.biletdukkani.com.tr";
static final int MY_PERMISSIONS_REQUEST_ACCESS_LOCATION = 55;
static final String SHOULD_ASK_FOR_LOCATION_PERMISSION = "shouldAskForLocationPermission";
static final String TAG = "MainActivity";
static final String COMMAND = "/system/bin/ping -c 1 185.22.184.184";
static XWalkView xWalkWebView;
TextView noInternet;
static Bundle stateBundle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate");
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
stateBundle = savedInstanceState.getBundle("xwalk");
}
setContentView(R.layout.activity_main);
initNoInternetTextView();
}
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can restore the view hierarchy
super.onRestoreInstanceState(savedInstanceState);
stateBundle = savedInstanceState.getBundle("xwalk");
Log.d(TAG, "onRestoreInstanceState");
}
/**
* İnternet yok mesajı gösteren TextVidew'i ayarlar.
*/
private void initNoInternetTextView() {
Log.d(TAG, "initNoInternetTextView");
noInternet = (TextView) findViewById(R.id.no_internet);
if (noInternet != null) {
noInternet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
checkInternetConnection();
}
});
}
}
/**
* WebView'i ayarlar.
*/
private void initWebView() {
Log.d(TAG, "initWebView");
if (xWalkWebView == null) {
ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
xWalkWebView = (XWalkView) findViewById(R.id.webView);
//xWalkWebView.clearCache(true);
xWalkWebView.load(URL, null);
xWalkWebView.setResourceClient(new BDResourceClient(xWalkWebView, progressBar));
}
}
#Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume");
checkLocationPermissions();
checkInternetConnection();
if (xWalkWebView != null && stateBundle != null) {
xWalkWebView.restoreState(stateBundle);
}
}
#Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause");
if (xWalkWebView != null) {
stateBundle = new Bundle();
xWalkWebView.saveState(stateBundle);
}
}
public void onSaveInstanceState(Bundle savedInstanceState) {
Log.d(TAG, "onSaveInstanceState");
// Save the user's current game state
savedInstanceState.putBundle("xwalk", stateBundle);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
#Override
public void onBackPressed() {
Log.d(TAG, "onBackPressed");
if (xWalkWebView != null && xWalkWebView.getNavigationHistory().canGoBack()) {
xWalkWebView.getNavigationHistory().navigate(XWalkNavigationHistory.Direction.BACKWARD, 1);
} else {
super.onBackPressed();
}
}
}
I have also tried to add following lines to manifest but didn't work.
android:launchMode="singleTask"
android:alwaysRetainTaskState="true"
How can i do that?
Thanks in advcance.
One way would be to initialize the view inside a fragment which is set to retain it's instance.

getLoaderManager().initLoader(); always returns a new loader when using support.v4.fragment

I'm using android.support.v4.content.AsyncTaskLoader to load data into a support.v4.fragmentbut when the configuration changes i.e : rotate the screen getLoaderManager().initLoader(); always returns a new loader thus loadInBackground() is called again . When I tried to use a normal fragment not the support.v4 version and changed to the normal AsyncTaskLoader every thing worked as expected ,so i'm not sure if this is a bug in the support library or what?
TestAsync.class:
import android.support.v4.content.AsyncTaskLoader;
public class TestAsync extends AsyncTaskLoader<List<Movie>> {
public TestAsync(Context context) {
super(context);
}
#Override
public void deliverResult(List<Movie> data) {
if (isReset()) {
// An async query came in while the loader is stopped. We
// don't need the result.
if (data != null) {
onReleaseResources(data);
}
}
List<Movie> oldData = mData;
mData = data;
if (isStarted()) {
// If the Loader is currently started, we can immediately
// deliver its results.
super.deliverResult(data);
}
// At this point we can release the resources associated with
// 'oldApps' if needed; now that the new result is delivered we
// know that it is no longer in use.
if (oldData != null) {
onReleaseResources(oldData);
}
}
#Override
protected void onStartLoading() {
super.onStartLoading();
if (mData != null || oneShot){
deliverResult(mData);
}else {
forceLoad();
}
}
#Override
protected void onStopLoading() {
cancelLoad();
}
#Override public void onCanceled(List<Movie> data) {
super.onCanceled(data);
// At this point we can release the resources associated with 'apps'
// if needed.
onReleaseResources(data);
}
/**
* Handles a request to completely reset the Loader.
*/
#Override protected void onReset() {
super.onReset();
// Ensure the loader is stopped
onStopLoading();
// At this point we can release the resources associated with 'apps'
// if needed.
if (mData != null) {
onReleaseResources(mData);
mData = null;
}
}
protected void onReleaseResources(List<Movie> apps) {
// For a simple List<> there is nothing to do. For something
// like a Cursor, we would close it here.
}
}
BrowseMoviesActivityFragment:
public class BrowseMoviesActivityFragment extends Fragment implements LoaderManager.LoaderCallbacks<List<Movie>> {
#Override
public Loader<List<Movie>> onCreateLoader(int id, Bundle args) {
return new TestAsync(mContext);
}
#Override
public void onLoadFinished(Loader<List<Movie>> loader, List<Movie> data) {
if (data != null) {
if (adapter.isEmpty()){
adapter.add(data);
gridView.setAdapter(adapter);
}else {
adapter.add(data);
adapter.notifyDataSetChanged();
}
}
}
#Override
public void onLoaderReset(Loader<List<Movie>> loader) {
adapter = new BrowseMoviesAdapter(getActivity(),new ArrayList<Movie>());
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mContext = activity;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle args = new Bundle();
getLoaderManager().initLoader(id, args, this);
}
}
BrowseMoviesActivity:
import android.support.v7.app.AppCompatActivity;
public class BrowseMoviesActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_browse);
android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
BrowseMoviesActivityFragment browseFragment = (BrowseMoviesActivityFragment) fm.findFragmentByTag(TAG_BROWSE_FRAGMENT);
if (savedInstanceState == null){
if (browseFragment==null){
browseFragment = new BrowseMoviesActivityFragment();
fm.beginTransaction().replace(R.id.browse_container, browseFragment).commit();
}
}

In which case getFragmentManager() return null?

Problem : getFragmentManager() return null randomly.
Case: I have one activity with tab. On each tab press I'm replacing the content container with fragment. In case of two fragment I'm doing network hit to fetch data from a server. For that I have written the following code:
public class FetchMessagesyFragmentTask extends Fragment {
private static final String TAG_EXTRA = "tab_extra";
private static final String TAG = "Test";
private String mData;
public static final FetchMessagesyFragmentTask newInstance(String data) {
FetchMessagesyFragmentTask fragment = new FetchMessagesyFragmentTask();
Bundle bundle = new Bundle();
bundle.putString(TAG_EXTRA, data);
fragment.setArguments(bundle);
return fragment;
}
public static interface TaskCallbacks {
void onPreExecute();
void onCancelled();
void onPostExecute(MessageResponse response);
}
private TaskCallbacks mCallbacks;
private FetchMessage mTask;
private boolean mRunning;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (!(getTargetFragment() instanceof TaskCallbacks)) {
throw new IllegalStateException(
"Target fragment must implement the TaskCallbacks interface.");
}
mCallbacks = (TaskCallbacks) getTargetFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
mData = getArguments().getString(TAG_EXTRA);
}
#Override
public void onDestroy() {
super.onDestroy();
cancel();
}
public void execute(String data) {
if (!mRunning) {
mTask = new FetchMessage();
mTask.execute(data);
mRunning = true;
}
}
public void cancel() {
if (mRunning) {
mTask.cancel(false);
mTask = null;
mRunning = false;
}
}
public boolean isRunning() {
return mRunning;
}
private class FetchMessage extends AsyncTask<String, Void, MessageResponse> {
private ProgressDialogFragment progressDialog;
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialogFragment.Builder().setMessage(
"Please wait...").build();
progressDialog.show(((Fragment) mCallbacks).getFragmentManager(),
"task_progress");
mCallbacks.onPreExecute();
mRunning = true;
}
#Override
protected MessageResponse doInBackground(String... params) {
//Doing network hit here and returning value.
return value;
}
#Override
protected void onCancelled() {
mCallbacks.onCancelled();
mRunning = false;
}
#Override
protected void onPostExecute(MessageResponse response) {
if (mCallbacks != null) {
FragmentManager manager = ((Fragment) mCallbacks)
.getFragmentManager();
//XXXXXXXX GETTING MANAGER AS NULL HERE SOMETIME XXXXXXXXXXXXXX
progressDialog.dismiss(manager);
if (response != null) {
if (Integer.parseInt(response.getResponseCode()) == NetworkConstant.SUCCESS
&& response.getChatMessage() != null) {
saveDataToDb(response);
}
}
mCallbacks.onPostExecute(response);
mRunning = false;
}
}
private void saveDataToDb(MessageResponse response) {
//SaveToDB
}
}
}
I'm following this url to handle network hit on orientation change. I have commented the line where I'm getting the issue.
Note
This code work fine in normal situation but crash when I switch tabs very fast.

How to implement onBackPressed() & intents in fragment?

I know that onBackPressed() is a method in activity but, I want to use the functionality in fragments such that when back button is pressed, it gets redirected to another activity via Intent. Is there any solution to this ?
public class News_Events_fragment extends Fragment {
ProgressDialog pd;
ListView lv1;
SharedPreferences sharedPreferences = null;
int NotiCount;
TextView txt_title, txt_msg, textView;
Context context;
Intent intent ;
ArrayList<SliderMsgTitleModel> CurrentOfficersPastList;
NewsActivityAdapter pastAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
context = (Context) getActivity();
View rootView = inflater.inflate(R.layout.activity_news, container, false);
new AsyncTask<Void, Void, ArrayList<SliderMsgTitleModel>>() {
protected void onPreExecute() {
pd = new ProgressDialog(getActivity());
pd.setCancelable(true);
pd.setTitle("UPOA");
pd.setMessage("Please wait,loading the data...");
pd.show();
}
#Override
protected ArrayList<SliderMsgTitleModel> doInBackground(
Void... params) {
System.out.println("In Background");
CurrentOfficersPastList = new ArrayList<SliderMsgTitleModel>();
// display view for selected nav drawer item
ParseQuery<ParseObject> query = ParseQuery.getQuery("message");
query.whereEqualTo("featured_status", true);
// query.whereEqualTo("push_status", true);
query.orderByDescending("updatedAt");
query.selectKeys(Arrays.asList("title"));
query.selectKeys(Arrays.asList("message"));
try {
query.setCachePolicy(ParseQuery.CachePolicy.NETWORK_ELSE_CACHE);
List<ParseObject> results = query.find();
for (int i = 0; i < results.size(); i++) {
ParseObject object = results.get(i);
CurrentOfficersPastList.add(new SliderMsgTitleModel(
object.getString("title"), object
.getString("message")));
System.out.println("title is=="
+ object.getString("title") + "&& message is"
+ object.getString("message") + "size is"
+ CurrentOfficersPastList.size());
}
} catch (Exception e) {
e.getMessage();
}
pd.dismiss();
return CurrentOfficersPastList;
}
#SuppressWarnings("unchecked")
#Override
protected void onPostExecute(ArrayList<SliderMsgTitleModel> value) {
pd.dismiss();
/*Intent ent = new Intent(getActivity(), NewsActivity.class);
ent.putExtra("NEWSLIST", (ArrayList<SliderMsgTitleModel>) value);
startActivity(ent);
System.out.println("Value is" + value.size());*/
CurrentOfficersPastList = new ArrayList<SliderMsgTitleModel>();
CurrentOfficersPastList = value;
lv1 = (ListView) getActivity().findViewById(R.id.list_title);
pastAdapter = new NewsActivityAdapter(getActivity(), R.layout.activity_news_txt, CurrentOfficersPastList);
lv1.setAdapter(pastAdapter);
}
}.execute();
return rootView;
}
public void onBackPressed() {
// TODO Auto-generated method stub
//super.onBackPressed();
//Toast.makeText(getApplicationContext(), "click",2000).show();
String cameback="CameBack";
intent = new Intent(getActivity(),HomeActivity.class);
intent.putExtra("Comingback", cameback);
startActivity(intent);
}
}
You can interact with the fragment using a callback interface. In your activity add the following:
public class MyActivity extends Activity {
protected OnBackPressedListener onBackPressedListener;
public interface OnBackPressedListener {
void doBack();
}
public void setOnBackPressedListener(OnBackPressedListener onBackPressedListener) {
this.onBackPressedListener = onBackPressedListener;
}
#Override
public void onBackPressed() {
if (onBackPressedListener != null)
onBackPressedListener.doBack();
else
super.onBackPressed();
}
#Override
protected void onDestroy() {
onBackPressedListener = null;
super.onDestroy();
}
}
In your fragment add the following:
public class MyFragment extends Fragment implements MyActivity.OnBackPressedListener {
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
((MyActivity) getActivity()).setOnBackPressedListener(this);
}
#Override
public void doBack() {
//BackPressed in activity will call this;
}
}
Yes, There is. You should implement like this.
#Override
public void onBackPressed() {
if (fragment != null)
//user defined onBackPressed method. Not of Fragment.
fragment.onBackPressed();
} else {
//this will pass BackPress event to activity. If not called, it will
//prevent activity to get BackPress event.
super.onBackPressed();
}
}
Explanation
Check whether your fragment is initialized or not. If it is, then pass on back press event to your fragment.
If above condition not passed, just pass back press to your activity so that it will handle it.
Note
Here condition can be anything. I just take fragment initialization as an example. May be that can't be helped you. You need to define your own condition to pass it to fragment.
Edit
I created a sample application on GitHub to implement Back Stack of fragment .
Download Fragment Back Stack application.
Override onKeyDown instead of onBackPressed. Not necessarily . But this works for me
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
String cameback="CameBack";
intent = new Intent(getActivity(),HomeActivity.class);
intent.putExtra("Comingback", cameback);
startActivity(intent);
return true
}
return false;
}
You can implement onKeyListener for your fragment and call next activity within that.
I've never tried this. But i hope it may help
For Example
fragmentObject.getView().setOnKeyListener( new OnKeyListener()
{
#Override
public boolean onKey( View v, int keyCode, KeyEvent event )
{
if( keyCode == KeyEvent.KEYCODE_BACK )
{
//your code here
}
return false;
}
} );
You need to override onBackPressed method in fragment.

Android AsyncLoader: Share objects between fragmentactivity/fragment

I have a problem regarding with FragmentActivity and mutltiple Fragments inside a ViewPager.
In the FragmentActivity an object is loaded, with a AsyncTask which is used in all the other fragments. I have used the android:configChanges="orientation|keyboardHidden|keyboard" "hack" to make sure the object is only loaded once, even during a screen rotation.
However, now I would to like to display more infromation in landscape modus in one of the Fragments, so now that hack doesn't work.
I've tried implementing a AsyncLoader and the FragmentRetainInstanceSupport from the Android samples. But none of the things work:
1 - I can't get the FragmentRetainInstanceSupport get to work within the ViewPager, when I follow the sample code the onCreate() method isn't called in the worker-fragment
2 - The AsyncLoader crashes during a screen rotation...
Here is my code in which I (tried to) implement the AsyncLoader:
public class TeamActivity extends SherlockFragmentActivity implements LoaderManager.LoaderCallbacks<Response<Team>> {
ViewPager mPager;
PageIndicator mIndicator;
FragmentPagerAdapter mAdapter;
private final int MENU_FOLLOW = Menu.FIRST;
private final int MENU_UNFOLLOW = Menu.FIRST + 1;
Team team = null;
static int team_id;
public Team getTeam(){
return team;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
team_id = this.getIntent().getIntExtra("index", 0);
Log.d("Teamid",""+team_id);
getSupportLoaderManager().initLoader(0, null, this);//.forceLoad();
//getSupportLoaderManager().getLoader(0).startLoading();
//new getTeam().execute();
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
if(team != null) {
team.getNaam();
SharedPreferences keyValues = this.getSharedPreferences("teams_follow", Context.MODE_PRIVATE);
MenuItem menuItem_volg = menu.findItem(MENU_FOLLOW);
MenuItem menuItem_delete = menu.findItem(MENU_UNFOLLOW);
if(keyValues.contains(String.valueOf(team.getStartnummer()))) {
menuItem_volg.setVisible(false);
menuItem_delete.setVisible(true);
} else {
menuItem_volg.setVisible(true);
menuItem_delete.setVisible(false);
}
}
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0,MENU_UNFOLLOW,Menu.NONE, R.string.ab_verwijderen)
.setIcon(R.drawable.ic_action_delete)
.setVisible(false)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
menu.add(0,MENU_FOLLOW,Menu.NONE, R.string.ab_volgen)
.setIcon(R.drawable.ic_action_star)
.setVisible(false)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Utils.goHome(getApplicationContext());
break;
case MENU_FOLLOW:
Utils.addFavoTeam(getApplicationContext(), team);
invalidateOptionsMenu();
break;
case MENU_UNFOLLOW:
Utils.removeFavoteam(getApplicationContext(), team.getID());
invalidateOptionsMenu();
break;
}
return super.onOptionsItemSelected(item);
}
class TeamFragmentAdapter extends FragmentPagerAdapter implements TitleProvider {
ArrayList<Fragment> fragments = new ArrayList<Fragment>();
ArrayList<String> titels = new ArrayList<String>();
public TeamFragmentAdapter(FragmentManager fm) {
super(fm);
fragments.add(new TeamInformatieFragment());
titels.add("Informatie");
fragments.add(new TeamLooptijdenFragment());
titels.add("Routetijden");
}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getCount() {
return fragments.size();
}
#Override
public String getTitle(int position) {
return titels.get(position);
}
}
private class getTeam extends AsyncTask<Void, Void, Void> {
private ProgressDialog progressDialog;
Response<Team> response;
protected void onPreExecute() {
progressDialog = ProgressDialog.show(TeamActivity.this,
"Bezig met laden", "Team wordt opgehaald...", true);
progressDialog.setCancelable(true);
progressDialog.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
cancel(true);
Utils.goHome(TeamActivity.this);
}
});
}
#Override
protected Void doInBackground(Void... arg0) {
if(!isCancelled())
response = api.getTeamByID(team_id);
return null;
}
#Override
protected void onPostExecute(Void result) {
if(Utils.checkResponse(TeamActivity.this, response)) {
setContentView(R.layout.simple_tabs);
team = response.getResponse();
mAdapter = new TeamFragmentAdapter(getSupportFragmentManager());
mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mIndicator = (TabPageIndicator)findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
invalidateOptionsMenu();
progressDialog.dismiss();
}
}
}
public static class AppListLoader extends AsyncTaskLoader<Response<Team>> {
Response<Team> response;
public AppListLoader(Context context) {
super(context);
}
#Override public Response<Team> loadInBackground() {
response = api.getTeamByID(team_id);
return response;
}
#Override public void deliverResult(Response<Team> response) {
if (isReset()) {
return;
}
this.response = response;
super.deliverResult(response);
}
#Override protected void onStartLoading() {
if (response != null) {
deliverResult(response);
}
if (takeContentChanged() || response == null) {
forceLoad();
}
}
#Override
protected void onStopLoading() {
// Attempt to cancel the current load task if possible.
cancelLoad();
}
#Override
protected void onReset() {
super.onReset();
// Ensure the loader is stopped
onStopLoading();
response = null;
}
}
private ProgressDialog progressDialog;
#Override
public Loader<Response<Team>> onCreateLoader(int arg0, Bundle arg1) {
progressDialog = ProgressDialog.show(TeamActivity.this,
"Bezig met laden", "Team wordt opgehaald...", true);
progressDialog.setCancelable(true);
progressDialog.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
finish();
}
});
return new AppListLoader(this);
}
#Override
public void onLoadFinished(Loader<Response<Team>> loader, Response<Team> response) {
//Log.d("Loader", "Klaar");
if(Utils.checkResponse(TeamActivity.this, response)) {
team = response.getResponse();
setContentView(R.layout.simple_tabs);
mAdapter = new TeamFragmentAdapter(getSupportFragmentManager());
mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mIndicator = (TabPageIndicator)findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
invalidateOptionsMenu();
progressDialog.dismiss();
}
}
#Override
public void onLoaderReset(Loader<Response<Team>> arg0) {
//Utils.goHome(this);
}
}
Fragment (example):
public class TeamInformatieFragment extends SherlockFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Team team = ((TeamActivity)this.getActivity()).getTeam();
//ERROR ON NEXT LINE AFTER SCREEN ROTATION:
getSherlockActivity().getSupportActionBar().setTitle(team.getNaam());
View view = inflater.inflate(R.layout.team_informatie, container, false);
return view;
}
}
The method is called from the fragments (with getActivity().getTeam()) but after a screen rotation getTeam() returns null;
I think the fragments are calling getTeam() too fast, before the variable team has been initialized(?)
Can you please help me?
Thank you!
This is probably not what you want to hear, but I recommend getting rid of
android:configChanges="orientation|keyboardHidden|keyboard"
It's an ugly hack, and a lot of the newer SDK elements like Loaders will break if you don't handle configuration changes correctly. Let Android handle the config changes, and design your code around that.

Categories

Resources