The best background processing way while using jsoup,problems with asynctask - android

I want to fetch some data from website and i am using jsoup for that.But there is a problem, when i use jsoup in an asynctask it work well but i am going to this process via a navigation view and when i click to an item it starts but navigation view is not closing and progress bar is not working,so i coulnd't know what should i do.
The question is:
Should i try to use different method like(threads , asynctaskloader etc.) or is there a way to prevent these problems.
Here is my onCreateView method of fragment :
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.tab_fragment_container, container, false);
newspapers = readFromFile("20 Name.txt");
newspapersPath = readFromFile("20 Path.txt");
FetchingInstantNews fetchingInstantNews = new FetchingInstantNews((AppCompatActivity)getActivity(),newspapers,newspapersPath);
try
{
cardItems = fetchingInstantNews.execute().get();
}
catch (Exception ex)
{
ex.printStackTrace();
}
mRecylerView = (RecyclerView)rootView.findViewById(R.id.recyclerView);
setupRecyclerView(mRecylerView);
return rootView;
}
Here is my asynctask class:
public class FetchingInstantNews extends AsyncTask<Void,Void,ArrayList<CardItem>>
{
private String[] newspapers,newspapersPath;
private AppCompatActivity activity;
private ProgressDialog progressDialog;
private Document doc,innerDoc;
private Elements[] elementses = new Elements[14];
private static String site,innerSite;
public FetchingInstantNews(AppCompatActivity activity,String[] newspapers,String[] newspapersPath)
{
this.newspapers = newspapers;
this.newspapersPath = newspapersPath;
this.activity = activity;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = new ProgressDialog(activity);
progressDialog.setTitle("Haberler");
progressDialog.setMessage("Haberleriniz Hazırlanıyor..");
progressDialog.setIndeterminate(false);
}
#Override
protected ArrayList<CardItem> doInBackground(Void... voids)
{
ArrayList<CardItem> cardViews = new ArrayList<>();
for(int i=0;i<newspapers.length;i++)
{
site = newspapersPath[i];
try
{
doc = Jsoup.connect(site).timeout(120*1000)
.userAgent("Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/25.0")
.referrer("http://www.google.com")
.get();
elementses[0] = doc.select("div[class=wrapper-new]");
elementses[1] = elementses[0].select("section[id=top]");
elementses[2] = elementses[1].select("section[class=manset-wrap c]");
elementses[3] = elementses[2].select("div[class=site-box box box-list]");
elementses[4] = elementses[3].select("div[class=us]");
elementses[5] = elementses[4].select("div[class=sol]");
elementses[6] = elementses[5].select("div[class=manset]");
elementses[7] = elementses[6].select("div[class=m-item]");
elementses[8] = elementses[7].select("article");
int perCount=0;
for (Element articleItem : elementses[8])
{
if(perCount >= 3)
{
break;
}
CardItem cardItem = new CardItem();
elementses[9] = articleItem.select("a");
cardItem.setPubDate(elementses[9].select("meta[itemprop=datePublished]").attr("content")); //Date
cardItem.setDescription(elementses[9].select("meta[itemprop=headline]").attr("content")); // desc
cardItem.setThumbnailUrl(elementses[9].select("img").attr("data-src")); // thumb
try
{
elementses[10] = elementses[6].select("nav");
elementses[11] = elementses[10].select("div[class=sol]").select("span");
cardItem.setName(elementses[11].text().replace("Son","")); // title
}
catch (Exception ex)
{
ex.printStackTrace();
}
try
{
innerSite = elementses[9].attr("href");
innerDoc = Jsoup.connect(innerSite).timeout(100*1000)
.userAgent("Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/25.0")
.referrer("http://www.google.com")
.get();
elementses[12] = innerDoc.select("div[class=flexwrap]");
elementses[13] = elementses[12].select("iframe");
cardItem.setPath(elementses[13].attr("src"));
}
catch (Exception ex)
{
ex.printStackTrace();
}
perCount++;
cardViews.add(cardItem);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
return cardViews;
}
#Override
protected void onPostExecute(ArrayList<CardItem> aVoid)
{
progressDialog.dismiss();
super.onPostExecute(aVoid);
}
}
Here is my Main Activity:
private Toolbar mToolbar;
private DrawerLayout mDrawerLayout;
private NavigationView mNavigationView;
private ActionBarDrawerToggle mActionBarDrawerToggle;
private RelativeLayout mStockLayout;
private TabLayout mTabLayout;
private FragmentManager mFragmentManager;
private FragmentTransaction mFragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mNavigationView = (NavigationView) findViewById(R.id.navigation_view);
if (mNavigationView != null)
{
setupDrawerContent(mNavigationView);
}
mActionBarDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, mToolbar, R.string.app_name, R.string.app_name) {
#Override
public void onDrawerOpened(View drawerView)
{
super.onDrawerOpened(drawerView);
}
#Override
public void onDrawerClosed(View drawerView)
{
super.onDrawerClosed(drawerView);
}
};
mFragmentTransaction.replace(R.id.frame,new TabFragmentsContainer());
mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);
mActionBarDrawerToggle.syncState();
}
private void setupDrawerContent(NavigationView navigationView)
{
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener()
{
#Override
public boolean onNavigationItemSelected(MenuItem menuItem)
{
menuItem.setChecked(true);
switch (menuItem.getItemId())
{
case R.id.anasayfa:
mDrawerLayout.closeDrawers();
changeFragment(new FragmentsContainer(),true);
break;
case R.id.anlık:
if(mDrawerLayout.isDrawerOpen(mNavigationView))
{
mDrawerLayout.closeDrawer(mNavigationView);
}
else
{
mDrawerLayout.openDrawer(mNavigationView);
}
changeFragment(new TabFragmentsContainer(),false);
break;
case R.id.ilkler:
Log.d("Frag","İlkler");
break;
case R.id.ulusal:
Log.d("Frag","Ulusal");
break;
}
return true;
}
});
}
Thanks in advance!.

Here's the thing, you really should not use your AsyncTask with get(). The get() method will block your UI thread which is likely the reason why your progress bar is not displayed and navigation drawer not closing.
Instead you should implement a callback mechanism, that is, tell your AsyncTask to call you back when the task is finished. Below is an example for your case:
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.tab_fragment_container, container, false);
newspapers = readFromFile("20 Name.txt");
newspapersPath = readFromFile("20 Path.txt");
FetchingInstantNews fetchingInstantNews = new FetchingInstantNews((AppCompatActivity)getActivity(),newspapers,newspapersPath);
try
{
fetchingInstantNews.execute(); // do not call get()
}
catch (Exception ex)
{
ex.printStackTrace();
}
cardItems = new ArrayList<CardItems>(); // initialise recycler view with an empty list for now, because AsyncTask will not finish before you setup RecyclerView.
mRecylerView = (RecyclerView)rootView.findViewById(R.id.recyclerView);
setupRecyclerView(mRecylerView);
return rootView;
}
// This method is called AFTER asynctask is finished
public void stepsAfterAsyncTask(ArrayList<CardItem> result)
{
cardItems = result;
// Re-initialise adapter with result data
mRecylerView = (RecyclerView)rootView.findViewById(R.id.recyclerView);
setupRecyclerView(mRecylerView);
// make sure you notify adapter to use the new cardItems
mRecylerView.getAdapter().notifyDataSetChanged();
}
Your AsyncTask:
public class FetchingInstantNews extends AsyncTask<Void,Void,ArrayList<CardItem>>
{
private String[] newspapers,newspapersPath;
//....
//....
#Override
protected void onPostExecute(ArrayList<CardItem> result)
{
activity.stepsAfterAsyncTask(result); // call back your activity with the result
progressDialog.dismiss();
super.onPostExecute(result);
}
}
I don't know what your setupRecyclerView method looks like, so you will need to make changes according to your needs.

Related

Viewpager operations triggered on wrong reference

I am having a Viewpager where i am loading data of different categories. I want to show a custom dialog popup whenever user stays on a particular category for 5 seconds or more asking the user if he/she wants to share the content. For that i have used a custom dialog and am hiding/showing based on the condition.
But the problem is, that if i want to open the dialog if the user stays on Viewpager item at position let's say 3, the dialog is opening for the Viewpager item at position 4.
I am not sure why it's referencing the wrong Viewpager item.
I am including the code of Adapter class for the reference.
ArticleAdapter.java
public class ArticleAdapter extends PagerAdapter {
public List<Articles> articlesListChild;
private LayoutInflater inflater;
Context context;
View rootView;
View customArticleShareDialog, customImageShareDialog;
public int counter = 0;
int contentType = 0;
int userId;
public ArticleAdapter(Context context, List<Articles> articlesListChild, int userId) {
super();
this.context = context;
this.userId = userId;
this.articlesListChild = articlesListChild;
}
#Override
public int getCount() {
return articlesListChild.size();
}
#Override
public void destroyItem(View collection, int position, Object view) {
((ViewPager) collection).removeView((View) view);
}
private Timer timer;
private TimerTask timerTask;
public void startTimer() {
timer = new Timer();
initializeTimerTask();
timer.schedule(timerTask, 5*1000, 5*1000);
}
private void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
switch (contentType) {
case 1:
showShareDialog("articles");
break;
case 2:
showShareDialog("images");
break;
default :
// Do Nothing
}
}
};
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#SuppressLint("ClickableViewAccessibility")
#Override
public Object instantiateItem(ViewGroup container, final int position) {
inflater = LayoutInflater.from(container.getContext());
View viewLayout = inflater.inflate(R.layout.article_single_item, null, false);
final ImageView contentIv, imageContentIv;
final TextView sharingTextTv;
final LinearLayout articleShareBtn, articlesLayout, imagesLayout, customArticleShareDialog, customImageShareDialog;
contentIv = viewLayout.findViewById(R.id.content_iv);
articleShareBtn = viewLayout.findViewById(R.id.article_share_btn);
articlesLayout = viewLayout.findViewById(R.id.articles_layout);
imagesLayout = viewLayout.findViewById(R.id.images_layout);
imageContentIv = viewLayout.findViewById(R.id.image_content_iv);
sharingTextTv = viewLayout.findViewById(R.id.sharing_text_tv);
customArticleShareDialog = viewLayout.findViewById(R.id.articles_share_popup);
customImageShareDialog = viewLayout.findViewById(R.id.images_share_popup);
rootView = viewLayout.findViewById(R.id.post_main_cv);
viewLayout.setTag(rootView);
articleShareBtn.setTag(rootView);
// Images
if (articlesListChild.get(position).getArticleCatId() == 1) {
articlesLayout.setVisibility(GONE);
imagesLayout.setVisibility(View.VISIBLE);
RequestOptions requestOptions = new RequestOptions();
requestOptions.placeholder(R.drawable.placeholder);
Glide.with(context)
.setDefaultRequestOptions(requestOptions)
.load(articlesListChild.get(position).getArticleImage())
.into(imageContentIv);
imageContentIv.setScaleType(ImageView.ScaleType.FIT_XY);
sharingTextTv.setText("Found this image interesting? Share it with your friends.");
counter = 0;
startTimer();
// Articles
} else if (articlesListChild.get(position).getArticleCatId() == 2){
RequestOptions requestOptions = new RequestOptions();
requestOptions.placeholder(R.drawable.placeholder);
articlesLayout.setVisibility(View.VISIBLE);
Glide.with(context)
.setDefaultRequestOptions(requestOptions)
.load(articlesListChild.get(position).getArticleImage())
.into(contentIv);
contentIv.setScaleType(ImageView.ScaleType.FIT_XY);
sharingTextTv.setText("Found this article interesting? Share it with your friends.");
counter = 0;
startTimer();
}
container.addView(viewLayout, 0);
return viewLayout;
}
public void showShareDialog(String categoryType) {
if (categoryType.equalsIgnoreCase("articles")) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
public void run() {
customArticleShareDialog.setVisibility(View.VISIBLE);
}
});
} else if (categoryType.equalsIgnoreCase("images")) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
public void run() {
customImageShareDialog.setVisibility(View.VISIBLE);
}
});
}
}
}
ArticleActivity.java
public class ArticleActivity extends AppCompatActivity {
#BindView(R.id.toolbar)
Toolbar toolbar;
#BindView(R.id.drawer_layout)
DrawerLayout drawer;
#BindView(R.id.articles_view_pager)
ViewPager articlesViewPager;
#BindView(R.id.constraint_head_layout)
CoordinatorLayout constraintHeadLayout;
private ArticleAdapter articleAdapter;
private List<List<Articles>> articlesList = null;
private List<Articles> articlesListChild = new ArrayList<>();
private List<Articles> articlesListChildNew = new ArrayList<>();
SessionManager session;
Utils utils;
final static int MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE = 1;
int userIdLoggedIn;
LsArticlesSharedPreference lsArticlesSharedPreference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
ButterKnife.bind(this);
toolbar.setTitle("");
toolbar.bringToFront();
session = new SessionManager(getApplicationContext());
if (session.isLoggedIn()) {
HashMap<String, String> user = session.getUserDetails();
String userId = user.get(SessionManager.KEY_ID);
userIdLoggedIn = Integer.valueOf(userId);
} else {
userIdLoggedIn = 1000;
}
utils = new Utils(getApplicationContext());
String storedTime = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("lastUsedDate", "");
System.out.println("lastUsedDate : " + storedTime);
if (utils.isNetworkAvailable()) {
insertData();
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
toggle.getDrawerArrowDrawable().setColor(getResources().getColor(R.color.colorWhite));
drawer.addDrawerListener(toggle);
if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE);
}
articleAdapter = new ArticleAdapter(getApplicationContext(), articlesListChild, userIdLoggedIn);
toggle.syncState();
clickListeners();
toolbar.setVisibility(View.GONE);
} else {
Intent noInternetIntent = new Intent(getApplicationContext(), NoInternetActivity.class);
startActivity(noInternetIntent);
}
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
finishAffinity();
super.onBackPressed();
}
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
finish();
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_refresh:
articleAdapter.notifyDataSetChanged();
insertData();
Toast.makeText(this, "Refreshed", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#SuppressLint("ClickableViewAccessibility")
public void clickListeners() {
}
private void insertData() {
Intent intent = new Intent(getBaseContext(), OverlayService.class);
startService(intent);
final SweetAlertDialog pDialog = new SweetAlertDialog(ArticleActivity.this, SweetAlertDialog.PROGRESS_TYPE);
pDialog.getProgressHelper().setBarColor(getResources().getColor(R.color.colorPrimary));
pDialog.setTitleText("Loading");
pDialog.setCancelable(false);
pDialog.show();
Api.getClient().getHomeScreenContents(userIdLoggedIn, new Callback<ArticlesResponse>() {
#Override
public void success(ArticlesResponse articlesResponse, Response response) {
articlesList = articlesResponse.getHomeScreenData();
if (!articlesList.isEmpty()) {
for (int i = 0; i < articlesList.size(); i++) {
articlesListChildNew = articlesList.get(i);
articlesListChild.addAll(articlesListChildNew);
}
articleAdapter = new ArticleAdapter(getApplicationContext(), articlesList, articlesListChild, userIdLoggedIn, toolbar);
articlesViewPager.setAdapter(articleAdapter);
articleAdapter.notifyDataSetChanged();
pDialog.dismiss();
} else {
List<Articles> savedArticles = lsArticlesSharedPreference.getFavorites(getApplicationContext());
if (!savedArticles.isEmpty()) {
articleAdapter = new ArticleAdapter(getApplicationContext(), articlesList, savedArticles, userIdLoggedIn, toolbar);
articlesViewPager.setAdapter(articleAdapter);
articleAdapter.notifyDataSetChanged();
pDialog.dismiss();
} else {
Api.getClient().getAllArticles(new Callback<AllArticlesResponse>() {
#Override
public void success(AllArticlesResponse allArticlesResponse, Response response) {
articlesListChild = allArticlesResponse.getArticles();
articleAdapter = new ArticleAdapter(getApplicationContext(), articlesList, articlesListChild, userIdLoggedIn, toolbar);
articlesViewPager.setAdapter(articleAdapter);
articleAdapter.notifyDataSetChanged();
};
#Override
public void failure(RetrofitError error) {
Log.e("articlesData", error.toString());
}
});
pDialog.dismiss();
}
}
}
#Override
public void failure(RetrofitError error) {
pDialog.dismiss();
Toast.makeText(ArticleActivity.this, "There was some error fetching the data.", Toast.LENGTH_SHORT).show();
}
});
}
}
Issue reason:
You face this issue because the viewpager preload fragments in background. It means that when you see 3rd fragment, the viewpager is instantiating 4th. Due to this workflow your timer for 3rd screen is cancelled and timer for 4th screen is started. Check out this link to understand what is going on.
Solution:
I would do next:
Then set page change listener for your adapter. How to do it
In this listener you can get current page and start timer for this page (and cancel timer for previously visible page).
You don't need to call startTimer() method when you instantiate item in instantiateItem() method.

ProgressDialog not showing up within a Fragment

I have the following class:
...
public class FragmentMapa extends Fragment {
/*
* Atributos
*/
private static String LOG_TAG = "FragmentMapa";
private HomeActivity homeActivity;
private GoogleMap mMapa;
private DrawerLayout mDrawer;
private ActionBarDrawerToggle mDrawerToggle;
private ListView mDrawerList;
private ListView mDrawerRightList;
private RelativeLayout mDrawerRelativeLayout;
private String[] mRightDrawerMenuTitles;
private ImageView mDiputacionLogo;
private IncidenciasFetchAsyncTask mFetchIncidenciasTask;
private Incidencias mIs;
private CamarasFetchAsyncTask mFetchCamarasTask;
private Camaras mCams;
private ViabilidadesInvernalesFetchAsyncTask mFetchViabilidadesInvernalesTask;
private ViabilidadesInvernales mVis;
private static LatLng POS_CENTRAL = new LatLng(43.243968,-2.896957);
private static LatLng limiteSurOesteBizkaia = new LatLng(42.895853,-3.594589);
private static LatLng limiteNorEsteBizkaia = new LatLng(43.540351,-2.180099);
private static final LatLngBounds BOUNDS = new LatLngBounds(limiteSurOesteBizkaia, limiteNorEsteBizkaia);
private ArrayList<Marker> markersIncidencias = new ArrayList<Marker>();
private ArrayList<Marker> markersObras = new ArrayList<Marker>();
private ArrayList<Marker> markersCamaras = new ArrayList<Marker>();
private ArrayList<Marker> markersViabilidadInvernal = new ArrayList<Marker>();
/*
* Métodos
*/
public FragmentMapa() {
}
#Override
public void onAttach (Activity activity) {
super.onAttach(activity);
homeActivity = (HomeActivity) activity;
mRightDrawerMenuTitles = getResources().getStringArray(R.array.mapa_submenu_options);
mDrawer = homeActivity.getmDrawer();
mDrawerRightList = homeActivity.getmDrawerRightList();
mDrawerRightList.setAdapter(new ArrayAdapter<String>(
homeActivity.getSupportActionBar().getThemedContext(),
R.layout.rightdrawer_map_list_item,
mRightDrawerMenuTitles
));
mDrawerRightList.setOnItemClickListener(new DrawerItemClickListener());
}
#Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.mapa, container, false);
setupMapIfNeeded();
return rootView;
}
private void setupMapIfNeeded() {
if( mMapa == null ){
SupportMapFragment smf = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapaPrincipal);
if( smf != null ){
//Toast.makeText(getActivity(), "VAAAMOOSS", Toast.LENGTH_SHORT).show();
mMapa = smf.getMap();
}/*else{
Toast.makeText(getActivity(), "smf es null...", Toast.LENGTH_SHORT).show();
}*/
if( mMapa != null ){
setupMap();
}
}
}
private void setupMap() {
//Toast.makeText(getActivity(), "A configurar el mapa!!", Toast.LENGTH_SHORT).show();
CameraPosition camPos;
camPos = new CameraPosition.Builder()
.target(POS_CENTRAL)
.zoom((float) 9.5)
.build();
final CameraUpdate camUpd =
CameraUpdateFactory.newCameraPosition(camPos);
mMapa.animateCamera(camUpd);
mMapa.setOnCameraChangeListener(new OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition newPos) {
float maxZoom = 17.0f;
if( !BOUNDS.contains(newPos.target) ){
//Mover la cámara al centro si se
//va más allá de los límites
mMapa.animateCamera(camUpd);
}
if(newPos.zoom > maxZoom){
mMapa.animateCamera(CameraUpdateFactory.zoomTo(maxZoom));
}
}
});
mMapa.setOnInfoWindowClickListener( new OnInfoWindowClickListener(){
public void onInfoWindowClick(Marker aMarker) {
Toast.makeText(getActivity(), "info window pulsado", Toast.LENGTH_SHORT).show();
if( markersCamaras.contains(aMarker) ){
Camara c = mCams.getCamaraByCoord(aMarker.getPosition());
homeActivity.showCameraFragment(c);
}
}
});
}
#Override
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onViewStateRestored (Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
}
#Override
public void onStart () {
super.onStart();
}
#Override
public void onResume () {
super.onResume();
}
#Override
public void onPause () {
super.onPause();
}
#Override
public void onStop () {
super.onStop();
}
#Override
public void onDestroyView () {
super.onDestroyView();
}
#Override
public void onDestroy () {
super.onDestroy();
}
#Override
public void onDetach () {
super.onDetach();
}
/* The click listener for ListView in the navigation drawer */
private class DrawerItemClickListener implements OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final int thePos = position;
mDrawer.setDrawerListener( new DrawerLayout.SimpleDrawerListener(){
#Override
public void onDrawerClosed(View drawerView) {
boolean wasChecked = !mDrawerRightList.isItemChecked(thePos);
//Toast.makeText(homeActivity, "Item pulsado: " + wasChecked, Toast.LENGTH_SHORT).show();
mDrawerRightList.setItemChecked(thePos, !wasChecked);
switch (thePos) {
case 0:
//Incidencias
//Toast.makeText(homeActivity, "Incidencias", Toast.LENGTH_SHORT).show();
if(!wasChecked){
//Toast.makeText(homeActivity, "Incidencias estaba sin pulsar", Toast.LENGTH_SHORT).show();
getIncidenciasObras();
introducirIncidencias();
}else{
//Toast.makeText(homeActivity, "Incidencias estaba pulsado", Toast.LENGTH_SHORT).show();
removeIncidenciasMarkers();
}
break;
case 1:
//Obras
//Toast.makeText(homeActivity, "Obras", Toast.LENGTH_SHORT).show();
if(!wasChecked){
//Toast.makeText(homeActivity, "Obras estaba sin pulsar", Toast.LENGTH_SHORT).show();
getIncidenciasObras();
introducirObras();
}else{
//Toast.makeText(homeActivity, "Obras estaba pulsado", Toast.LENGTH_SHORT).show();
removeObrasMarkers();
}
break;
case 2:
//Cámaras
//Toast.makeText(homeActivity, "Cámaras", Toast.LENGTH_SHORT).show();
if(!wasChecked) {
getCamaras();
introducirCamaras();
}else
removeCamarasMarkers();
break;
case 3:
//Viabilidad invernal
//Toast.makeText(homeActivity, "Viabilidad invernal", Toast.LENGTH_SHORT).show();
if(!wasChecked){
getViabilidadesInvernales();
introducirViabilidadInvernal();
}else
removeViabilidadInvernalMarkers();
break;
default:
//Toast.makeText(homeActivity, "Default", Toast.LENGTH_SHORT).show();
break;
}
}
});
if(mDrawer.isDrawerOpen(Gravity.END))
mDrawer.closeDrawer(mDrawerRightList);
}
}
private void getViabilidadesInvernales(){
mVis = ViabilidadesInvernales.getInstance();
if(mVis.isEmptyViabilidadesInvernales()){
mFetchViabilidadesInvernalesTask = new ViabilidadesInvernalesFetchAsyncTask(homeActivity);
try {
mVis = mFetchViabilidadesInvernalesTask.execute("es").get();
} catch (InterruptedException e) {
Log.e(LOG_TAG, "Error InterruptedException: " + e.getMessage());
e.printStackTrace();
} catch (ExecutionException e) {
Log.e(LOG_TAG, "Error ExecutionException: " + e.getMessage());
e.printStackTrace();
}
}
}
...
private void introducirViabilidadInvernal() {
if(markersViabilidadInvernal.isEmpty()){
Marker aMarker;
for (ViabilidadInvernal vi : mVis.getViabilidades()) {
String estado = "";
BitmapDescriptor icon;
if(vi.getEstado() == PuertoEstado.ABIERTO){
estado = getResources().getString(R.string.mapa_puerto_abierto);
icon = BitmapDescriptorFactory.fromResource(R.drawable.marker_puertoabierto);
}else{
//vi.getEstado() == PuertoEstado.CERRADO
estado = getResources().getString(R.string.mapa_puerto_cerrado);
icon = BitmapDescriptorFactory.fromResource(R.drawable.marker_puertocerrado);
}
aMarker = mMapa.addMarker(new MarkerOptions()
.position(vi.getCoord())
.title(vi.getT())
.snippet(estado)
.icon(icon));
markersViabilidadInvernal.add(aMarker);
}
}
}
private void removeViabilidadInvernalMarkers() {
for(Marker aMarker : markersViabilidadInvernal){
aMarker.remove();
}
}
...
private class ViabilidadesInvernalesFetchAsyncTask extends AsyncTask<String, Void, ViabilidadesInvernales>{
private ProgressDialog mPd;
private HomeActivity ownerActivity;
private Context context;
private Exception exceptionToBeThrown;
public ViabilidadesInvernalesFetchAsyncTask(Activity activity){
this.ownerActivity = (HomeActivity) activity;
context = activity;
this.exceptionToBeThrown = null;
mPd = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mPd.setTitle("cargando");
mPd.setMessage("miralo");
//mPd.setTitle(getResources().getString(R.string.mapa_cargando_titulo));
//mPd.setMessage(getResources().getString(R.string.mapa_cargando, getResources().getString(R.string.mapa_cargando_elemento_viabilidad)));
mPd.setCancelable(false);
mPd.setIndeterminate(true);
mPd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mPd.show();
}
#Override
protected ViabilidadesInvernales doInBackground(String... params) {
String idioma = params[0];
if(!idioma.equalsIgnoreCase("es") && !idioma.equalsIgnoreCase("eu")){
idioma = "es";
}
SystemClock.sleep(5000);
ViabilidadesInvernalesParser vip = new ViabilidadesInvernalesParser();
ViabilidadesInvernales lasViabilidades = vip.parse(idioma);
Log.d(LOG_TAG, lasViabilidades.toString());
ViabilidadesInvernales vis = ViabilidadesInvernales.getInstance();
return vis;
}
#Override
protected void onPostExecute(ViabilidadesInvernales vis) {
super.onPostExecute(vis);
mVis = vis;
if(mPd != null){
mPd.dismiss();
}
// Check if exception exists.
//if (exceptionToBeThrown != null) {
//TODO
//ownerActivity.handleXXX();
//throw exceptionToBeThrown;
//}
}
}
....
}
The aim is to show a Dialog (ProgressDialog) when an AsyncTask is executed, so that the Dialog remains in front of the UI for a moment and then, the map (which was being shown previously) returns to the front. More exactly, you launch the application (home activity), you open the left drawer, press Mapa and go to the current fragment. An empty map is shown. You open the right drawer and press a button. Just afterwards, the process of launching AsyncTask is executed (and my desired ProgressDialog).
I don't know why, but the ProgressDialog is not being shown, but I have realised that the "sleep" process is ok (and the AsyncTask is executed properly every time).
Can anybody lend me a hand?
PS: My main activity (HomeActivity) launches fragments. The main activity has two drawers: left drawer is always visible, and right drawer is only visible when launching the FragmentMapa (the fragment I'm showing you right now). Might this issue be due to the Drawer behaviour?
THANK YOU SO MUCH
SOLVED. Anyone who faces this problem, check the following post: https://stackoverflow.com/a/3291713/828551.
You must create an interface, create an instance of it within the AsyncTask and implement the interface the main class where you launch the AsyncTask.

Call method of interface implements with child fragment From container activity Android

I'm stuck with communication between activity and fragment using interface. I have created activity with child fragment. I wanna do some stuff with continuous thread defined in activity and during that thread when I'm getting some result at that time I wanna trigger to child fragment to do something.
My Container Activity
public class MySpaceActivity extends BaseDrawerActivity {
private OnSetLastSeenListener mListner;
public static Thread mThread = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setHeaders(Const.MY_SPACE);
super.setSubmenus(Const.MY_SPACE,
Utils.getSubmenuList(Const.MY_SPACE, MySpaceActivity.this),
submenuBean);
// super.attachFragment(submenuBean);
}
#Override
public void setHeaderSubMenu(SubmenuBean subMenuBean) {
// txt_submenu.setText(subMenuBean.getSubmenu_name());
this.submenuBean = subMenuBean;
Log.print("::::: setHeaderSubMenu ::::");
super.attachFragment(submenuBean);
}
public void setsubFragment(SubmenuBean subMenuBean) {
this.submenuBean = subMenuBean;
super.attachSubFragment(submenuBean);
}
#Override
public void onBackPressed() {
super.onBackPressed();
popLastFragment();
}
private void popLastFragment() {
if (super.getNumberOfChilds() > 1) {
super.popSubFragment();
} else {
finish();
}
}
#Override
protected Fragment getFragement() {
StudentsFragment fragment = new StudentsFragment(Const.MY_SPACE,
getSubmenubean());
return fragment;
}
public SubmenuBean getSubmenubean() {
return submenuBean;
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
mThread = new Thread(new CountDownTimer(MySpaceActivity.this));
mThread.start();
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
if (mThread.isAlive()) {
mThread.interrupt();
mThread = null;
}
}
public void updateLastSeen(){
Log.print("::::::Call Interface::::::");
mListner.updateLastSeen();
}
class CountDownTimer implements Runnable {
private Context mContext;
private JSONObject mJsonObject;
private JSONArray mJsonArray;
public CountDownTimer(Context mContext) {
this.mContext = mContext;
}
// #Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
HttpChatLastSeen mChat = new HttpChatLastSeen();
mJsonObject = mChat.Http_ChatLastSeen(mContext);
String mResult = mJsonObject.getString("Result");
if (mResult.equalsIgnoreCase(String
.valueOf(Const.RESULT_OK))) {
mJsonArray = mJsonObject.getJSONArray("UserData");
for (int i = 0; i < mJsonArray.length(); i++) {
mJsonObject = mJsonArray.getJSONObject(i);
new DbStudentMasterBll(mContext).update(
"last_seen", mJsonObject
.getString("LastSeen"), Integer
.parseInt(mJsonObject
.getString("UserId")));
}
} else {
Log.print("MY LAST SEEN Response : "
+ mJsonObject.toString());
}
updateLastSeen();
Thread.sleep(15000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (Exception e) {
Log.print("ChatLastSeenThread : ", e.getMessage());
}
}
}
}
}
My Child Fragment With Interface :
public class StudentsFragment extends Fragment implements OnSetLastSeenListener{
TextView txt_submenu;
ListView list_students;
SubmenuBean submenuBean;
int Mainmenu;
MySpaceActivity mMySpaceActivity;
ArrayList<DbStudentMasterBean> studentsList;
StudentsAdapter mAdapter = null;
OnSetLastSeenListener mListner;
public StudentsFragment() {
super();
}
public StudentsFragment(int Mainmenu, SubmenuBean submenuBean) {
this.submenuBean = submenuBean;
this.Mainmenu = Mainmenu;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_students, container,
false);
mMySpaceActivity = (MySpaceActivity) getActivity();
txt_submenu = (TextView) view.findViewById(R.id.txt_submenu);
txt_submenu.setText(submenuBean.getSubmenu_name());
txt_submenu.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mMySpaceActivity.openDrawer();
}
});
list_students = (ListView) view.findViewById(R.id.list_colleagues);
studentsList = new DbStudentMasterBll(getActivity()).getAllRecords();
mAdapter = new StudentsAdapter(getActivity(), studentsList, handler);
list_students.setAdapter(mAdapter);
list_students.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
DbStudentMasterBean bean = (DbStudentMasterBean) parent
.getAdapter().getItem(position);
Message msg = new Message();
msg.what = CHAT;
msg.obj = bean;
handler.sendMessage(msg);
}
});
return view;
}
Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case CHAT:
submenuBean.setTag(VIEWCHATSTUDENT);
DbStudentMasterBean bean = (DbStudentMasterBean) msg.obj;
mMySpaceActivity.setsubFragment(submenuBean);
break;
}
};
};
#Override
public void updateLastSeen() {
// TODO Auto-generated method stub
Log.print("!!!!!!!!!Refresh Adapter!!!!!!!!!!!");
mAdapter.notifyDataSetChanged();
}
}
My Interface :
public interface OnSetLastSeenListener {
public void updateLastSeen();
}
So I have implemented interface OnSetLastSeenListener with my child fragment StudentsFragment . Now I'm calling method of tht interface updateLastSeen() from my container activity with thread. But it is not getting trigger to child fragment where I have implemented interface. So I don't know whether it is good way to communicate or not? Let me take your help to suggest on this solution or best way to communicate from child fragment to parent activity.
Thanks,
It is better to use interface when you want to communicate something from Fragment to Activity and not vice versa.
In your case, you can directly call the method in Fragment from Activity through fragment object. No need to use interface.
Something like this (For static fragments)
StudentsFragment fragment = (StudentsFragment) getFragmentManager()
.findFragmentById(R.id.fragmentid);
if (fragment != null && fragment.isInLayout()) {
fragment.updateLastSeen();
}
For dynamic fragment you can use the fragment object directly.

AsynkTask within Fragment within a ViewPager

First of all, I am relatively new to android programming.
I am creating a ViewPager application with two Fragments. One of the Fragments requests data from a server and return a result to the main FragmentActivity. My problem is that this request to the server can take sometime, and I have been trying to get a ProgressDialog to appear with AsyncTask while the user waits for the data to be retrieved. Once I create the background thread to retrieve the data, I successfully execute some code in the onPostExecute() method and set some variables. However, the return statement that sends information back to the FragmentActivity is being executed before the background thread actually ends. I can't seem to figure out a way for the main thread to wait on the background thread. Using Asyctask's get() method results in the ProgressDialog from appearing. I have looked through a lot of posts in here, but can't seem to find an answer.
Anything helps.
Code below:
SplashScreen.java
public class SplashScreen extends FragmentActivity {
MainMenu mainMenu;
MapScreen mapScreen;
PagerAdapter pagerAdapter;
ViewPager viewPager;
List<LatLng> geoPoints;
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_splash_screen);
context = this;
initializePaging();
}
private void initializePaging()
{
mainMenu = new MainMenu();
mapScreen = new MapScreen();
pagerAdapter = new PagerAdapter(getSupportFragmentManager());
pagerAdapter.addFragment(mainMenu);
pagerAdapter.addFragment(mapScreen);
viewPager = (ViewPager) super.findViewById(R.id.viewPager);
viewPager.setAdapter(pagerAdapter);
viewPager.setOffscreenPageLimit(2);
viewPager.setCurrentItem(0);
viewPager.setOnPageChangeListener(new OnPageChangeListener()
{
#Override
public void onPageScrollStateChanged(int postion){}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2){}
#Override
public void onPageSelected(int position)
{
switch(position){
case 0: findViewById(R.id.first_tab).setVisibility(View.VISIBLE);
findViewById(R.id.second_tab).setVisibility(View.INVISIBLE);
break;
case 1: findViewById(R.id.first_tab).setVisibility(View.INVISIBLE);
findViewById(R.id.second_tab).setVisibility(View.VISIBLE);
break;
}
}
});
}
//Called from onClick in main_mainu.xml
public void getDirections(View view)
{
InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
try
{
geoPoints = mainMenu.getDirections(context);
mapScreen.plotPoints(geoPoints);
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), "Error! Invalid address entered.", Toast.LENGTH_LONG).show();
mainMenu.clear();
}
}
}
MainMenu.java
public class MainMenu extends Fragment {
String testString;
int testInt;
TextView testTV;
private TextView tvDisplay;
private EditText departure;
private EditText destination;
private Geocoder geocoder;
private List<Address> departAddress;
private List<Address> destinationAddress;
private List<LatLng> geoPoints;
private String departString;
private String destinationString;
private Address departLocation;
private Address destinationLocation;
private LatLng departurePoint;
private LatLng destinationPoint;
private Context contextMain;
private GetData task;
public MainMenu()
{
super();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View root = (View) inflater.inflate(R.layout.main_menu, null);
geoPoints = new ArrayList<LatLng>(2);
return root;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
departure = (EditText) getView().findViewById(R.id.depart_field);
destination = (EditText) getView().findViewById(R.id.destination_field);
tvDisplay = (TextView) getView().findViewById(R.id.textView1);
}
public List<LatLng> getDirections(Context context)
{
contextMain = context;
geocoder = new Geocoder(getActivity());
departString = departure.getText().toString();
destinationString = destination.getText().toString();
try
{
task = new GetData(new Callback(){
public void run(Object result)
{
//return geoPoints;
}
});
task.execute((Void[])null);
}catch(Exception e)
{
e.printStackTrace();
}
return geoPoints;
}
public void clear()
{
departure.setText("");
destination.setText("");
tvDisplay.setText("Enter departure point, and destination point");
}
private class GetData extends AsyncTask<Void, Void, List<List<Address>>>
{
Callback callback;
private ProgressDialog processing;
public GetData(Callback callback)
{
this.callback = callback;
}
#Override
protected void onPreExecute()
{
processing = new ProgressDialog(contextMain);
processing.setTitle("Processing...");
processing.setMessage("Please wait.");
processing.setCancelable(false);
processing.setIndeterminate(true);
processing.show();
}
#Override
protected List<List<Address>> doInBackground(Void...arg0)
{
List<List<Address>> list = new ArrayList<List<Address>>(2);
try
{
departAddress = geocoder.getFromLocationName(departString, 5, 37.357059, -123.035889, 38.414862, -121.723022);
destinationAddress = geocoder.getFromLocationName(destinationString, 5, 37.357059, -123.035889, 38.414862, -121.723022);
list.add(departAddress);
list.add(destinationAddress);
}catch(IOException e)
{
e.printStackTrace();
}
return list;
}
#Override
protected void onPostExecute(List<List<Address>> list)
{
departLocation = list.get(0).get(0);
destinationLocation = list.get(1).get(0);
departurePoint = new LatLng(departLocation.getLatitude(), departLocation.getLongitude());
destinationPoint = new LatLng(destinationLocation.getLatitude(), destinationLocation.getLongitude());
if(geoPoints.size() >= 2)
{
geoPoints.clear();
}
geoPoints.add(departurePoint);
geoPoints.add(destinationPoint);
callback.run(list);
processing.dismiss();
}
}
}
#Override
protected Object doInBackground(Void...arg0)
{
Object result = null;
try
{
departAddress = geocoder.getFromLocationName(departString, 5, 37.357059, -123.035889, 38.414862, -121.723022);
destinationAddress = geocoder.getFromLocationName(destinationString, 5, 37.357059, -123.035889, 38.414862, -121.723022);
}catch(IOException e)
{
e.printStackTrace();
}
return result;
}
You never set the value of result...

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