I have a dialog that I want to display, and I cannot. The activity that I'm calling it from has an opengl es SurfaceViewRenderer. Some code is below. The text 'here' shows, and some of the activity from the fragment is going on in the background (I see some of the println statements from there) but no fragment is visible. I do not see 'is visible' in the logs.
public void goToFrag() {
dDial = new MYDialogFragment();
Bundle args = new Bundle();
dDial.setArguments(args);
dDial.show(getFragmentManager(), "dDialog");
if (dDial.isVisible() ) System.out.println("is visible");
System.out.println("here");
}
so here's some more info. I tried to run the 'goToFrag()' method from the 'runOnUIThread()' method and the fragment appears, but only for a second. Then the PlayActivity (what I'm calling the activity that launches the Fragment and contains the GLSurfaceRenderer) disappears. After that I'm back at the activity that calls the PlayActivity. There's no error output that I can find.
//from OpenGL SurfaceViewRenderer...
public void goToFrag() {
mPlayActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
mPlayActivity.goToFrag();
}
});
}
More code might help
public class APDuellingDialogFragment extends DialogFragment {
public boolean mDebugMessages = true;
public OnFragmentReturnListener mListener;
public View v;
public ListView mListView;
public RadioGroup radio_left_right;
public interface OnFragmentReturnListener {
public void onActivityResult(int requestCode, int resultCode, Intent data);
}
public APDuellingDialogFragment() {
mBT = new APDuellingBluetooth(this);
mList = new ArrayList<APDuellingBluetooth.MenuItem>();
mSocketsLaunched = false;
}
public static APDuellingDialogFragment newInstance() {
APDuellingDialogFragment dialog = new APDuellingDialogFragment();
//dialog.setStyle(DialogFragment.STYLE_NO_FRAME, R.style.AppTheme);
dialog.setShowsDialog(true);
dialog.setRetainInstance(true);
dialog.setCancelable(false);
return dialog;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (mDebugMessages) System.out.println("on attach");
//...
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mListener = (OnFragmentReturnListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (mDebugMessages) System.out.println("on create");
}
#Override
public void onDismiss(DialogInterface dialog) {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_ap_dueling, container, false);
if (mDebugMessages) System.out.println("on create view");
}
Button button_close = (Button)v.findViewById(R.id.duel_button_close);
button_close.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dismiss();
}
});
Button button_rescan = (Button)v.findViewById(R.id.duel_button_rescan);
button_rescan.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(mBT.isBluetoothSupported()) {
//...
}
}
});
radio_left_right = (RadioGroup) v.findViewById(R.id.duel_right_left_group);
radio_left_right.setOnCheckedChangeListener( new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
//...
}
});
Switch switch_audio = (Switch) v.findViewById(R.id.duel_switch_sound);
switch_audio.setOnCheckedChangeListener( new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
//...
}
});
mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
//...
return false;
}
});
return v;
}
public void restartGameFromFragment() {
if(mDebugMessages) System.out.println("restartgamefrom fragment");
Intent mIntent = prepareIntentForGame();
mListener.onActivityResult(AP.INTENT_ACTIVITY_DUEL_SETUP, Activity.RESULT_OK, mIntent);
dismiss();
}
public Intent prepareIntentForGame() {
Intent mIntent = new Intent();
//...
return mIntent;
}
#Override
public void onDestroy() {
super.onDestroy();
if (mDebugMessages) System.out.println("on destroy");
}
}
finally this:
public class MYActivityPlay extends Activity implements MYDuellingDialogFragment.OnFragmentReturnListener {
private MYGLSurfaceView myMYView;
public MYButtonManager mButtons;
public MYReadXML mXML;
public MYDuellingDialogFragment duelDialogFragment;
public RelativeLayout mTitleAndScoresView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mIntent = this.getIntent();
mMode = mIntent.getIntExtra(MY.INTENT_MODE_CONSTANT, MY.MODE_PLAY);
mIntentLevel = mIntent.getIntExtra(MY.INTENT_LEVEL_CONSTANT, 1);
mScore = mIntent.getLongExtra(MY.INTENT_SCORE_CONSTANT, 0);
mHealth = mIntent.getIntExtra(MY.INTENT_HEALTH_CONSTANT, MYDirector.FULL_HEALTH_CONST);
mPlayButtonPressedCount = mIntent.getIntExtra(MY.INTENT_PLAY_PRESSED_CONSTANT, 0);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
startSurfaceView();
if (mMode == MY.MODE_DUEL) goToFrag(); // <--here is problem!!
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//....
}
public void startSurfaceView() {
if (true ) {
Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
Point size = new Point();
display.getSize(size);
mButtons = new MYButtonManager(this.getApplicationContext(), size.x ,size.y );
MYSound mSounds = new MYSound(this);
LayoutInflater mInflater = (LayoutInflater)getApplicationContext().getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
View mTitleAndScore = mInflater.inflate(R.layout.overlay_title_score, null);
myMYView = new MYGLSurfaceView(/*some stuff here*/);
RelativeLayout mRelative = new RelativeLayout(this);
mRelative.addView(myMYView);
mRelative.addView(mTitleAndScore);
mRelative.addView(mButtons);
setContentView(mRelative);
this.setupTitleAndScore();
}
}
}
this is the final piece.
Related
I am showing one dialog fragment (showing progress ) in my activity . Calling rest api methods are in my activity . Based on rest api results , I need to some progress in the dialog fragment . So I need to call a method of dialog fragment from activity . I tried with event bus , (Firing from Activity caught on Dialog Fragment ) - But events are not caught in dialog fragment . Is there any other solution ?
Fragment Code:
public class SyncProgressFragment extends BaseDialogFragment {
#BindView(R.id.layout_cancel)
LinearLayout layoutCancel;
#BindView(R.id.sync_with_master_breadcrumbs)
BreadcrumbsView syncWithMasterBreadCrumbs;
#BindView(R.id.master_breadcrumbs)
BreadcrumbsView masterBreadCrumbs;
#BindView(R.id.tvStep)
AppCompatTextView tvStep;
#BindView(R.id.tv_create_defect_title)
AppCompatTextView tvTitle;
private ThreadBus bus;
private FragmentManager manager;
private GoogleApiHelper googleApiHelper;
private Handler handler;
private Runnable runnable;
private boolean isOld;
private boolean isSync;
//private long requestId;
private BreadcrumbsView breadcrumbsView;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bus = AppController.getInstance().getBus();
bus.register(this);
googleApiHelper = AppController.getInstance().getGoogleApiHelper();
googleApiHelper.reconnect();
if (getArguments() != null) {
Bundle bundle = getArguments();
isOld = bundle.getBoolean(AppConstants.IS_OLD,false);
isSync = bundle.getBoolean(AppConstants.IS_OLD,false);
}
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initUI();
}
private void initUI() {
if (isOld && isSync)
tvTitle.setText(getString(R.string.syncing_old_data_with_bo));
else if(!isOld && isSync)
tvTitle.setText(getString(R.string.syncing_data_with_bo));
else {
tvTitle.setText(getString(R.string.downloading_master_data));
}
if(isSync) {
breadcrumbsView = syncWithMasterBreadCrumbs;
syncWithMasterBreadCrumbs.setVisibility(View.VISIBLE);
masterBreadCrumbs.setVisibility(View.GONE);
tvStep.setText(getString(R.string.sending_data));
}
else{
breadcrumbsView = masterBreadCrumbs;
masterBreadCrumbs.setVisibility(View.VISIBLE);
syncWithMasterBreadCrumbs.setVisibility(View.GONE);
tvStep.setText(getString(R.string.getting_master_data));
}
}
private void initValues() {
handler = new Handler();
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = super.onCreateDialog(savedInstanceState);
// request a window without the title
dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
dialog.setCanceledOnTouchOutside(false);
dialog.setCancelable(false);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
return dialog;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_sync_progress, container, false);
ButterKnife.bind(this, view);
initValues();
return view;
}
#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 onDestroy() {
super.onDestroy();
if (bus != null) {
bus.unregister(this);
}
try {
handler.removeCallbacks(runnable);
} catch (Exception e) {
}
}
#Override
public void onDestroyView() {
super.onDestroyView();
}
#Override
public void setCancelable(boolean cancelable) {
super.setCancelable(cancelable);
}
#Override
public void onCancel(DialogInterface dialog) {
super.onCancel(dialog);
}
#Override
public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
try {
handler.removeCallbacks(runnable);
} catch (Exception e) {
}
}
#OnClick({R.id.img_close, R.id.layout_cancel})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.layout_cancel:
case R.id.img_close:
dismissAllowingStateLoss();
break;
}
}
#Subscribe
public void onSyncGotResponse(SyncGotResponse syncGotResponse) {
Utilities.log(SyncProgressFragment.class,"onSyncGotResponse",""+syncGotResponse.isSuccess());
if(syncGotResponse.isSuccess()) {
breadcrumbsView.nextStep();
tvStep.setText(getString(R.string.synced_data_with_bo));
}
else
dismissAllowingStateLoss();
}
#Subscribe
public void onMasterGotResponse(MasterGotResponse masterGotResponse) {
Utilities.log(SyncProgressFragment.class,"onMasterGotResponse",""+masterGotResponse.isSuccess());
if(masterGotResponse.isSuccess()) {
tvStep.setText(getString(R.string.downloaded_data_from_bo));
breadcrumbsView.nextStep();
}
else
dismissAllowingStateLoss();
}
}
Activity Code:
#Override
public void dataSyncSuccess(DataSyncResponse dataSyncResponse) {
bus.post(new SyncGotResponse(true));
}
#Override
public void dataSyncFailure(String msg) {
UiUtils.showToast(getContext(), msg);
bus.post(new SyncGotResponse(false));
}
//Calling Rest Api method
if (CheckInternetConnection(getContext())) {
try {
presenter.data_sync();
Bundle bundle = new Bundle();
bundle.putBoolean(AppConstants.IS_OLD,false);
bundle.putBoolean(AppConstants.IS_SYNC,true);
syncProgressFragment.setArguments(bundle);
syncProgressFragment.setCancelable(false);
syncProgressFragment.show(getSupportFragmentManager(), syncProgressFragment.getTag());
} catch (JSONException e) {
e.printStackTrace();
}
} else {
ShowSanckBarShow();
}
my problem is same as link given below
I have a ViewPager by same fragments RecyclerView just load items in one fragment of ViewPager
but at this post no one solve issue...
I have a recycler view items...I want when I click on recycler view item it takes me to viewpager fragment and shows that data of clicked item dynamically and on swiping viewpager it should move previous and next fragment accordingly...under fragment I want to show data of recyclerrview item using single fragment...
I have done this by using multiple fragment and using multiple instances by different name and different layout name and different id for its recyclerView and it works but i have a large number of fragments and it is not the solution for me ):
here is my viewpager code
public class AndroidViewPagerExample extends FragmentActivity {
ViewPager pager;
int positionring;
String rgtv;
#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.mainuuuu);
Intent it = getIntent();
positionring = it.getIntExtra("POS", 0);
final int position = it.getIntExtra("POS", 0);
rgtv= it.getStringExtra("name");
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
pager.setPageTransformer(true, new RotateUpTransformer());
pager.setCurrentItem(position);
pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
Boolean first = true;
Boolean userScrollChange=false;
public void onPageScrollStateChanged(int state) {
System.out.println("onPageScrollStateChanged");
System.out.println("Current position=="+position);
int curreentpos=position;
int newpos=curreentpos+1;
int previousState=curreentpos-1;
if (previousState == pager.SCROLL_STATE_DRAGGING
&& state == pager.SCROLL_STATE_SETTLING)
userScrollChange = true;
else if (previousState == pager.SCROLL_STATE_SETTLING
&& state == pager.SCROLL_STATE_IDLE)
userScrollChange = false;
previousState = state;
}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
System.out.println("onPageScrolled");
}
public void onPageSelected(int position) {
// Check if this is the page you want.
System.out.println("onPageSelected");
Apples.newInstance(rgtv);
}
});
}
private class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
return Apples.newInstance(rgtv);
}
#Override
public int getCount() {
return ringtonelist.size();
}
}
#Override
public void onBackPressed() {
// if (pager.getCurrentItem() != 36) {
// pager.setCurrentItem(36);
// } else {
Vp_Ringtoneplaybtn.Playstop();
super.onBackPressed();
// }
}
}
code given below is adapter code
public class RingToneAdapter extends RecyclerView.Adapter<RingToneAdapter.RingToneViewHolder> {
public int mSelectedItem = -1;
static MediaPlayer mp;
View view;
static Context rcntx;
int oldpossssssss;
List<RingTone_Items> ringtonelist;
private TextView hello, close;
ImageView prev, next;
private ImageView iconplay;
private InterstitialAd mInterstitialAd;
Dialog MyDialog;
static final int[] resID = {R.raw.a48, R.raw.funny_hen, R.raw.funny_roster_1, R.raw.funny_roster_2, R.raw.rooster_1, R.raw.rooster_2,R.raw.rooster_3,R.raw.funny_cock,R.raw.a12,R.raw.a45,R.raw.a44,R.raw.a43,R.raw.a31, R.raw.a10,R.raw.chicken_1,R.raw.chick_2,R.raw.chick_3,R.raw.chick_4,R.raw.chick_5,R.raw.chick_6};
public RingToneAdapter(Context rcntx, List<RingTone_Items> ringtonelist) {
this.rcntx = rcntx;
this.ringtonelist = ringtonelist;
}
#NonNull
#Override
public RingToneViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
view = LayoutInflater.from(rcntx).inflate(R.layout.ringtone_values, viewGroup, false);
RingToneViewHolder ringToneViewHolder = new RingToneViewHolder(view);
return ringToneViewHolder;
}
#Override
public void onBindViewHolder(#NonNull final RingToneViewHolder ringToneViewHolder, final int i) {
final RingTone_Items ringTone_items = ringtonelist.get(i);
ringToneViewHolder.rtv.setText(ringTone_items.getRintonetv());
if (mSelectedItem == i) { // mSelectedItem = -1 and at 1st time
// there is no position selected...so the condition goes false...go
// to else condtion
ringToneViewHolder.iconplay.setImageResource(R.drawable.ic_pause_black_24dp);
} else {
ringToneViewHolder.iconplay.setImageResource(R.drawable.ic_play_arrow_black_24dp); // all icons will show play icon
}
ringToneViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// MyCustomAlertDialog(i);
if (mp != null && mp.isPlaying()) {
mp.stop();
mp.reset();
mp = null;
ringToneViewHolder.iconplay.setImageResource(R.drawable.ic_play_arrow_black_24dp);
}
//Intent it = new Intent(rcntx, ViewPager_Data.class);
Intent it = new Intent(rcntx, AndroidViewPagerExample.class);
it.putExtra("POS",i);
it.putExtra("name",ringTone_items.getRintonetv());
// mInterstitialAd = new InterstitialAd(rcntx);
// mInterstitialAd.setAdUnitId(rcntx.getResources().getString(R.string.ad_interstitial));
// AdRequest adRequest = new AdRequest.Builder().build();
// mInterstitialAd.loadAd(adRequest);
// mInterstitialAd.setAdListener(new AdListener() {
// public void onAdLoaded() {
// if (mInterstitialAd.isLoaded()) {
// mInterstitialAd.show();
// }
// }
// });
rcntx.startActivity(it);
}
});
ringToneViewHolder.iconplay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mSelectedItem == i) {
mSelectedItem = -1;
oldpossssssss = i;
} else {
mSelectedItem = i;
}
notifyDataSetChanged(); //update the position of row...notifyDataSetChanged is bindview method
if (mp != null && mp.isPlaying()) {
mp.stop();
//mp.deselectTrack(resID[i]);
mp.reset();
mp.release();
mp = null;
if (oldpossssssss == i) {
} else {
mp = new MediaPlayer();
mp = MediaPlayer.create(rcntx, resID[i]);
mp.start();
}
} else {
// MyCustomAlertDialog(i);
mp = new MediaPlayer();
mp = MediaPlayer.create(rcntx, resID[i]);
mp.start();
}
}
});
}
#Override
public int getItemCount() {
return ringtonelist.size();
}
class RingToneViewHolder extends RecyclerView.ViewHolder {
private TextView rtv, hello, close;
private ImageView iconplay;
public RingToneViewHolder(#NonNull View itemView) {
super(itemView);
rtv = itemView.findViewById(R.id.ringtitle);
iconplay = itemView.findViewById(R.id.playicon);
}
}
public void InterstitialAdmob() {
mInterstitialAd = new InterstitialAd(rcntx);
mInterstitialAd.setAdUnitId(rcntx.getResources().getString(R.string.ad_interstitial));
mInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
requestNewInterstitial();
}
});
requestNewInterstitial();
}
protected void requestNewInterstitial() {
AdRequest adRequest = new AdRequest.Builder().build();
mInterstitialAd.loadAd(adRequest);
}
}
here is main activity code
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
RingToneAdapter adapter;
public static ArrayList<RingTone_Items> ringtonelist;
//final int[] resID = {R.raw.alert};
public static int posss;
private String[] fruitlist = new String[]{"Funny hen 1", "Funny hen 2", "Funny roaster 1", "Funny roaster 2","Funny roaster 3", "Funny roaster 4", "funny roaster 5","Funny cock", "Funny hen alarm","Abstracts", "Wake up", "Funny tone","Get up","Alarm","Hen sound 1","Hen sound 2","Hen sound 3","Hen sound 4","Hen sound 5","Hen sound 6"};
private boolean isFABOpen;
FloatingActionButton fab,fab1, fab3;
FrameLayout fab2;
AdView mAdView;
RelativeLayout layout_no, layoutrateus, layout_yes, adlayout, adlayout1;
private static final int PERMISSION_REQUEST_CODE = 1;
private String fNmae = String.valueOf(R.raw.alarm);
private String fPAth = "android.resource://packagename/raw/alarm";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler);
// Here, thisActivity is the current activity
if (Build.VERSION.SDK_INT >= 23) {
if (checkPermission()) {
if (Settings.System.canWrite(MainActivity.this)) {
//setRingtone();
} else {
Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_WRITE_SETTINGS)
.setData(Uri.parse("package:" + getPackageName()))
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
Log.e("value", "Permission already Granted, Now you can save image.");
} else {
requestPermission();
}
} else {
// setRingtone();
Log.e("value", "Not required for requesting runtime permission");
}
mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
//recyclerView.setBackgroundColor(getResources().getColor(R.color.colorAccent));
recyclerView.setBackground(getResources().getDrawable(R.drawable.bg));
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
// RecyclerView.LayoutManager mLayoutManager =
// new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.HORIZONTAL, false);
ringtonelist = getRingTone_Items();
adapter = new RingToneAdapter(this, ringtonelist);
recyclerView.setAdapter(adapter);
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView, new RecyclerTouchListener.ClickListener() {
#Override
public void onClick(View view, int position) {
RingTone_Items itemrg = ringtonelist.get(position);
posss=position;
}
#Override
public void onLongClick(View view, int position) {
}
}));
}
protected boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
protected void requestPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Toast.makeText(MainActivity.this, "Write External Storage permission allows us to do store images. Please allow this permission in App Settings.", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.e("value", "Permission Granted, Now you can save image .");
if (Build.VERSION.SDK_INT >= 23) {
if (Settings.System.canWrite(MainActivity.this)) {
// setRingtone();
} else {
Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_WRITE_SETTINGS)
.setData(Uri.parse("package:" + getPackageName()))
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
} else {
Log.e("value", "Permission Denied, You cannot save image.");
}
break;
}
}
private ArrayList<RingTone_Items> getRingTone_Items(){
ArrayList<RingTone_Items> list = new ArrayList<>();
for(int i = 0; i < 20; i++){
RingTone_Items model = new RingTone_Items();
model.setRintonetv(fruitlist[i]);
list.add(model);
}
return list;
}
public void onBackPressed(){
if (mp != null && mp.isPlaying()) {
mp.pause();
mp.stop();
mp.release();
mp = null;
}
onexit();
}
public void onexit() {
android.view.LayoutInflater layout1 = android.view.LayoutInflater.from(this);
View view1 = layout1.inflate(R.layout.backpress, null);
final RelativeLayout relativeLayout=(RelativeLayout) view1.findViewById(R.id.layout_top);
final AlertDialog.Builder gotoBuilder1 = new AlertDialog.Builder(this);
gotoBuilder1.setView(view1);
final AlertDialog gotoDialog1 = gotoBuilder1.create();
layout_no = view1.findViewById(R.id.layoutno);
layoutrateus = view1.findViewById(R.id.layoutrateus);
layout_yes = view1.findViewById(R.id.layout_yes);
layout_no.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
gotoDialog1.dismiss();
}
});
layoutrateus.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
Intent mintent = new Intent(Intent.ACTION_VIEW);
mintent.setData(android.net.Uri.parse("market://details?id="
+ getPackageName()));
startActivity(mintent);
} catch (Exception e1) {
try {
android.net.Uri uriUrl = android.net.Uri
.parse("https://market.android.com/details?id="
+ getPackageName());
Intent launchBrowser = new Intent(Intent.ACTION_VIEW,
uriUrl);
startActivity(launchBrowser);
} catch (Exception e2) {
android.widget.Toast.makeText(getApplicationContext(),
"No Application Found to open link",
android.widget.Toast.LENGTH_SHORT).show();
}
}
gotoDialog1.dismiss();
}
});
layout_yes.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
} catch (Exception e) {
}
gotoDialog1.dismiss();
finish();
}
});
gotoDialog1.getWindow().setLayout(android.view.ViewGroup.LayoutParams.MATCH_PARENT,
android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
gotoDialog1.show();
}
public void onDestroy() {
super.onDestroy();
}
}
this is my fragment
public class Apples extends BaseFragment{
ImageView vpbtn;
MediaPlayer mp;
ImageView tvshare;
static String s;
static TextView rgtname;
int position = 0;
private ShareActionProvider mShareActionProvider;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.apple, container, false);
vpbtn = (ImageView) v.findViewById(R.id.iconplaypause);
mAdView = (AdView) v.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
rgtname=v.findViewById(R.id.rgtname);
rgtname.setText(s);
tvshare=v.findViewById(R.id.tvshare);
fab = v.findViewById(R.id.fab);
fab1 = v.findViewById(R.id.frm1);
fab2 = v.findViewById(R.id.frm2);
fab3 = v.findViewById(R.id.frm3);
// Vp_Ringtoneplaybtn.Setrintones(fab,fab1,fab2,fab3);
// tvshare.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// Vp_Ringtoneplaybtn.shareapp();
// }
// });
Vp_Ringtoneplaybtn.shareapp(tvshare);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(!isFABOpen){
showFABMenu();
}else{
closeFABMenu();
}
}
});
Vp_Ringtoneplaybtn.Setrintones(fab1,fab2,fab3,position);
vpbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Vp_Ringtoneplaybtn.PlaySound( vpbtn, position);
}
});
return v;
}
public static Apples newInstance(String rgtvv) {
s=rgtvv;
Apples f16 = new Apples();
return f16;
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (this.isVisible()) {
// If we are becoming invisible, then...
if (!isVisibleToUser) {
Vp_Ringtoneplaybtn.Playstop();
vpbtn.setImageResource(R.drawable.ic_play_arrow_black_24dp);
} else {
// do what you like
}
}
}
#Override
public void onPause() {
super.onPause();
}
}
In my form fragment Hardware "back" button work not correctly. For example when I opened fragment and when I didn't start typing, and I pressed Hardware "back" button it's work excellent. But when I started typing and after typing press to Hardware "back" button app crashed without any error logs.
my form fragment
public class D_Category_Login extends Fragment implements View.OnClickListener{
public static FragmentListItemClick fragmentListItemClick;
EditText edt_name,edt_lastname,edt_phone,edt_pass1,edt_pass2;
String name="";
DBHelper dbHelper;
public static final String REGISTER_URL = "http://admin.unimax.kz/api/Klientapi/AddClient?";
public static final String KEY_USERNAME = "first_name";
public static final String KEY_LASTNAME = "last_name";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.form_login, null);
((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("Регистрация");
edt_name = (EditText) view.findViewById(R.id.edt_firstname);
edt_lastname = (EditText) view.findViewById(R.id.lastname);
edt_phone = (EditText) view.findViewById(R.id.login);
edt_pass1 = (EditText) view.findViewById(R.id.pass);
edt_pass2 = (EditText) view.findViewById(R.id.pass_repeet);
Button btn_submit = (Button) view.findViewById(R.id.btn_submit);
TextView tv_number = (TextView) view.findViewById(R.id.tv_number);
btn_submit.setOnClickListener(this);
tv_number.setOnClickListener(this);
edt_phone.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
if(!s.toString().contains("+7 ")){
edt_phone.setText("+7 ");
Selection.setSelection(edt_phone.getText(), edt_phone.getText().length());
}
}
});
return view;
}
void setfragmentclick(FragmentListItemClick fr){
fragmentListItemClick = fr;
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_submit:{
if (edt_name.getText().toString().trim().isEmpty() || edt_lastname.getText().toString().trim().isEmpty()){
if (edt_name.getText().toString().trim().isEmpty()) {
edt_name.setError("Заполните это поле");
requestFocus(edt_name);
}
if (edt_lastname.getText().toString().trim().isEmpty()) {
edt_lastname.setError("Заполните это поле");
requestFocus(edt_lastname);
}
}
else {
CheckInternet();
}
}
break;
case R.id.tv_number:{
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + "+77079300066"));
startActivity(intent);
}
break;
}
}
void CheckInternet(){
if (isOnline()){
registerUser();
}
else {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getContext());
alertDialogBuilder.setMessage("Проверьте подключение к Интернету");
alertDialogBuilder.setPositiveButton("Закрыть", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
void registerUser(){
final String first_name = edt_name.getText().toString().trim();
final String last_name = edt_lastname.getText().toString().trim();
String fill_url = REGISTER_URL+"familia="+Uri.encode(last_name)+"&name="+Uri.encode(first_name);
StringRequest stringRequest = new StringRequest(Request.Method.POST, fill_url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
dbHelper = new DBHelper(getContext());
final ContentValues cv = new ContentValues();
final SQLiteDatabase db = dbHelper.getWritableDatabase();
name+= String.valueOf(edt_name.getText()+" "+String.valueOf(edt_lastname.getText()));
cv.put("id_user", Integer.valueOf(response));
cv.put("name", name);
db.execSQL("delete from form_login");
db.insert("form_login",null, cv);
db.close();
dbHelper.close();
getFragmentManager().popBackStack();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(),"Ошибка сервера"+error.toString(),Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
requestQueue.add(stringRequest);
}
private void requestFocus(View view) {
if (view.requestFocus()) {
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
}
My form fragment is child fragment. And this parent fragment where I implement backaction.
#Override
public void onResume() {
super.onResume();
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
backAction();
return true;
}
return false;
}
});
}
public void backAction() {
if (getChildFragmentManager().getBackStackEntryCount() > 0) {
getChildFragmentManager().popBackStack();
}
else {
((MainActivity) getActivity()).setCurrentItem(0, true);
}
}
Create TextWatcher like
TextWatcher textWatcher=new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
if(!s.toString().contains("+7 ")){
edt_phone.setText("+7 ");
Selection.setSelection(edt_phone.getText(), edt_phone.getText().length());
}
};
Add it to edt_phone like
edt_phone.addTextChangedListener(textWatcher);
Then in the back press event remove the listener,
getView().setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
edt_phone.removeTextChangedListener(textWatcher);
return true;
}
}
return false;
}
});
In your foam fragment(child fragment)
Communicator communicator;
#Override
public void onBackPressed() {
super.onBackPressed();
communicator.exitFragment();
}
public void setCommunicator(Communicator communicator)
{
this.communicator = communicator;
}
public interface Communicator
{
void exitFragment();
}
in your parent fragment do this
public parentFragment extends Fragment implements childFragment.Communicator
{
#override
public void onCreatView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
childFragment.setCommunicator(this);
}
public void exitFragment()
{
getActivity().finish();
}
}
Fragments are managed by the Fragment Managers which are called by the Activity; so, to control what you want to do when the back button is clicked, you must do that in the activity;
Now, if you have more than one fragment set, you should use tags to find them, check to see if they are visible and if so, do what you mentioned above.
When setting your fragments, you should give them a tag and then use this tag later to findFragmentByTagName() and do an if check to see which fragment is set at the moment;
Let me know if you need any clarification on the same.
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
i want to integrate flurry in my app. in the following code i am integrate flurry but that was not working properly in android. flurry listener call its method two times. how it working please help me.
LoginActivity.java
public class LoginActivity extends Activity implements OnClickListener,
AsyncTaskCompleteListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
instance = this;
setContentView(R.layout.login_activity);
Map<String, String> map = new HashMap<String, String>();
map.put("url", NFLConstanants.LOGIN_URL);
map.put("username", strUser);
map.put("passwd", strPassword);
new ParseController(LoginActivity.this, map,
NFLConstanants.SERVICE_CODE0, 1);
}
#Override
protected void onStart() {
super.onStart();
System.out.println("call on start method");
FlurryAgent.onStartSession(this, MACUtils.APIKEY_FLURRY);
FlurryAgent.enableTestAds(true);
FlurryAgent.initializeAds(this);
FlurryAgent.setLogEnabled(true);
}
#Override
protected void onStop() {
super.onStop();
System.out.println("call on stop method");
FlurryAgent.onEndSession(this);
}
#Override
public void onTaskCompleted(String responce, int sc) {
if (FlurryAgent.isAdAvailable(LoginActivity.this,
MACUtils.myAdSpaceName,
FlurryAdSize.FULLSCREEN, MACUtils.timeout)) {
final String msgv = "To help keep this app free please watch this short video. Thanks";
AlertDialog.Builder dlg = new AlertDialog.Builder(
LoginActivity.this);
dlg.setCancelable(false);
dlg.setTitle("Message");
dlg.setMessage(msgv);
dlg.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface dialog,
int which) {
try {
MyAdListener myAdListener = new MyAdListener(
LoginActivity.this,
LoginActivity.this, "3");
FlurryAgent
.setAdListener(myAdListener);
FrameLayout container = new FrameLayout(
LoginActivity.this);
FlurryAgent
.getAd(LoginActivity.this,
MACUtils.myAdSpaceName,
container,
FlurryAdSize.FULLSCREEN,
MACUtils.timeout);
} catch (Exception e) {
e.printStackTrace();
}
}
});
AlertDialog alert = dlg.create();
alert.show();
}
}
}
MyAdListener.java
public class MyAdListener implements FlurryAdListener {
public Activity activity;
public Context ctx;
String pagePosition;
boolean isDialogLaunch = false;
public MyAdListener(Activity act, Context ctx, String page) {
this.activity = act;
this.pagePosition = page;
this.ctx = ctx;
this.isDialogLaunch = false;
}
#Override
public boolean shouldDisplayAd(String myAdSpaceName, FlurryAdType type) {
System.out.println("shouldDisplayAd:: " + type);
return true;
}
#Override
public void onAdClosed(String myAdSpaceName) {
System.out.println("onAdClosed::: " + myAdSpaceName);
if (pagePosition.equals("1") || pagePosition.equals("2")) {
actionOnFlurryVideo();
} else {
if (!FlurryAgent.isAdAvailable(activity, MACUtils.myAdSpaceName,
FlurryAdSize.FULLSCREEN, MACUtils.timeout)) {
Intent macIntent = new Intent(activity, MACCustomTab.class);
macIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
activity.startActivity(macIntent);
activity.finish();
}
}
}
#Override
public void onApplicationExit(String myAdSpaceName) {
System.out.println("onApplicationExit:: " + myAdSpaceName);
actionOnFlurryVideo();
}
#Override
public void onRenderFailed(String adSpace) {
System.out.println("onRenderFailed:: " + adSpace);
actionOnFlurryVideo();
}
#Override
public void spaceDidReceiveAd(String adSpace) {
System.out.println("spaceDidReceiveAd:: " + adSpace);
}
#Override
public void spaceDidFailToReceiveAd(String adSpace) {
System.out.println("spaceDidFailToReceiveAd:: " + adSpace);
}
#Override
public void onAdClicked(String id) {
System.out.println("onAdClicked:: " + id);
}
#Override
public void onAdOpened(String id) {
System.out.println("onAdOpened::: " + id);
}
public void actionOnFlurryVideo() {
System.out.println("call actionOnflurryvideo");
if (pagePosition.equals("1") || pagePosition.equals("2")) {
if (!isDialogLaunch) {
isDialogLaunch = true;
final String msg = "Thanks for supporting our free website. Your bet has now been confirmed.";
AlertDialog.Builder dlg = new AlertDialog.Builder(ctx);
dlg.setCancelable(false);
dlg.setTitle("Message");
dlg.setMessage(msg);
dlg.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
NavigationGroupActivity parent = ((NavigationGroupActivity) activity
.getParent());
parent.backToFirst();
}
});
AlertDialog alert = dlg.create();
alert.show();
}
} else {
Intent macIntent = new Intent(activity, MACCustomTab.class);
macIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
activity.startActivity(macIntent);
activity.finish();
}
}
}
This issue will be fixed in our next release which is expected to come out very soon.
(Full disclosure: I work in the Support team at Flurry)