Allow one handler for Runnable? - android

Im trying to implement Interstitial Ads in my app. Im using a handler with postDelayed to delay the showing of the interstitial ad by 10 seconds.
My small app uses fragments. I have fragment 1 which contains a button to go to fragment 2 via fragment replacement transaction.
A problem im having is multiple instances of the same task being made which results into more than 1 interstitial ad showing (which is not good). This happens if you go into fragment 2, press back and then go into fragment 2 again.
What I want is a way to only allow a single handler (1 message) for this runnable. To prevent multiple ads from appearing
My main activity
public class MainActivity extends ActionBarActivity {
private ViewGroup container;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState == null)
{
container = (ViewGroup)findViewById(R.id.container);
if(container != null)
{
Fragment1 fragment1 = new Fragment1();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(container.getId(), fragment1, Fragment1.class.getName());
fragmentTransaction.commit();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume()
{
// TODO Auto-generated method stub
super.onResume();
int isAvaiable = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if(isAvaiable == ConnectionResult.SUCCESS)
{
Log.d("TEST", "GPS IS OK");
}
else if(isAvaiable == ConnectionResult.SERVICE_MISSING ||
isAvaiable == ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED ||
isAvaiable == ConnectionResult.SERVICE_DISABLED)
{
GooglePlayServicesUtil.getErrorDialog(isAvaiable, this, 10).show();
}
}
}
Fragment 1
public class Fragment1 extends Fragment implements OnClickListener {
private Button bFragmentB;
private ViewGroup container;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_1, container, false);
this.container = container;
bFragmentB = (Button)view.findViewById(R.id.bFragmentB);
bFragmentB.setOnClickListener(this);
return view;
}
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
switch(arg0.getId())
{
case R.id.bFragmentB:
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(container.getId(),new Fragment2(),Fragment2.class.getName());
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
break;
}
}
}
Fragment 2 (which contains the interstitial ad)
public class Fragment2 extends Fragment
{
private Handler handler = new Handler();
private InterstitialAd interstitialAd;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_2, container, false);
return view;
}
#Override
public void onDestroy()
{
// TODO Auto-generated method stub
super.onDestroy();
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
interstitialAd = new InterstitialAd(getActivity());
interstitialAd.setAdUnitId(getResources().getString(R.string.banner_ad_unit_id));
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.build();
interstitialAd.loadAd(adRequest);
interstitialAd.setAdListener(new AdListener()
{
#Override
public void onAdLoaded()
{
handler.postDelayed(showInterstitialAd, 10000);
}
});
}
private Runnable showInterstitialAd = new Runnable()
{
#Override
public void run()
{
interstitialAd.show();
}
};
}
Here is a summary of the things I have tried but did not work
On fragment B onDestroy I have this code
#Override
public void onDestroy()
{
super.onDestroy();
handler.removeCallbacks(showInterstitialAd);
}
Still resulted in more than 1 instance of the task (2 ads appearing). Also is not good if the screen rotates anyway because the task would be destroyed from my understanding.
Another attempt at things
interstitialAd.setAdListener(new AdListener()
{
#Override
public void onAdLoaded()
{
if(!handler.hasMessages(1))
{
handler.sendEmptyMessage(1);
handler.postDelayed(showInterstitialAd, 10000);
}
//else do nothing
}
});
This one was pretty stupid considering a new hander object is made at the start so it would not have a message to begin with :D. The idea was to have message in the queue of 1 and if it sees 1 existing already then do not start another handler.

Looks like your old fragment2 is not getting full destryoed/GC'ed yet.
Since we are trying to get hold of the existing callback, which we created in old fragment, we need to save a reference to it, so we can delete it from handler message queue. You can do this by saving it in Application level global.
public class Global extends Application {
public Runnable oldshowInterstitialAd = null;
}
update your manifest Application with
<application android:name=".Global"
add the handler.removeCallbacks(oldshowInterstitialAd); just before posting a new one.
public void onAdLoaded()
{
handler.removeCallbacks(((Global)getApplicationContext()).oldshowInterstitialAd);
handler.postDelayed(showInterstitialAd, 10000);
((Global)getApplicationContext()).oldshowInterstitialAd = showInterstitialAd;
}
saving a reference to old fragment's member may hinder its GC'ing, but we loose the reference anyways as we update oldshowInterstitialAd with newer one.

Related

A resource was acquired at attached stack trace but never released after start splash screen using jeremyfeinstein

currently I need to create an application of wallpaper. I need to start a splash screen before enter into main screen. my main screen is developed using reference from slidingmenu. However, after start splash screen, I have got error below: Please advise and help. Thank you !!
Error after start a fragment activity after run splash screen
E/StrictMode: A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
java.lang.Throwable: Explicit termination method 'end' not called
at dalvik.system.CloseGuard.open(CloseGuard.java:184)
at java.util.zip.Inflater.<init>(Inflater.java:82)
at com.android.okio.GzipSource.<init>(GzipSource.java:57)
Splash Screen activity
public class SplashScreen extends SherlockActivity {
// Splash screen timer
private static int SPLASH_TIME_OUT = 2000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
new Handler().postDelayed(new Runnable() {
/*
* Showing splash screen with a timer. This will be useful when you
* want to show case your app logo / company
*/
#Override
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
Intent i = new Intent(SplashScreen.this, FragmentChangeActivity.class);
startActivity(i);
// close this activity
finish();
}
}, SPLASH_TIME_OUT);
}
}
Fragment Activity
public class FragmentChangeActivity extends MainActivity {
private Fragment mContent;
public FragmentChangeActivity() {
super(R.string.changing_fragments);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set the Above View
if (savedInstanceState != null)
mContent = getSupportFragmentManager().getFragment(savedInstanceState, "mContent");
if (mContent == null)
mContent = new ColorFragment(R.color.red);
// set the Above View
setContentView(R.layout.content_frame);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame, mContent)
.commit();
// set the Behind View
setBehindContentView(R.layout.menu_frame);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.menu_frame, new ColorMenuFragment())
.commit();
// customize the SlidingMenu
getSlidingMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
getSupportFragmentManager().putFragment(outState, "mContent", mContent);
}
public void switchContent(Fragment fragment) {
mContent = fragment;
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame, fragment)
.commit();
getSlidingMenu().showContent();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.share:
new AlertDialog.Builder(this)
.setTitle(R.string.share)
.setMessage(Html.fromHtml(getString(R.string.apache_license)))
.show();
break;
case R.id.info:
new AlertDialog.Builder(this)
.setTitle(R.string.info)
.setMessage(Html.fromHtml(getString(R.string.about_msg)))
.show();
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.example_list, menu);
return true;
}
}
Remove the
public MainActivity(int titleRes) {
mTitleRes = titleRes;
}
Activity classes are instantiated with the no-arg constructor and your activity does not have it. Declaring an explicit constructor prevents the implicit no-arg constructor from being generated.
To pass parameters to activities, use the extras Bundle with the Intent. Start an Activity with a parameter
I am able to display the splash screen now. Here is the code:
public class SplashScreen extends SherlockFragmentActivity {
// Splash screen timer
private static int SPLASH_TIME_OUT = 2000;
private PictureFragment mainFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add the fragment on initial activity setup
if (savedInstanceState == null) {
// Add the fragment on initial activity setup
mainFragment = new PictureFragment();
getSupportFragmentManager()
.beginTransaction()
.add(android.R.id.content, mainFragment)
.commit();
} else {
// Or set the fragment from restored state info
mainFragment = (PictureFragment) getSupportFragmentManager()
.findFragmentById(android.R.id.content);
}
}
}
Here is the code to display splash screen image
public class PictureFragment extends SherlockFragment {
// Splash screen timer
private static int SPLASH_TIME_OUT = 2000;
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_splash, container, false);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(getActivity(), FragmentChangeActivity.class);
startActivity(i);
getActivity().finish();
}
}, SPLASH_TIME_OUT);
return view;
}
}

getting nullPointerException when trying to call fragment method in my Activity?

I am trying to do something relatively basic by drawing a circle on a fragments layout when the app user presses down on the screen. essentially drawing a small circle on the area of the screen where a user presses. So i started with a basic project with a fragment in the main layout.I have a gestures class that extends simpleOnGestureListener. this returns the coordinates for my circle to the main activity. this works fine. but in my onTouchEvent method in the main activity when i call frag.drawCircle() i get a nullpointerexception and I am not too sure why this is. below is the code for my MainActivity. i think I am doind everything correctly including getting the fragment using the fragmentmanager and using its "tag" to retrieve the fragment? below is the code for my main class.
public class Circles extends Activity {
private GestureDetector detector;
private PlaceholderFragment frag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_circles);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.activitylayout, new PlaceholderFragment(),"myfrag")
.commit();
}
detector = new GestureDetector(this, new Gestures());
FragmentManager manager = getFragmentManager();
frag = (PlaceholderFragment) manager.findFragmentByTag("myfrag");
}
#Override
public boolean onTouchEvent(MotionEvent event)
{
boolean consumed = detector.onTouchEvent(event);
float x = Gestures.x;
float y = Gestures.y;
if(consumed)
{
Log.d("consumed? ", String.valueOf(consumed));
Log.d("x : ", String.valueOf(x));
Log.d("y : ", String.valueOf(y));
frag.drawCircle();
}
return super.onTouchEvent(event);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.circles, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_circles, container, false);
return rootView;
}
public void drawCircle()
{
Log.d("stuff", "draw circle here!");
}
}
}
obviously the fragments isn't being instantiated properly. I am just not too sure why that is at present. any help is greatly appreciated.
Override onResume method and try moving this code in onResume
FragmentManager manager = getFragmentManager();
frag = (PlaceholderFragment) manager.findFragmentByTag("myfrag");
A better solution will be doing everything in onCreate(). Doing in onResume will just destroy the meaning of having onCreate and moreover just confuse the control flow if reference of that fragment is required before the execution of onResume.
Instread of putting everything in one statement, just break it and make it fit your need.
Here is the code
private PlaceholderFragment frag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_circles);
if (savedInstanceState == null) {
frag = new PlaceHolderFragment();
getFragmentManager().beginTransaction()
.add(R.id.activitylayout, frag ,"myfrag")
.commit();
}else{
FragmentManager manager = getFragmentManager();
frag = (PlaceholderFragment) manager.findFragmentByTag("myfrag");
}
detector = new GestureDetector(this, new Gestures());
}
This way you wont have issue getting a null reference. Since if activity is recreated the Fragment will be in backstack so you can retrieve it by tag. But if activity is being created forthe first time then first get reference and then commit the transaction.

How to remove the fragments so it wont appear in the next activity?

So i've just started doing some android programing, and I'm already stuck! My problem is; I want want my fragment, from MainActivity, to NOT be a part of my new Activity. I want the activity to be all blank, the fragment from MainActivity should be gone, buuut it's not.
The content from the "fragmentz" xml document, which is "linked" in the Fragment Class. Should NOT appear in the second Activity... Where in the SecondActivity have I associated it with the Fragment Class? This is getting frustrating :D
So here is my MainActivity code:
public class MainActivity extends ActionBarActivity {
FragmentManager manager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
manager= getSupportFragmentManager();
ArticleFragment frag = new ArticleFragment();
FragmentTransaction transaction = manager.beginTransaction();
transaction = manager.beginTransaction();
transaction.add(R.id.fragmentet,frag,"tagg");
transaction.commit();
// here the Fragment should be added to my MainActiviy
}
public void WalkForward(View view)
{
ArticleFragment frag = (ArticleFragment) manager.findFragmentByTag("tagg");
FragmentTransaction transaction = manager.beginTransaction();
transaction.remove(frag);
transaction.commit();
// Here, the fragment should disappear before the new activity start
Intent intenten = new Intent(this, SecondActivity.class);
startActivity(intenten);
// Start new activity
finish();
// I've tried this finish method, and also onDestroy and so on... But that work either. I thought the Fragments should
// disappear with its activity?
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
My Fragment Class:
public class ArticleFragment extends Fragment {
public void onAttach(Activity activity)
{
Log.d("Fraggment", "onAttach");
super.onAttach(activity);
// #17 Android FragmentTransaction Part 2: Android Application Development Development [HD 1080p]
}
public void onCreate(Bundle saveInstanceState)
{
Log.d("Fraggment", "onCreate");
super.onCreate(saveInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragmentz, container, false);
}
public void onActivityCreate(Bundle saveInstanceState)
{
Log.d("Fraggment", "onActivityCreated");
super.onActivityCreated(saveInstanceState);
}
public void onPause()
{
super.onPause();
Log.d("Fraggment", "onPause");
}
public void onStop()
{
super.onStop();
Log.d("Fraggment", "onStop");
}
public void onDestroyView()
{
super.onDestroyView();
Log.d("Fraggment", "onDestroyView");
}
public void onDestroy()
{
super.onDestroy();
Log.d("Fraggment", "onDestroy");
}
public void onDetach()
{
super.onDetach();
Log.d("Fraggment", "onDetach");
}
And my Second Activity Class:
public class SecondActivity extends MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.second, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_second,
container, false);
return rootView;
}
}
}
I hope you understand what I mean :P Is there anything I can do? Thanks in advance!
Remove this
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
from your Second Activity. And why are you extending MainActivity? Some Reason?

android fragment onorientationchange issue

I created a simple project that Button in Activity click to Show Toast from Fragment.Works fine when just click Button, but after orientation changed and clicking Button occurs error.
public class MainActivity extends Activity {
PlaceholderFragment pf;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pf = new PlaceholderFragment();
Button b = (Button)findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
pf.showToast();
}
});
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, pf)
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Log.i("TAG", "onCreateView");
return rootView;
}
public void showToast(){
Toast.makeText(getActivity(), "Show Toast from PlaceholderFragment", Toast.LENGTH_SHORT).show();
}
#Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
Log.i("TAG", "onAttach");
}
#Override
public void onDetach() {
// TODO Auto-generated method stub
super.onDetach();
Log.i("TAG", "onDetach");
}
}
}
I found out Fragment was calling onAttach and onDetach after orientating. How can i fix this problem?
When the device Orientation changes, the activity in which the fragment sits is by default destroyed and created again. You can avoid these changes by adjusting the android:configChanges in the manifest file. This code should work:
android:configChanges="keyboardHidden|orientation"

Fragment Transaction inside worker thread

Basically i tried doing a fragment transaction inside a background thread, and i get can't perform this action after onSavedInstanceState. This is what i have done:
I have an activity with two fragments, Fragment A (Contains UI all elements) and Fragment B(contains progress bar) . When the activity is created fragment A is added so the user sees UI elements(Buttons and Edittexts). Then when a button is clicked in Fragment A, (1) a background task is started in the parent activity, and (2) Fragment A is replaced with Fragment B. All this works fine.
But when the task is finished if the task was successful i would like to start a new activity and if it fails i want the current fragment to be replaced with the original one. I have no problem with starting the activity, but when i try to do the fragment transaction, the app crashes saying can't perform this action after onSavedInstanceState.
I did a lot of research on this and found a lot of useful things here, here, but i still haven't been able to solve my problem. The first link is a question on SO, one of the answers was to shift calling the fragment transaction to the onResume method of the activity, but i don't know how to do this. Also i tried using commitAllowingStateLoss and the app still crashes, but the logcat says Activity has been destroyed.
Note: If there is no configuration change, everything runs smoothly.
Here is my Code:
Containing Activity
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i("tag", "mainActivity onCreate");
Fragment taskf =getSupportFragmentManager().findFragmentByTag("taskfrag");
//Put the Fragment A if Fragment B is not showing
if(savedInstanceState == null){
if(taskf == null){
Log.i("tag", "MainFragment added");
FragmentTransaction fragmentTransaction= getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.wrapper, new MainFragment() , "mainfrag").commit();
}
}
}
//Fragment B is added here
public void addFragment(){
Log.i("tag", "fragment added");
this.getSupportFragmentManager().beginTransaction().replace(R.id.wrapper, new TaskFragment(), "taskfrag").commit();
}
// My dummy Task
public void startTask(){
Log.i("tag", "start Task");
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 100; i++) {
Log.i("tag", "publishProgress(" + i + "%)");
SystemClock.sleep(100);
}
getSupportFragmentManager().beginTransaction().replace(R.id.wrapper, new MainFragment(), "mainfrag").commitAllowingStateLoss();
}
}).start();
}
}
Fragment A
public class MainFragment extends Fragment {
View fView;
ProgressBar bar;
TextView textView;
Button button;
#Override
public void onCreate(Bundle savedInstanceState) {
Log.i("tag", "onCreate in Main Fragment ");
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
Log.i("tag", "onCreate View in Mainfragment");
fView = inflater.inflate(R.layout.mainfragment, container, false);
textView = (TextView) fView.findViewById(R.id.textview);
button = (Button) fView.findViewById(R.id.button);
//Button Click Listener
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Log.i("tag", "button clicked");
((MainActivity)getActivity()).startTask();
((MainActivity)getActivity()).addFragment();
}
});
return fView;
}
}
Fragment B
public class TaskFragment extends Fragment{
View fview;
ProgressBar bar;
#Override
public void onCreate(Bundle savedInstanceState) {
Log.i("tag", "TaskFragment Created");
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
Log.i("tag", "onCreateView in TaskFragment");
fview = inflater.inflate(R.layout.progressfragment, container, false);
bar = (ProgressBar) fview.findViewById(R.id.sendingSmsProgress);
return fview;
}
}
Thanks.

Categories

Resources