Fragment orientation handle AsyncTask - android

I have tried writing asynctask within fragment so that orientation dilemma can be solveable.So far asynctask working good but the progressbar which is associated with it, on screen change, not showing .
I have attached my code below .
On Screen rotate, progressbar and textview gets hidden
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.a_fragment, container, false);
unbinder = ButterKnife.bind(this, view);
setRetainInstance(true);
return view;
}
#OnClick(R.id.btn)
public void onViewClicked() {
Log.w(TAG, "onBtn clicked");
new URLAsyncTask().execute();
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
progressBar.setVisibility(View.VISIBLE);
tvProgress.setVisibility(View.VISIBLE);
progressValue = savedInstanceState.getInt("value");
System.out.println(progressValue);
progressBar.setProgress(progressValue);
String rcv = savedInstanceState.getString("value2");
tvProgress.setText(rcv);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("value", progressBar.getProgress());
outState.putString("value2", tvProgress.getText().toString());
}
private class URLAsyncTask extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(Void... voids) {
String result = null;
for (int i = 0; i <= 20; i++) {
SystemClock.sleep(500);
System.out.println("Loading..... " + i);
publishProgress(i);
}
result = "A dummy";
return result;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressBar.setProgress(values[0]);
progressValue = values[0];
tvProgress.setText("Loading .. at % ".concat(String.valueOf(progressValue)));
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.d(TAG, "onPostExecute() : s : " + s);
System.out.println(TAG + " " + progressValue);
if (progressValue == 20) {
tvProgress.setText("LOADING 100 % DONE");
progressBar.setVisibility(View.GONE);
}
}
}
}
A bit help would be highly appreciated

I dont understand well your problem but I assume that you have problem with device orientation in fragment, that the AsynTask is reexecuting and displaying wrong percentage.
If I'm correct: Then instead using AsynTask, try this :
AsynTaskLoader
Also you can find some quality tutorial on Udacity`s Android Developer Course,
(free)
https://www.udacity.com/course/android-basics-networking--ud843

Related

How do I use onSaveInstanceState on an button's visibility in a fragment?

in my fragment, my button changes it's visibility to GONE whenever I click on it.
I want the visibility to remain GONE when i rotate my screen.
I am using onSaveInstanceState but I would like help on what to add in for the outState.
Any help would be greatly appreciated, thanks!
public class PlaylistsFragment extends Fragment {
private Button add1;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_playlists, container, false);
}
#Override
public void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.
}
#Override
public void onViewCreated(final View view, #Nullable final Bundle savedInstanceState) {
final Button add1 = (Button) getView().findViewById(R.id.p_add1);
add1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
add1.setVisibility(View.GONE);
}
});
}
}
Try this:
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// Save UI state changes to the savedInstanceState.
savedInstanceState.putInt("button_visibility", add1.getVisibility());
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
myButtonVisibility = savedInstanceState.getInt("button_visibility", 0);
}
For instance in onCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
add1 = (Button)findViewById(R.id.p_add1);
if (savedInstanceState != null) {
int buttonVisibility = savedInstanceState.getInt("button_visibility", 0);
// here will IDE complaint about setting only integer
add1.setVisibility(buttonVisibility == View.VISIBLE ? View.VISIBLE : View.GONE)
}
}
If you have more question you should definitely check out this tutorial:
saveInstanceState tutorial
Enjoy.

call AsyncTask in Fragment from an Activity

in my application, i have main_activity with a FrameLayout, and a Fragment
public class Fragment1 extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment1, container, false);
return view;
}
public class StartAsyncTask extends AsyncTask<Void,Void,Void>{
#Override
protected Void doInBackground(Void... voids) {
Log.e("startAsyncTask", "start");
return null;
}
}
}
I need to call the AsyncTask from the MainActivity,
so i use:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
Fragment1 fragment1 = new Fragment1();
fragmentTransaction.replace(R.id.fragment, fragment1).commit();
new Fragment1.StartAsyncTask().execute();
}
but it dosn't work. new Fragment1.StartAsyncTask().execute(); is in red with (is not enclosing class) error.
You Can Do Like this, From your MainActivity You can Call your AsyncTask indirectly
ublic class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
BlankFragment fragment1 = new BlankFragment();
fragmentTransaction.replace(R.id.activity_main, fragment1).commit();
fragment1.startASycnc();
}
}
And Your Fragment Looks Like This:
public class BlankFragment extends Fragment {
public BlankFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_blank, container, false);
}
public void startASycnc() {
new StartAsyncTask().execute();
}
public class StartAsyncTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
Log.e("startAsyncTask", "start");
return null;
}
}
}
StartAsyncTask is an internal class of the Fragment, not a method. If you really need to trigger something to be done in the Fragment, have it expose a public method which takes the appropriate action rather than having a class outside of it be aware of its internals.
this is how i did it
public class MyFriendsLocationUpdate extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
while (true) {
System.out.println("working 1");
if (getActivity() != null) {
System.out.println("working 2");
if (FirebaseAuth.getInstance().getCurrentUser() != null) {
System.out.println("working 3");
DatabaseReference reference = FirebaseDatabase.getInstance().getReference(Comman.FRIENDS_REF).child(FirebaseAuth.getInstance().getCurrentUser().getUid());
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
final FriendsModel friendsModel = snapshot.getValue(FriendsModel.class);
DatabaseReference reference1 = FirebaseDatabase.getInstance().getReference(Comman.PUBLIC_LOCATION_REF).child(friendsModel.getFrienduid()).child("l");
reference1.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull final DataSnapshot dataSnap) {
if (dataSnap.hasChild("0")) {
Picasso.get().load(friendsModel.getFriendimgurl())
.into(new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
if (markerFriend != null) {
markerFriend.remove();
}
double lat = (double) dataSnap.child("0").getValue();
double lng = (double) dataSnap.child("1").getValue();
System.out.println("lat = " + lat);
System.out.println("Your Friend " + friendsModel.getFriendname() + " is Here");
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(new LatLng(lat, lng));
markerOptions.icon(BitmapDescriptorFactory.fromBitmap(getMarkerBitmapFromView(bitmap)));
markerOptions.title("Your Friend " + friendsModel.getFriendname() + "");
// markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_person_marker));
markerFriend = mMap.addMarker(markerOptions);
if (isSharingValue.equals("true")) {
setupMapIfNeeded();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkLocationPermission() && checkLocation())//check whether location service is enable or not in your phone
{
setupLocation();
}
} else {
if (checkLocation())//check whether location service is enable or not in your phone
{
setupLocation();
}
}
}
}
#Override
public void onBitmapFailed(Exception e, Drawable errorDrawable) {
double lat = (double) dataSnap.child("latitude").getValue();
double lng = (double) dataSnap.child("longitude").getValue();
System.out.println("lat = " + lat);
System.out.println("You Friend " + friendsModel.getFriendname() + " is Here");
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(new LatLng(lat, lng));
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
markerOptions.title("You Friend " + friendsModel.getFriendname() + "");
// markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_person_marker));
mMap.addMarker(markerOptions);
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
for (int i = 0; i < placesArrayList.size(); i++) {
LatLng latLngplace = new LatLng(Double.parseDouble(placesArrayList.get(i).getPlacelat()), Double.parseDouble(placesArrayList.get(i).getPlacelng()));
queryForFriendInThePlace(latLngplace, (Double.parseDouble(placesArrayList.get(i).getPlaceradius()) / 1000), friendsModel.getFrienduid(), friendsModel.getFriendname(), placesArrayList.get(i).getPlacename());
}
} else {
System.out.println("result is: nofriend online");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
try {
Thread.sleep(4000);
} catch (Exception e) {
e.printStackTrace();
}
// return "Executed";
}
}
}
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
to execute it you just write
new MyFriendsLocationUpdate().execute("");

Don't call method on screen rotation

I have parent fragment called OpFragment. From this fragment are inherited all fragments in my app.
public abstract class OpFragment extends Fragment {
private Loading loading;
public abstract int getLayoutId();
public abstract void getData();
public abstract void setListeners();
protected BackHandlerInterface backHandlerInterface;
public boolean onBackPressed(){
return false;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
if(!(getActivity() instanceof BackHandlerInterface)) {
throw new ClassCastException("Hosting activity must implement BackHandlerInterface");
} else {
backHandlerInterface = (BackHandlerInterface) getActivity();
}
FragmentArgs.inject(this);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(getLayoutId(), container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if(!isAdded()){
return;
}
getData();
setListeners();
}
protected String returnName() {
return null;
}
public void showTitle() {
EventBus.getDefault().post(new ShowName(returnName()));
}
#Override
public void onDestroyView() {
super.onDestroyView();
}
public Loading getLoading() {
if (this.loading == null) {
this.loading = new Loading(this.getActivity());
}
return this.loading;
}
/**
* Gets a component for dependency injection by its type.
*/
#SuppressWarnings("unchecked")
protected <C> C getComponent(Class<C> componentType) {
return componentType.cast(((HasComponent<C>) getActivity()).getComponent());
}
#Override
public void onStart() {
super.onStart();
backHandlerInterface.setSelectedFragment(this);
}
public interface BackHandlerInterface {
void setSelectedFragment(OpFragment backHandledFragment);
}
#Override
public void onResume() {
super.onResume();
sendGAScreens();
}
private void sendGAScreens() {
final Tracker tracker = OpApp.getDefaultTracker();
if(tracker != null) {
tracker.setScreenName(getClass().getSimpleName());
tracker.send(new HitBuilders.ScreenViewBuilder().build());
}
}
}
There are methods getData() and setListeners() inside onViewCreated.
I don't want to recall this methods after screen rotation. How can I do that ?
Simply checking savedInstanceState == null not gave me expected result.
override this method to detect screen rotation in your fragment and set some flag if its screen rotation. as shown below:
#Override
public void onConfigurationChanged(Configuration newConfig)
{
Log.d("tag", "config changed");
super.onConfigurationChanged(newConfig);
int orientation = newConfig.orientation;
if (orientation == Configuration.ORIENTATION_PORTRAIT || orientation == Configuration.ORIENTATION_LANDSCAPE)
flag= true;
....
}
and in your onViewCreated() do like this
if(!flag){
// call your functions
}

Half of the lifecycle methods of fragment get not called after rotation

I'm experiencing an strange behavior of Fragment life-cycle each time that i rotate the screen. Only the first half of life-cycle methods are getting called, onPause,onSaveInstanceState,onStop, onDestroyView,onDestroy and onDetach. The other half (onAttach ...-onResume) are not getting called. The Activity associated with the Fragment is calling all its life-cycle methods.
Any help would be highly appreciated because I'm stuck on this issue.
Thanks in advance.
Here the entire code of the Activity and the static nested class where is the Fragment:
public class MoviesFeed extends AppCompatActivity {
private static boolean mTwoPane;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("ACT","onCreate");
setContentView(R.layout.themoviedb_main);
if(findViewById(R.id.detail_activity_container)!=null) {
//the detail_activity_container will be present only in large-screen
//Layouts (res/Layout-sw600dp. If this view is present, then the activity
//should be in two-pane mode
mTwoPane=true;
//In two-pane mode, show the detail view in this activity by adding
// or replacing the detail fragment using a fragment transaction
DetailActivityFragment detailActivityFragment=new DetailActivityFragment();
// Bundle bundle=new Bundle();
// bundle.putBoolean("twopane",mTwoPane);
// detailActivityFragment.setArguments(bundle);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.detail_activity_container, detailActivityFragment)
.commit();
}
} else {
mTwoPane=false;
}
}
#Override
protected void onStart() {
Log.d("ACT","onStart");
super.onStart();
}
#Override
protected void onResume() {
Log.d("ACT","onResume");
super.onResume();
}
#Override
protected void onPause() {
Log.d("ACT","onPause");
super.onPause();
}
#Override
protected void onStop() {
Log.d("ACT","onStop");
super.onStop();
}
#Override
protected void onRestart() {
Log.d("ACT","onRestart");
super.onRestart();
}
#Override
protected void onDestroy() {
Log.d("ACT","onDestroy");
super.onDestroy();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.movies_feed_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
startActivity(new Intent(this,SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
public static class MoviesFeedFragment extends Fragment implements AdapterView.OnItemClickListener {
private static final int APPROX_FIXED_IMAGE_WIDTH=170;
private GridView mGridView;
private MovieAdapter mMovieAdapter;
private ArrayList<Response.Movie> mListMovies=new ArrayList<Response.Movie>();
private TimeMeasure mTm;
private boolean mFromDetailsActivity =false;
private boolean mUserRotation=false;
private boolean mFavoritesMode=false;
#Override
public void onAttach(Activity activity) {
Log.d("FRAG", "onAttach");
super.onAttach(activity);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("FRAG", "onCreate");
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.fragment_moviesfeed, container, false);
Log.d("FRAG", "onCreateView");
mGridView= (GridView) view.findViewById(R.id.gridView);
mGridView.setOnItemClickListener(this);
mMovieAdapter = new MovieAdapter(getActivity(), mListMovies);
mGridView.setAdapter(mMovieAdapter);
//for tablets specially
// float scalefactor = getResources().getDisplayMetrics().density * APPROX_FIXED_IMAGE_WIDTH;
// Point size=new Point();
// getWindowManager().getDefaultDisplay().getSize(size);
// int number=size.x;
// int columns = (int) ((float) number / (float) scalefactor);
//
// mGridView.setNumColumns(columns);
if(savedInstanceState!=null){
mUserRotation=true;
ArrayList<Response.Movie> tempList=new ArrayList<Response.Movie>();
tempList=savedInstanceState.getParcelableArrayList("mListMovies");
mListMovies.clear();
mListMovies.addAll(tempList);
mMovieAdapter = new MovieAdapter(getActivity(), mListMovies);
mGridView.setAdapter(mMovieAdapter);
}
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
Log.d("FRAG", "onActivity");
super.onActivityCreated(savedInstanceState);
}
#Override
public void onPause() {
Log.d("FRAG", "onPause");
super.onPause();
}
#Override
public void onStop() {
Log.d("FRAG", "onStop");
super.onStop();
}
#Override
public void onSaveInstanceState(Bundle outState) {
Log.d("FRAG", "onSaveInstanceState");
super.onSaveInstanceState(outState);
outState.putParcelableArrayList("mListMovies", mListMovies);
}
#Override
public void onResume() {
Log.d("FRAG", "onResume");
super.onResume();
if (mFromDetailsActivity !=true && mUserRotation!=true) {
executeCallToMoviesApi();
} else if(mFromDetailsActivity==true && mFavoritesMode==true) {
getFavoritesMovies();
}
mFromDetailsActivity =false;
mUserRotation=false;
}
#Override
public void onDestroyView() {
Log.d("FRAG", "onDestroyView");
super.onDestroyView();
}
#Override
public void onDestroy() {
Log.d("FRAG", "onDestroy");
super.onDestroy();
}
#Override
public void onDetach() {
Log.d("FRAG", "onDetach");
super.onDetach();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (mTwoPane==true) {
DetailActivityFragment detailActivityFragment=new DetailActivityFragment();
Bundle args=new Bundle();
args.putString("movieId", String.valueOf(mListMovies.get(position).getId()));
//Response.Movie movie=new Response.Movie();
//movie.setId(mListMovies.get(position).getId());
//args.putParcelable("movie",movie);
args.putBoolean("favoritesMode",mFavoritesMode);
detailActivityFragment.setArguments(args);
getActivity().getSupportFragmentManager().beginTransaction()
.replace(R.id.detail_activity_container,detailActivityFragment)
.commit();
} else {
Intent intent = new Intent(getActivity(), DetailActivity.class);
intent.putExtra("favoritesMode", mFavoritesMode);
intent.putExtra("movieId", mListMovies.get(position).getId());
mFromDetailsActivity = true;
startActivity(intent);
}
}
public void executeCallToMoviesApi(){
SharedPreferences sharedPreferences= PreferenceManager.getDefaultSharedPreferences(getActivity());
String orderStr= sharedPreferences.getString(getString(R.string.pref_order_key),
getString(R.string.pref_order_default));
mFavoritesMode=false;
if (orderStr.equals(getString(R.string.pref_popularity))){
getActivity().setTitle(getString(R.string.mainactivity_title_popularity));
getMoviesByPopularity();
}
if (orderStr.equals(getString(R.string.pref_rate))){
getActivity().setTitle(getString(R.string.mainactivity_title_rate));
getMoviesByRate();
}
if (orderStr.equals(getString(R.string.pref_favorites))) {
getActivity().setTitle(getString(R.string.mainactivity_title_favorites));
mFavoritesMode=true;
getFavoritesMovies();
}
}
public void getMoviesByPopularity(){
ApiClient.MyApi myApi=ApiClient.getMyApiClient();
myApi.getMoviesByPopularityDesc(AppConstants.API_KEY, callbackResponse());
}
public void getMoviesByRate(){
ApiClient.MyApi myApi=ApiClient.getMyApiClient();
myApi.getMoviesByAverageRate(AppConstants.API_KEY, callbackResponse());
}
private Callback<Response> callbackResponse() {
return new Callback<Response>() {
#Override
public void success(Response response, retrofit.client.Response response2) {
// Message.displayToast(MoviesFeed.this, "success");
mListMovies.clear();
mListMovies.addAll((ArrayList) response.getResults());
mMovieAdapter = new MovieAdapter(getActivity(), mListMovies);
mGridView.setAdapter(mMovieAdapter);
}
#Override
public void failure(RetrofitError error) {
Log.v("VILLANUEVA", "error:" + error.getMessage().toString());
Message.displayToast(getActivity(), "failure" + error.getMessage().toString());
}
};
}
public void getFavoritesMovies(){
List<MovieDetail> tempListDetail;
ArrayList<Response.Movie> tempList=new ArrayList<Response.Movie>();
SharedPreferenceManager sharedPreferenceManager=new SharedPreferenceManager(getActivity());
tempListDetail = sharedPreferenceManager.getFavoritesList();
Response.Movie tempMovie;
if (tempListDetail!=null) {
for (MovieDetail movieDetail : tempListDetail) {
tempMovie = new Response.Movie();
tempMovie.setId(movieDetail.getId());
tempMovie.setPoster_path(movieDetail.getPoster_path());
tempList.add(tempMovie);
}
mListMovies.clear();
mListMovies.addAll(tempList);
}
mMovieAdapter = new MovieAdapter(getActivity(), mListMovies);
mGridView.setAdapter(mMovieAdapter);
}
}//MoviesFeedFragment
Screenshots, before and after rotation.
Before:
After:
Log

How to show ProgressDialog In Android Fragments?

I have some tabpages and fragments. And these fragments contain a GridView element. My program is going to webservice and reading JSON data, after getting images caching and populating gridviews custom grid.
Now, how can show ProgressDialog only not completed fragments? And how can I dismiss progressDialog GridView populating will complete?
My Fragment OnCreate Method;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_b, container, false);
context = getActivity();
final ProgressDialog dialog = ProgressDialog.show(context, "", "Please wait, Loading Page...", true);
GridView gridView = (GridView) v.findViewById(R.id.gridview);
if (isConnected()) {
try {
new ProgressTask(context).execute();
gridView.setAdapter(new AdapterB(context, WallPaperList));
} catch (NullPointerException e) {
e.printStackTrace();
return v;
}
} else {
Toast.makeText(v.getContext(), "Please check your internet connection..!", Toast.LENGTH_LONG).show();
}
return v;
}
its the short example for showing progress may this help you
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(DownloadImageActivity.this, "Wait", "Downloading...");
}
#Override
protected Bitmap doInBackground(String... params) {
//your downloading code
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(Bitmap bitmap) {
progressDialog.dismiss();
}
}
Check this...........
public interface AsyncTaskListener<Boolean> {
public void onCompletingTask(Boolean result);
}
public class AsyncTaskGetApiKey extends AsyncTask<Void, Void, Boolean>{
ArrayList<AsyncTaskListener<Boolean>> listeners;
public AsyncTaskLoadingInSplash() {
listeners = new ArrayList<AsyncTaskListener<Boolean>>();
}
public void addListener(AsyncTaskListener<Boolean> listener){
listeners.add(listener);
}
public void removeListener(AsyncTaskListener<Boolean> listener){
listeners.remove(listener);
}
#Override
protected Boolean doInBackground(Void... params) {
//do your activities here
return true; // If everything is fine
}
#Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
for (AsyncTaskListener<Boolean> listener:listeners) {
listener.onReceivingApiKey(result);
}
}
}
public class MyFagemnt extends Fragment
implements AsyncTaskListener<Boolean>{
AsyncTaskGetApiKey task;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//......
task = new AsyncTaskGetApiKey();
task.addListener(this);
//........
}
#Override
public void onCompletingTask(Boolean result) {
// your asyntask finished
// now close the progress bar
}
}
In AsyncTask, create progress dialog in onPreExecute() and dismiss that progress dialog in onPostExecute().
updated:
add this code in your viewpager activity.
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
//You can get Call back to show the progress dialog when swipping.
boolean isLoading = true;//Check if the fragment is still loading or not at given position.
if (isLoading) {
//Show progress dialog.
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});

Categories

Resources