Show custom interstitial ad like as admob interstitial ad - android

We are currently using admob's interstitial ad in our app. What we have in our first splash screen is:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
getWindow().setNavigationBarColor(getResources().getColor(R.color.colorPrimary));
}
setContentView(R.layout.activity_splash);
mContext = this;
requestNewInterstitialList();
}
private void requestNewInterstitialList() {
InterstitialAd mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId(getString(R.string.gl_start_app_inter));
mInterstitialAd.loadAd(new AdRequest.Builder().build());
mInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdOpened() {
super.onAdOpened();
mContext.finish();
}
#Override
public void onAdLoaded() {
super.onAdLoaded();
if (mInterstitialAd != null && mInterstitialAd.isLoaded()) {
Intent intent = new Intent(SplashActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
mInterstitialAd.show();
}
}
});
}
I requested interstitial from onCreate() in our splash screen. Notice that in interstitial ad in onAdLoaded() I started MainActivity.class via intent and this will definitely start that screen without closing interstitial ad! So, it will just start new screen in background and show interstitial ad at a time! After that in onAdOpened() of ad I just finished my current activity(Splash screen) and that also that not affect the interstitial ad and in mean while when user close the ad in the behind main screen is loaded!
Now situation is that we have some sponsors and they want show custom built interstitial ad in our App! So, I made that in DialogFragment:
public class DF_Interstitial_Ad extends DialogFragment {
private LayoutInterstitialAdBinding mBinding;
private Context mContext;
private String adUrl;
private SimpleExoPlayer player;
private PlayerView exoPlayerView;
private long playBackPosition = 0;
private boolean isPlayerReady = false;
private boolean isOnPause = false;
private InterAdListener mAdListener = null;
public DF_Interstitial_Ad(#NonNull Context mContext, #NonNull String adUrl) {
this.mContext = mContext;
this.adUrl = adUrl;
mBinding = DataBindingUtil.inflate(LayoutInflater.from(mContext), R.layout.layout_interstitial_ad, null,
false);
dataSourceFactory = buildDataSourceFactory();
exoPlayerView = mBinding.playerAd;
initializePlayer();
}
private class ModelInterStitialAd {
private String title;
private String description;
private String appIconUrl;
private String videoUrl;
private String installUrl;
private float rattings;
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public String getAppIconUrl() {
return appIconUrl;
}
public String getVideoUrl() {
return videoUrl;
}
public String getInstallUrl() {
return installUrl;
}
public float getRattings() {
return rattings;
}
}
//region Data source...
private DataSource.Factory dataSourceFactory;
private MediaSource mediaSource;
private AdsLoader adsLoader;
private void releaseAdsLoader() {
if (adsLoader != null) {
adsLoader.release();
adsLoader = null;
Objects.requireNonNull(exoPlayerView.getOverlayFrameLayout()).removeAllViews();
}
}
private void releasePlayer() {
if (player != null) {
playBackPosition = player.getCurrentPosition();
player.release();
player = null;
mediaSource = null;
Log.i("Player>>>", "Player released");
}
if (adsLoader != null) {
releaseAdsLoader();
}
}
private DataSource.Factory buildDataSourceFactory() {
return MyApplication.getInstance().buildDataSourceFactory(null);
}
//endregion
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(STYLE_NORMAL, R.style.FullScreenDialog);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Objects.requireNonNull(Objects.requireNonNull(getDialog()).getWindow()).addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
if (mAdListener != null) {
mAdListener.onShow();
}
playPausePlayer(true);
return mBinding.getRoot();
}
#Override
public void onResume() {
super.onResume();
isOnPause = false;
playPausePlayer(true);
}
#Override
public void onPause() {
super.onPause();
isOnPause = true;
playPausePlayer(true);
}
#Override
public void onDestroy() {
super.onDestroy();
if (mAdListener != null) {
mAdListener.onClose();
}
releasePlayer();
}
//region Player zone...
private void initializePlayer() {
player = new SimpleExoPlayer.Builder(mContext).build();
player.setPlayWhenReady(false);
exoPlayerView.setPlayer(player);
exoPlayerView.setBackgroundColor(Color.BLACK);
exoPlayerView.setUseController(false);
mBinding.viewMain.setOnClickListener(v -> {
if (isPlayerReady)
if (player != null) {
if (player.getPlaybackState() == Player.STATE_ENDED) {
mBinding.ivPlayVideo.setVisibility(View.VISIBLE);
playBackPosition = 0;
playPausePlayer(true);
} else {
if (player.getPlayWhenReady()) {
playPausePlayer(false);
mBinding.ivPlayVideo.setVisibility(View.VISIBLE);
} else {
playPausePlayer(true);
mBinding.ivPlayVideo.setVisibility(View.GONE);
}
}
}
});
player.addListener(new Player.EventListener() {
#Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
if (playbackState == Player.STATE_ENDED) {
mBinding.ivPlayVideo.setVisibility(View.VISIBLE);
} else if (playbackState == Player.STATE_READY) {
if (!isPlayerReady) {
isPlayerReady = true;
if (mAdListener != null) {
mAdListener.onLoaded();
}
}
if (isOnPause)
playPausePlayer(false);
}
}
});
prepareExoPlayer();
}
private void prepareExoPlayer() {
mediaSource = buildMediaSource(Uri.parse(adUrl));
player.prepare(mediaSource, true, false);
}
private MediaSource buildMediaSource(Uri uri) {
CacheDataSourceFactory cacheDataSourceFactory = new CacheDataSourceFactory(VideoCache.getInstance(mContext),
dataSourceFactory);
#C.ContentType int type = Util.inferContentType(uri, null);
switch (type) {
case C.TYPE_HLS:
return new HlsMediaSource.Factory(cacheDataSourceFactory).setAllowChunklessPreparation(true).createMediaSource(uri);
case C.TYPE_OTHER:
return new ProgressiveMediaSource.Factory(cacheDataSourceFactory).createMediaSource(uri);
case C.TYPE_DASH:
case C.TYPE_SS:
default:
throw new IllegalStateException("Unsupported type: " + type);
}
}
private void playPausePlayer(boolean play) {
if (player != null) {
if (play) {
player.seekTo(playBackPosition);
player.setPlayWhenReady(true);
player.getPlaybackState();
mBinding.ivPlayVideo.setVisibility(View.GONE);
} else {
playBackPosition = player.getCurrentPosition();
player.setPlayWhenReady(false);
player.getPlaybackState();
mBinding.ivPlayVideo.setVisibility(View.VISIBLE);
}
}
}
//endregion
public void setmAdListener(InterAdListener mAdListener) {
this.mAdListener = mAdListener;
}
public boolean isLoaded() {
return isPlayerReady;
}
}
This is my DialogFragment in which I implemented my own custom interstitial ad. So, after that I just request it regularly same as admob's interstitial ad from splash screen like:
private void requestMyInterstitialAd() {
DF_Interstitial_Ad dfInterstitialAd = new DF_Interstitial_Ad(mContext, "https://booads.s3.ap-south-1.amazonaws.com/output.mp4");
dfInterstitialAd.setmAdListener(new InterAdListener() {
#Override
public void onLoaded() {
super.onLoaded();
if (dfInterstitialAd != null && dfInterstitialAd.isLoaded()) {
Intent intent = new Intent(SplashActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
dfInterstitialAd.show(getSupportFragmentManager(), "SplashScreen");
}
}
#Override
public void onShow() {
super.onShow();
}
#Override
public void onClose() {
super.onClose();
}
});
}
It is show next screen(MainActivity) in front of screen rather than DialogFragment of ad! So, what to do? for showing ad in front of user and in mean while open next activity behind the ad! I already tried showing ad in activity rather than DialogFragment but its also not working for me!

Related

After updating Google Ads SDK to 21.5.0 is deprecated, How to resolve?

After updating Google Ads SDK to 21.5.0 gives a deprecated warning message for InterstitialAd, while I searched this link for resolving the issue but not succeed. how can I resolve it?
`public class Ads {
public static int statusclick = 3;
public static int statusclickcount = 0;
public static String privecy = "http://google.com/";
private com.google.android.gms.ads.InterstitialAd interstitialAds;
public void interstitialload(Context context) {
MobileAds.initialize(context, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
//add
}
});
interstitialAds = new com.google.android.gms.ads.InterstitialAd(context);
interstitialAds.setAdUnitId(context.getString(R.string.interstitial_full_screen));
interstitialAds.loadAd(
new AdRequest.Builder()
.build()
);
}
public void showInd(final Adclick adclick) {
if ((interstitialAds == null) || (!interstitialAds.isLoaded())) {
adclick.onclicl();
return;
}
interstitialAds.setAdListener(new com.google.android.gms.ads.AdListener() {
#Override
public void onAdClosed() {
adclick.onclicl();
interstitialAds.loadAd(
new AdRequest.Builder()
.build()
);
}
#Override
public void onAdLoaded() {
//add
}
#Override
public void onAdOpened() {
//add
}
});
interstitialAds.show();
}
public Ads() {
//add
}
`
I tried a lot but it still gives me an error
`public class Ads {
public static int statusclick = 3;
public static int statusclickcount = 0;
public static String privecy = "http://google.com/";
private InterstitialAd mInterstitialAd;
// private InterstitialAd mInterstitialAd;
public void interstitialload(Context context) {
MobileAds.initialize(context, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
//add
}
});
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(context,
"ca-app-pub-3940256099942544/1033173712",
adRequest,
new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
// The mInterstitialAd reference will be null until
// an ad is loaded.
mInterstitialAd = interstitialAd;
Log.i(TAG, "onAdLoaded");
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
#Override
public void onAdShowedFullScreenContent() {
// Called when fullscreen content is shown.
// Make sure to set your reference to null so you don't
// show it a second time.
// mInterstitialAd = null;
Log.d("TAG", "The ad was shown.");
}
#Override
public void onAdClicked() {
// Called when a click is recorded for an ad.
Log.d(TAG, "Ad was clicked.");
}
#Override
public void onAdDismissedFullScreenContent() {
// Called when ad is dismissed.
// Set the ad reference to null so you don't show the ad a second time.
Log.d(TAG, "Ad dismissed fullscreen content.");
// goWatch();
mInterstitialAd = null;
}
#Override
public void onAdFailedToShowFullScreenContent(AdError adError) {
// Called when ad fails to show.
// goWatch();
Log.e(TAG, "Ad failed to show fullscreen content.");
mInterstitialAd = null;
}
#Override
public void onAdImpression() {
// Called when an impression is recorded for an ad.
// goWatch();
Log.d(TAG, "Ad recorded an impression.");
mInterstitialAd = null;
}
});
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
// Handle the error
Log.i(TAG, loadAdError.getMessage());
// goWatch();
mInterstitialAd = null;
}
});
//interstitialAds = new com.google.android.gms.ads.InterstitialAd(context);
// interstitialAds.setAdUnitId(context.getString(R.string.interstitial_full_screen));
// interstitialAds.loadAd(
// new AdRequest.Builder()
// .build()
// );
}
public void showInd(final Adclick adclick) {
// if ((mInterstitialAd == null) || (!mInterstitialAd.isLoaded())) {
if ((mInterstitialAd == null) || (mInterstitialAd != null)) {
adclick.onclicl();
return;
}
interstitialAds.setAdListener(new com.google.android.gms.ads.AdListener() {
#Override
public void onAdClosed() {
adclick.onclicl();
interstitialAds.loadAd(
new AdRequest.Builder()
.build()
);
}
#Override
public void onAdLoaded() {
//add
}
#Override
public void onAdOpened() {
//add
}
});
interstitialAds.show();
}`
I tried a lot but it still gives me an error
` public void showInd(final Adclick adclick) {
// if ((mInterstitialAd == null) || (!mInterstitialAd.isLoaded())) {
if ((mInterstitialAd == null) || (mInterstitialAd != null)) {
adclick.onclicl();
return;
}
interstitialAds.setAdListener(new com.google.android.gms.ads.AdListener() {
#Override
public void onAdClosed() {
adclick.onclicl();
interstitialAds.loadAd(
new AdRequest.Builder()
.build()
);
}
#Override
public void onAdLoaded() {
//add
}
#Override
public void onAdOpened() {
//add
}
});
interstitialAds.show();
}`

I have only one fragment and I want to change this fragment in viewpager dynamically according to recycler view item data

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();
}
}

Exoplayer Orientation problem when rotate to Landscape

When the video plays in Exoplayer its fine but when it rotates the video starts again.
I want to make sure that the when the video rotates the video resumes to same position
I have saved the playersCurrent position but still its not working.
Please help.....
public class RecipeStepDescriptionFragment extends Fragment {
#BindView(R.id.playerView)
PlayerView playerView;
#BindView(R.id.stepDescription)
TextView stepDescription;
#BindView(R.id.ingredientsCardSteps)
CardView ingredientsCardSteps;
#BindView(R.id.ingredientsListStepDescription)
TextView ingredientsListStepDescription;
#BindView(R.id.widgetButtonStepDescription)
FloatingActionButton widgetButton;
private SimpleExoPlayer player;
private static final String TAG = "StepDetail";
String videoUrl;
String longDescription;
boolean tablet;
String ingredients;
String name;
public RecipeStepDescriptionFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_recipe_step_description, container, false);
ButterKnife.bind(this, rootView);
if (getArguments() != null) {
videoUrl = getArguments().getString("videoURL");
longDescription = getArguments().getString("description");
tablet = getArguments().getBoolean("tablet");
ingredients = getArguments().getString("ingredients");
name = getArguments().getString("name");
//recipeList = (List<Steps>) getArguments().getSerializable("recipe_steps");*/
}
stepDescription.setText(longDescription);
if (!tablet) {
ingredientsCardSteps.setVisibility(View.GONE);
} else {
ingredientsListStepDescription.setText(ingredients);
}
if (videoUrl != null) {
playerView.setVisibility(View.VISIBLE);
if (videoUrl.equals("")) {
playerView.setVisibility(View.GONE);
} else {
player = ExoPlayerFactory.newSimpleInstance(getContext(), new DefaultTrackSelector());
playerView.setPlayer(player);
DefaultDataSourceFactory dataSourceFactory = new DefaultDataSourceFactory(getContext(), Util.getUserAgent(getContext(), "exo-demo"));
ExtractorMediaSource mediaSource = new ExtractorMediaSource.Factory(dataSourceFactory).createMediaSource(Uri.parse(videoUrl));
player.prepare(mediaSource);
player.setPlayWhenReady(true);
}
} else {
playerView.setVisibility(View.GONE);
}
if (savedInstanceState != null && player != null) {
player.seekTo(savedInstanceState.getLong("current_position"));
player.setPlayWhenReady(savedInstanceState.getBoolean("play_state"));
}
widgetButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor = getActivity().getSharedPreferences("INGREDIENTS", MODE_PRIVATE).edit();
editor.putString("ingredients", ingredients);
editor.putString("name", name);
editor.commit();
Toast.makeText(getContext(), "Widget Added to Home Screen", Toast.LENGTH_SHORT).show();
}
});
return rootView;
}
public void initializePlayer(){
player = ExoPlayerFactory.newSimpleInstance(getContext(), new DefaultTrackSelector());
playerView.setPlayer(player);
DefaultDataSourceFactory dataSourceFactory = new DefaultDataSourceFactory(getContext(), Util.getUserAgent(getContext(), "exo-demo"));
ExtractorMediaSource mediaSource = new ExtractorMediaSource.Factory(dataSourceFactory).createMediaSource(Uri.parse(videoUrl));
player.prepare(mediaSource);
player.setPlayWhenReady(true);
}
#Override
public void onStart() {
super.onStart();
if ((Util.SDK_INT > 23)) {
initializePlayer();
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (player != null) {
outState.putLong("current_position", player.getCurrentPosition());
outState.putBoolean("play_state", player.getPlayWhenReady());
}
}
#Override
public void onStop() {
super.onStop();
Log.i(TAG, "onStop:called ");
playerView.setPlayer(null);
if (player != null)
player.release();
}
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy:called ");
playerView.setPlayer(null);
}
#Override
public void onResume() {
super.onResume();
if ((Util.SDK_INT <= 23 || player == null)) {
initializePlayer();
}
}
}
This is the link to the repository..
https://github.com/Rahulxx01/Baking-App-Nanodegree
try adding this line to your player Activity declaration in manifest file:
android:configChanges="orientation|screenSize|layoutDirection"

Cannot click on interstitial ad in WebView fragment

I have made an AdvanceWebView Application.
In that I have made a function to show interstitialAd in "fragmentActivity", that means whenever I download something from that webview that Ad will show up but it isn't clickable.
I think my ad is showing behind that fragment or something like that or maybe some other issue.
And when Vedio Ads are showen, the countdown of that ad also doesn't woprking.
I can see the Ad but it isn't clickable and if I click on any part of Ad, Logcat
is showing this => "I/HwSecImmHelper: mSecurityInputMethodService is null"
Here it is some part of my code:
WebfragmentActivy:
public class WebFragment extends Fragment implements AdvancedWebView.Listener, SwipeRefreshLayout.OnRefreshListener{
//Layouts
public FrameLayout rl;
public AdvancedWebView browser;
public SwipeRefreshLayout swipeLayout;
public ProgressBar progressBar;
//WebView Clients
public WebToAppChromeClient chromeClient;
public WebToAppWebClient webClient;
//WebView Session
public String mainUrl = null;
static String URL = "url";
public int firstLoad = 0;
//Keep track of the interstitials we show
private int interstitialCount = -1;
public WebFragment() {
// Required empty public constructor
}
public static WebFragment newInstance(String url) {
WebFragment fragment = new WebFragment();
Bundle args = new Bundle();
args.putString(URL, url);
fragment.setArguments(args);
return fragment;
}
public void setBaseUrl(String url){
this.mainUrl = url;
browser.loadUrl(mainUrl);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null && mainUrl == null) {
mainUrl = getArguments().getString(URL);
firstLoad = 0;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rl = (FrameLayout) inflater.inflate(R.layout.fragment_observable_web_view, container,
false);
progressBar = (ProgressBar) rl.findViewById(R.id.progressbar);
browser = (AdvancedWebView) rl.findViewById(R.id.scrollable);
swipeLayout = (SwipeRefreshLayout) rl.findViewById(R.id.swipe_container);
return rl;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (Config.PULL_TO_REFRESH)
swipeLayout.setOnRefreshListener(this);
else
swipeLayout.setEnabled(false);
// Setting the webview listeners
browser.setListener(this, this);
// set javascript and zoom and some other settings
browser.requestFocus();
browser.getSettings().setJavaScriptEnabled(true);
browser.getSettings().setBuiltInZoomControls(false);
browser.getSettings().setAppCacheEnabled(true);
browser.getSettings().setDatabaseEnabled(true);
browser.getSettings().setDomStorageEnabled(true);
// Below required for geolocation
browser.setGeolocationEnabled(true);
// 3RD party plugins (on older devices)
browser.getSettings().setPluginState(PluginState.ON);
if (Config.MULTI_WINDOWS) {
browser.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
browser.getSettings().setSupportMultipleWindows(true);
}
webClient = new WebToAppWebClient(getActivity(), browser);
browser.setWebViewClient(webClient);
chromeClient = new WebToAppChromeClient(getActivity(), rl, browser, swipeLayout, progressBar);
browser.setWebChromeClient(chromeClient);
// load url (if connection available
if (webClient.hasConnectivity(mainUrl, true)) {
String pushurl = ((App) getActivity().getApplication()).getPushUrl();
if (pushurl != null){
browser.loadUrl(pushurl);
} else {
browser.loadUrl(mainUrl);
}
}
}
#Override
public void onRefresh() {
browser.reload();
}
#SuppressLint("NewApi")
#Override
public void onPause() {
super.onPause();
browser.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
browser.onDestroy();
}
#SuppressLint("NewApi")
#Override
public void onResume() {
super.onResume();
browser.onResume();
}
#SuppressLint("NewApi")
#Override
public void onDownloadRequested(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
if (!hasPermissionToDownload(getActivity())) return;
String filename = null;
try {
filename = new GetFileInfo().execute(url).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
if (filename == null) {
String fileExtenstion = MimeTypeMap.getFileExtensionFromUrl(url);
filename = URLUtil.guessFileName(url, null, fileExtenstion);
}
if (AdvancedWebView.handleDownload(getActivity(), url, filename)) {
Toast.makeText(getActivity(), getResources().getString(R.string.download_done), Toast.LENGTH_SHORT).show();
onDownloadInterstitialAd();
}
else {
Toast.makeText(getActivity(), getResources().getString(R.string.download_fail), Toast.LENGTH_SHORT).show();
}
}
private static boolean hasPermissionToDownload(final Activity context) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M ||
ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED )
return true;
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(R.string.download_permission_explaination);
builder.setPositiveButton(R.string.common_permission_grant, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Fire off an async request to actually get the permission
// This will show the standard permission request dialog UI
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
context.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
}
});
AlertDialog dialog = builder.create();
dialog.show();
return false;
}
#Override
public void onPageStarted(String url, Bitmap favicon) {
if (firstLoad == 0 && MainActivity.getCollapsingActionBar()){
((MainActivity) getActivity()).showToolbar(this);
firstLoad = 1;
} else if (firstLoad == 0){
firstLoad = 1;
}
}
/**
* Show an interstitial ad
*/
private void onDownloadInterstitialAd(){
final InterstitialAd mInterstitialAd = new InterstitialAd(getActivity());
mInterstitialAd.setAdUnitId(getResources().getString(R.string.ad_interstitial_id));
AdRequest adRequestInter = new AdRequest.Builder().addTestDevice(AdRequest.DEVICE_ID_EMULATOR).build();
mInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
mInterstitialAd.show();
}
});
mInterstitialAd.loadAd(adRequestInter);
}
#Override
public void onPageFinished(String url) {
//showInterstitial();
}
#Override
public void onPageError(int errorCode, String description, String failingUrl) {
// TODO Auto-generated method stub
}
#Override
public void onExternalPageRequest(String url) {
// TODO Auto-generated method stub
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
browser.onActivityResult(requestCode, resultCode, data);
}
}
And this is my Main Activity:
public class MainActivity extends AppCompatActivity implements DrawerFragment.DrawerFragmentListener{
//Views
public Toolbar mToolbar;
public View mHeaderView;
public TabLayout mSlidingTabLayout;
public SwipeableViewPager mViewPager;
//App Navigation Structure
private NavigationAdapter mAdapter;
private DrawerFragment drawerFragment;
private WebFragment CurrentAnimatingFragment = null;
private int CurrentAnimation = 0;
//Identify toolbar state
private static int NO = 0;
private static int HIDING = 1;
private static int SHOWING = 2;
//Keep track of the interstitials we show
private int interstitialCount = 0;
SharedPreferences prefs;
public FirebaseAuth authtt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
authtt = FirebaseAuth.getInstance();
mToolbar = (Toolbar) findViewById(R.id.toolbar);
mHeaderView = (View) findViewById(R.id.header_container);
mSlidingTabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager = (SwipeableViewPager) findViewById(R.id.pager);
setSupportActionBar(mToolbar);
mAdapter = new NavigationAdapter(getSupportFragmentManager(), this);
final Intent intent = getIntent();
final String action = intent.getAction();
if (Intent.ACTION_VIEW.equals(action)) {
String data = intent.getDataString();
((App) getApplication()).setPushUrl(data);
}
hasPermissionToDo(this, Config.PERMISSIONS_REQUIRED);
RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) mViewPager.getLayoutParams();
if ((Config.HIDE_ACTIONBAR && getHideTabs()) || ((Config.HIDE_ACTIONBAR || getHideTabs()) && getCollapsingActionBar())){
lp.topMargin = 0;
} else if ((Config.HIDE_ACTIONBAR || getHideTabs()) || (!Config.HIDE_ACTIONBAR && !getHideTabs() && getCollapsingActionBar())){
lp.topMargin = getActionBarHeight();
} else if (!Config.HIDE_ACTIONBAR && !getHideTabs()){
lp.topMargin = getActionBarHeight() * 2;
}
if (Config.USE_DRAWER) {
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setLogo(R.mipmap.ic_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);
drawerFragment = (DrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
drawerFragment.setDrawerListener(this);
} else {
((DrawerLayout) findViewById(R.id.drawer_layout)).setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
}
mViewPager.setLayoutParams(lp);
mViewPager.setAdapter(mAdapter);
mViewPager.setOffscreenPageLimit(mViewPager.getAdapter().getCount() - 1);
mSlidingTabLayout.setSelectedTabIndicatorColor(getResources().getColor(R.color.accent));
mSlidingTabLayout.setupWithViewPager(mViewPager);
mSlidingTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
if (getCollapsingActionBar()) {
showToolbar(getFragment());
}
mViewPager.setCurrentItem(tab.getPosition());
showInterstitial();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
for (int i = 0; i < mSlidingTabLayout.getTabCount(); i++) {
if (Config.ICONS.length > i && Config.ICONS[i] != 0) {
mSlidingTabLayout.getTabAt(i).setIcon(Config.ICONS[i]);
}
}
// admob
if (!getResources().getString(R.string.ad_banner_id).equals("")) {
// Look up the AdView as a resource and load a request.
AdView adView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
} else {
AdView adView = (AdView) findViewById(R.id.adView);
adView.setVisibility(View.GONE);
}
// application rating
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setTitle(getString(R.string.rate_title))
.setMessage(String.format(getString(R.string.rate_message), getString(R.string.app_name)))
.setPositiveButton(getString(R.string.rate_yes), null)
.setNegativeButton(getString(R.string.rate_never), null)
.setNeutralButton(getString(R.string.rate_later), null);
new AppRate(this)
.setShowIfAppHasCrashed(false)
.setMinDaysUntilPrompt(2)
.setMinLaunchesUntilPrompt(2)
.setCustomDialog(builder)
.init();
// showing the splash screen
if (Config.SPLASH) {
findViewById(R.id.imageLoading1).setVisibility(View.VISIBLE);
//getFragment().browser.setVisibility(View.GONE);
}
}
// using the back button of the device
#Override
public void onBackPressed() {
View customView = null;
WebChromeClient.CustomViewCallback customViewCallback = null;
if (getFragment().chromeClient != null) {
customView = getFragment().chromeClient.getCustomView();
customViewCallback = getFragment().chromeClient.getCustomViewCallback();
}
if ((customView == null)
&& getFragment().browser.canGoBack()) {
getFragment().browser.goBack();
} else if (customView != null
&& customViewCallback != null) {
customViewCallback.onCustomViewHidden();
} else {
super.onBackPressed();
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
public void setTitle(String title) {
if (mAdapter != null && mAdapter.getCount() == 1 && !Config.USE_DRAWER && !Config.STATIC_TOOLBAR_TITLE)
getSupportActionBar().setTitle(title);
}
public WebFragment getFragment(){
return (WebFragment) mAdapter.getCurrentFragment();
}
boolean getHideTabs(){
if (mAdapter.getCount() == 1 || Config.USE_DRAWER){
return true;
} else {
return Config.HIDE_TABS;
}
}
#Override
public boolean onDrawerItemSelected(View view, int position) {
String url = Config.URLS[position];
if (WebToAppWebClient.urlShouldOpenExternally(url)){
try {
view.getContext().startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
} catch(ActivityNotFoundException e) {
if (url.startsWith("intent://")) {
view.getContext().startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(url.replace("intent://", "http://"))));
} else {
Toast.makeText(this, getResources().getString(R.string.no_app_message), Toast.LENGTH_LONG).show();
}
}
return false;
} else {
getFragment().browser.loadUrl("about:blank");
getFragment().setBaseUrl(Config.URLS[position]);
showInterstitial();
return true;
}
}
private static boolean hasPermissionToDo(final Activity context, final String[] permissions) {
boolean oneDenied = false;
for (String permission : permissions) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
ContextCompat.checkSelfPermission(context, permission)
!= PackageManager.PERMISSION_GRANTED)
oneDenied = true;
}
if (!oneDenied) return true;
android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(context);
builder.setMessage(R.string.common_permission_explaination);
builder.setPositiveButton(R.string.common_permission_grant, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Fire off an async request to actually get the permission
// This will show the standard permission request dialog UI
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
context.requestPermissions(permissions,1);
}
});
android.support.v7.app.AlertDialog dialog = builder.create();
dialog.setCanceledOnTouchOutside(false);
dialog.show();
return false;
}
}

Update custom adapter with query results

i want to query results from custom adapter by comparing query text with list in RecycleView, it successfully gets results from query then i make list of results and update the existing adapter but it does not effect anything, i use below code fot that
combinationMessagesList = createCombinationMessagesList();
combinationMessages = createCombinationMessagesList();
combinationMessages.clear();
for (int i = 0; i < combinationMessagesList.size(); i++) {
CombinationMessage message = combinationMessagesList.get(i);
if (message.getBody().toString().equals(search.getText().toString())){
combinationMessages.add(combinationMessagesList.get(i));
}
}
messagesAdapter.setList(combinationmessagesList);
messagesAdapter.notifyDataSetChanged();
}
PrivateDialogActivity
public class PrivateDialogActivity extends BaseDialogActivity {
private FriendOperationAction friendOperationAction;
private FriendObserver friendObserver;
private int operationItemPosition;
private final String TAG = "PrivateDialogActivity";
EditText search;
public static void start(Context context, User opponent, Dialog dialog) {
Intent intent = new Intent(context, PrivateDialogActivity.class);
intent.putExtra(QBServiceConsts.EXTRA_OPPONENT, opponent);
intent.putExtra(QBServiceConsts.EXTRA_DIALOG, dialog);
context.startActivity(intent);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initFields();
context = this;
if (dialog == null) {
finish();
}
setUpActionBarWithUpButton();
if (isNetworkAvailable()) {
deleteTempMessages();
}
addObservers();
initMessagesRecyclerView();
search = (EditText) findViewById(R.id.search_edittext);
Button button = (Button) findViewById(R.id.search);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showResult();
}
});
}
private void showResult() {
combinationMessagesList = createCombinationMessagesList();
combinationMessages = createCombinationMessagesList();
combinationMessages.clear();
for (int i = 0; i < combinationMessagesList.size(); i++) {
CombinationMessage message = combinationMessagesList.get(i);
if (message.getBody().toString().equals(search.getText().toString())){
combinationMessages.add(combinationMessagesList.get(i));
}
}
messagesAdapter.setList(combinationMessagesList);
messagesAdapter.notifyDataSetChanged();
}
#Override
protected void addActions() {
super.addActions();
addAction(QBServiceConsts.ACCEPT_FRIEND_SUCCESS_ACTION, new AcceptFriendSuccessAction());
addAction(QBServiceConsts.ACCEPT_FRIEND_FAIL_ACTION, failAction);
addAction(QBServiceConsts.REJECT_FRIEND_SUCCESS_ACTION, new RejectFriendSuccessAction());
addAction(QBServiceConsts.REJECT_FRIEND_FAIL_ACTION, failAction);
updateBroadcastActionList();
}
#Override
protected void onResume() {
super.onResume();
checkForCorrectChat();
if (isNetworkAvailable()) {
startLoadDialogMessages();
}
checkMessageSendingPossibility();
}
#Override
protected void onDestroy() {
super.onDestroy();
deleteObservers();
}
#Override
protected void updateActionBar() {
setOnlineStatus(opponentUser);
checkActionBarLogo(opponentUser.getAvatar(), R.drawable.placeholder_user);
}
#Override
protected void onConnectServiceLocally(QBService service) {
onConnectServiceLocally();
setOnlineStatus(opponentUser);
}
#Override
protected void onFileLoaded(QBFile file, String dialogId) {
if(!dialogId.equals(dialog.getDialogId())){
return;
}
try {
privateChatHelper.sendPrivateMessageWithAttachImage(file, opponentUser.getUserId(), null, null);
} catch (QBResponseException exc) {
ErrorUtils.showError(this, exc);
}
}
#Override
protected Bundle generateBundleToInitDialog() {
Bundle bundle = new Bundle();
bundle.putInt(QBServiceConsts.EXTRA_OPPONENT_ID, opponentUser.getUserId());
return bundle;
}
#Override
protected void initMessagesRecyclerView() {
super.initMessagesRecyclerView();
messagesAdapter = new PrivateDialogMessagesAdapter(this, friendOperationAction, combinationMessagesList, this, dialog);
messagesRecyclerView.addItemDecoration(
new StickyRecyclerHeadersDecoration((StickyRecyclerHeadersAdapter) messagesAdapter));
findLastFriendsRequest();
messagesRecyclerView.setAdapter(messagesAdapter);
scrollMessagesToBottom();
}
#Override
protected void updateMessagesList() {
initActualExtras();
checkForCorrectChat();
int oldMessagesCount = messagesAdapter.getAllItems().size();
this.combinationMessagesList = createCombinationMessagesList();
Log.d(TAG, "combinationMessagesList = " + combinationMessagesList);
messagesAdapter.setList(combinationMessagesList);
findLastFriendsRequest();
checkForScrolling(oldMessagesCount);
}
private void initActualExtras() {
opponentUser = (User) getIntent().getExtras().getSerializable(QBServiceConsts.EXTRA_OPPONENT);
dialog = (Dialog) getIntent().getExtras().getSerializable(QBServiceConsts.EXTRA_DIALOG);
}
#Override
public void notifyChangedUserStatus(int userId, boolean online) {
super.notifyChangedUserStatus(userId, online);
if (opponentUser != null && opponentUser.getUserId() == userId) {
setOnlineStatus(opponentUser);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.private_dialog_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
boolean isFriend = DataManager.getInstance().getFriendDataManager().getByUserId(
opponentUser.getUserId()) != null;
if (!isFriend && item.getItemId() != android.R.id.home) {
ToastUtils.longToast(R.string.dialog_user_is_not_friend);
return true;
}
switch (item.getItemId()) {
case R.id.action_audio_call:
callToUser(opponentUser, QBRTCTypes.QBConferenceType.QB_CONFERENCE_TYPE_AUDIO);
break;
case R.id.switch_camera_toggle:
callToUser(opponentUser, QBRTCTypes.QBConferenceType.QB_CONFERENCE_TYPE_VIDEO);
break;
default:
super.onOptionsItemSelected(item);
}
return true;
}
#Override
protected void checkMessageSendingPossibility() {
boolean enable = dataManager.getFriendDataManager().existsByUserId(opponentUser.getUserId()) && isNetworkAvailable();
checkMessageSendingPossibility(enable);
}
#OnClick(R.id.toolbar)
void openProfile(View view) {
UserProfileActivity.start(this, opponentUser.getUserId());
}
private void initFields() {
chatHelperIdentifier = QBService.PRIVATE_CHAT_HELPER;
friendOperationAction = new FriendOperationAction();
friendObserver = new FriendObserver();
initActualExtras();
// opponentUser = (User) getIntent().getExtras().getSerializable(QBServiceConsts.EXTRA_OPPONENT);
// dialog = (Dialog) getIntent().getExtras().getSerializable(QBServiceConsts.EXTRA_DIALOG);
combinationMessagesList = createCombinationMessagesList();
title = opponentUser.getFullName();
}
private void addObservers() {
dataManager.getFriendDataManager().addObserver(friendObserver);
}
private void deleteObservers() {
dataManager.getFriendDataManager().deleteObserver(friendObserver);
}
private void findLastFriendsRequest() {
((PrivateDialogMessagesAdapter) messagesAdapter).findLastFriendsRequestMessagesPosition();
messagesAdapter.notifyDataSetChanged();
}
private void setOnlineStatus(User user) {
if (user != null) {
if (friendListHelper != null) {
String offlineStatus = getString(R.string.last_seen, DateUtils.toTodayYesterdayShortDateWithoutYear2(user.getLastLogin()),
DateUtils.formatDateSimpleTime(user.getLastLogin()));
setActionBarSubtitle(
OnlineStatusUtils.getOnlineStatus(this, friendListHelper.isUserOnline(user.getUserId()), offlineStatus));
}
}
}
public void sendMessage(View view) {
sendMessage(true);
}
private void callToUser(User user, QBRTCTypes.QBConferenceType qbConferenceType) {
if (!isChatInitializedAndUserLoggedIn()) {
ToastUtils.longToast(R.string.call_chat_service_is_initializing);
return;
}
List<QBUser> qbUserList = new ArrayList<>(1);
qbUserList.add(UserFriendUtils.createQbUser(user));
CallActivity.start(PrivateDialogActivity.this, qbUserList, qbConferenceType, null);
}
private void acceptUser(final int userId) {
if (isNetworkAvailable()) {
if (!isChatInitializedAndUserLoggedIn()) {
ToastUtils.longToast(R.string.call_chat_service_is_initializing);
return;
}
showProgress();
QBAcceptFriendCommand.start(this, userId);
} else {
ToastUtils.longToast(R.string.dlg_fail_connection);
return;
}
}
private void rejectUser(final int userId) {
if (isNetworkAvailable()) {
if (!isChatInitializedAndUserLoggedIn()) {
ToastUtils.longToast(R.string.call_chat_service_is_initializing);
return;
}
showRejectUserDialog(userId);
} else {
ToastUtils.longToast(R.string.dlg_fail_connection);
return;
}
}
private void showRejectUserDialog(final int userId) {
User user = DataManager.getInstance().getUserDataManager().get(userId);
if (user == null) {
return;
}
TwoButtonsDialogFragment.show(getSupportFragmentManager(),
getString(R.string.dialog_message_reject_friend, user.getFullName()),
new MaterialDialog.ButtonCallback() {
#Override
public void onPositive(MaterialDialog dialog) {
super.onPositive(dialog);
showProgress();
QBRejectFriendCommand.start(PrivateDialogActivity.this, userId);
}
});
}
private void checkForCorrectChat() {
Dialog updatedDialog = null;
if (dialog != null) {
updatedDialog = dataManager.getDialogDataManager().getByDialogId(dialog.getDialogId());
} else {
finish();
}
if (updatedDialog == null) {
finish();
} else {
dialog = updatedDialog;
}
}
private class FriendOperationAction implements FriendOperationListener {
#Override
public void onAcceptUserClicked(int position, int userId) {
operationItemPosition = position;
acceptUser(userId);
}
#Override
public void onRejectUserClicked(int position, int userId) {
operationItemPosition = position;
rejectUser(userId);
}
}
private class AcceptFriendSuccessAction implements Command {
#Override
public void execute(Bundle bundle) {
((PrivateDialogMessagesAdapter) messagesAdapter).clearLastRequestMessagePosition();
messagesAdapter.notifyItemChanged(operationItemPosition);
startLoadDialogMessages();
hideProgress();
}
}
private class RejectFriendSuccessAction implements Command {
#Override
public void execute(Bundle bundle) {
((PrivateDialogMessagesAdapter) messagesAdapter).clearLastRequestMessagePosition();
messagesAdapter.notifyItemChanged(operationItemPosition);
startLoadDialogMessages();
hideProgress();
}
}
private class FriendObserver implements Observer {
#Override
public void update(Observable observable, Object data) {
if (data != null && data.equals(FriendDataManager.OBSERVE_KEY)) {
checkForCorrectChat();
checkMessageSendingPossibility();
}
}
}
}
it was my own mistake it code, i made the code work by changing messagesAdapter.setList(combinationmessagesList)
to
messagesAdapter.setList(combinationMessages);

Categories

Resources