Cannot click on interstitial ad in WebView fragment - android

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

Related

How do I check if the download completed in onCreate android fetch library?

How do I check if the download completed in onCreate fetch library?
The following code work without problem, but maybe user cancel the download operation before completion and incomplete file exists in the path.
public class MainActivity extends AppCompatActivity implements FetchObserver<Download> {
private Button Edame, tavaghof, DownloadImage, online;
public static TextView etaTextView;
public static TextView downloadSpeedTextView;
public static Request request;
public static Fetch fetch;
public static ProgressBar progressBar;
public static TextView progressTextView;
private LinearLayout dllaye;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
File root = android.os.Environment.getExternalStorageDirectory();
File path = new File(root.getAbsolutePath() + "/telavat/" + "naba.mp3");
if (path.exists()) {
dllaye.setVisibility(View.GONE);
}
} catch (Exception e) {
}
FetchConfiguration fetchConfiguration = new FetchConfiguration.Builder(this)
.setDownloadConcurrentLimit(3)
.build();
fetch = Fetch.Impl.getInstance(fetchConfiguration);
DownloadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
enqueueDownload();
}
});
Edame.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fetch.resume(request.getId());
}
});
tavaghof.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fetch.pause(request.getId());
}
});
//EndOnceate
}
private void enqueueDownload() {
File root = android.os.Environment.getExternalStorageDirectory();
final String url = "https://amoozesh3.ir/play/naba.mp3";
final String filePath = root.getAbsolutePath() + "/telavatquran/" + Uri.parse(url).getLastPathSegment();
request = new Request(url, filePath);
request.setExtras(getExtrasForRequest(request));
fetch.attachFetchObserversForDownload(request.getId(), this)
.enqueue(request, new Func<Request>() {
#Override
public void call(#NotNull Request result) {
request = result;
}
}, new Func<Error>() {
#Override
public void call(#NotNull Error result) {
}
});
}
#Override
protected void onResume() {
super.onResume();
if (request != null) {
fetch.attachFetchObserversForDownload(request.getId(), this);
}
}
#Override
protected void onPause() {
super.onPause();
if (request != null) {
fetch.removeFetchObserversForDownload(request.getId(), this);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
fetch.close();
}
#Override
public void onChanged(Download data, #NotNull Reason reason) {
updateViews(data, reason);
}
private Extras getExtrasForRequest(Request request) {
final MutableExtras extras = new MutableExtras();
extras.putBoolean("testBoolean", true);
extras.putString("testString", "test");
extras.putFloat("testFloat", Float.MIN_VALUE);
extras.putDouble("testDouble", Double.MIN_VALUE);
extras.putInt("testInt", Integer.MAX_VALUE);
extras.putLong("testLong", Long.MAX_VALUE);
return extras;
}
private void updateViews(#NotNull Download download, Reason reason) {
if (request.getId() == download.getId()) {
if (reason == Reason.DOWNLOAD_COMPLETED) {
dllaye.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), "File download successful",
Toast.LENGTH_LONG).show();
}
setProgressView(download.getStatus(), download.getProgress());
etaTextView.setText(Utils.getETAString(this, download.getEtaInMilliSeconds()));
downloadSpeedTextView.setText(Utils.getDownloadSpeedString(this, download.getDownloadedBytesPerSecond()));
}
}
private void setProgressView(#NonNull final Status status, final int progress) {
switch (status) {
case QUEUED: {
progressTextView.setText(R.string.queued);
progressBar.setProgress(progress);
break;
}
case ADDED: {
progressTextView.setText(R.string.added);
progressBar.setProgress(progress);
break;
}
case DOWNLOADING: {
if (progress == -1) {
progressTextView.setText(R.string.downloading);
progressBar.setProgress(progress);
} else {
final String progressString = getResources().getString(R.string.percent_progress, progress);
progressTextView.setText(progressString);
progressBar.setProgress(progress);
}
break;
}
case COMPLETED: {
break;
}
default: {
progressTextView.setText(R.string.status_unknown);
progressBar.setProgress(progress);
break;
}
}
}
}
I want to free up more space on the screen after downloading
How can I understand the download is completed?
I’d appreciate your cooperation.

Show custom interstitial ad like as admob interstitial ad

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!

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

Skipped 98 frames! The application may be doing too much work on its main thread

I have navigationdrawer with nav menus. When clicking on each nav menus, specific fragment opened. Each fragment display recylerviews who fetch data from SQLite external database.Now when open new fragment, little seconds must wait and when to click on each item for go to next activity for display details information about the item, 5 seconds must wait to open Details Activity. I know this is a problem for fetching data in main Thread and fetch bitmap in the main thread.But I don't know how to solve this problem with use AsyncTask.My big problem is an open new activity for display information and waiting for 5 seconds.
This is my asiafragment.
AsiaFragment
public class AsiaFragment extends Fragment {
private static final String ASIA_FRAGMENT = "asia_fragment";
ArrayList<AsiaCountry> asiaCountries = new ArrayList<>();
ContentAdapter contentAdapter;
RecyclerView recyclerView;
private boolean isListView;
private Menu menu;
private StaggeredGridLayoutManager staggeredGridLayoutManager;
private MyAsyncTas myAsyncTas;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.asia_fragment, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
getActivity().setTitle("Asia");
isListView = true;
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
new MyAsyncTas().execute();
}
// When click on grid icon, view items must be convert to grid.
public void toggle() {
MenuItem item = menu.findItem(R.id.grid);
if (isListView) {
staggeredGridLayoutManager.setSpanCount(2);
item.setIcon(R.drawable.ic_vertical);
item.setTitle("Show as list");
isListView = false;
} else {
staggeredGridLayoutManager.setSpanCount(1);
item.setIcon(R.drawable.ic_grid);
item.setTitle("Show grid");
isListView = true;
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.grid_item, menu);
this.menu = menu;
Log.d("Menu created", "grid");
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.grid) {
Toast.makeText(getActivity(), "Grid item touched", Toast.LENGTH_SHORT).show();
toggle();
return true;
}
if (id == R.id.settings) {
Toast.makeText(getActivity(), "Setting clicked", Toast.LENGTH_SHORT).show();
return true;
}
return onOptionsItemSelected(item);
}
// When loading AsiaFragment, database loading from Eternal database.
public void loadDataBase() {
WorldCountryDatabase worldCountryDatabase = new WorldCountryDatabase(getActivity());
try {
worldCountryDatabase.createDatabase();
worldCountryDatabase.openDataBase();
Log.d("TAG", "Database open");
} catch (SQLiteException o) {
o.printStackTrace();
Log.d("Tag", o.getMessage());
}
try {
// Tell to database , take name and viewImage from worldCountries .
Cursor cursor = worldCountryDatabase.QueryData("SELECT name, Image FROM country WHERE continent ='آسیا'");
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
AsiaCountry asiaCountry = new AsiaCountry();
asiaCountry.setName(cursor.getString(0));
asiaCountry.setFlag(cursor.getString(1));
Log.d(ASIA_FRAGMENT, cursor.getString(1));
asiaCountries.add(asiaCountry);
} while (cursor.moveToNext());
worldCountryDatabase.close();
}
}
} catch (SQLiteException o) {
o.printStackTrace();
Log.d("TAG", o.getMessage());
}
// When loading RecylerView staggeredGridLayout loading.
staggeredGridLayoutManager = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL);
contentAdapter = new ContentAdapter(getActivity(), asiaCountries);
contentAdapter.notifyDataSetChanged();
contentAdapter.setListener(new ContentAdapter.Listener() {
#Override
public void onClick(int position) {
}
});
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(staggeredGridLayoutManager);
recyclerView.setAdapter(contentAdapter);
}
public class MyAsyncTas extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... params) {
return true;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
loadDataBase();
}
}
This is my DetailCountry fragment, who must be displayed detatail country clicked.
DetailsCountry
public class DetailsCountry extends AppCompatActivity implements
TabLayout.OnTabSelectedListener,
EconomicFragment.EconomicOnFragmentInteractionListener,
SummarizeFragment.SummarizeOnFragmentInteractionListener,
HistoryFragment.HistoryOnFragmentInteractionListener,
GeographyFragment.GeographyOnFragmentInteractionListener,
TipsFragment.TipsOnFragmentInteractionListener,
DescriptionFragment.OtherOnFragmentInteractionListener,
PeopleFragment.PeopleOnFragmentInteractionListener {
public static String NAME_COUNTRY = "name";
public final String pageTitle[] = {"خلاصه",
"تاریخ",
"جغرافی",
"اقتصاد",
"مردم",
"غیره",
"نکات"};
ArrayList<AsiaCountry> asiaList = new ArrayList<>();
ImageView imageHistory;
TabLayout tabLayout;
ViewPager viewPager;
String content;
Bundle bundle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detial_country);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_details);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
viewPager = (ViewPager) findViewById(R.id.viewPager_detail_country);
tabLayout = (TabLayout) findViewById(R.id.tabLayout_detail_country);
imageHistory = (ImageView) findViewById(R.id.image_detail_country);
bundle = getIntent().getExtras();
if (bundle != null) {
content = bundle.getString("name");
Log.d("contentDetail", content);
}
// Set title for activity title.
getSupportActionBar().setTitle(content);
retrieveData();
if (asiaList != null && asiaList.size() > 0) {
for (int i = 0; i < asiaList.size(); i++) {
imageHistory.setImageBitmap(loadBitmapFromAssets(getApplicationContext(),
asiaList.get(i).getImageResourceID()));
}
}
int numberPage = 7;
for (int i = 0; i < numberPage; i++) {
tabLayout.addTab(tabLayout.newTab().setText(pageTitle[i]));
}
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
ViewPagerCountryAdapter viewPagerAdapter = new ViewPagerCountryAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setOnTabSelectedListener(this);
}
private void retrieveData() {
WorldCountryDatabase worldCountryDatabase = new WorldCountryDatabase(getApplicationContext());
worldCountryDatabase.createDatabase();
worldCountryDatabase.openDataBase();
Log.d(ARG_PARAM1, "Database opened");
try {
Cursor cursor = worldCountryDatabase.QueryData("SELECT viewImage FROM country WHERE name = '" + content + "'");
Log.d("CURSOR", cursor.toString());
if (cursor.moveToFirst()) {
do {
AsiaCountry asia = new AsiaCountry();
asia.setImageResourceID(cursor.getString(0));
Log.d("image", cursor.getString(0));
asiaList.add(asia);
} while (cursor.moveToNext());
cursor.close();
}
} catch (SQLException e) {
e.printStackTrace();
Log.d("TAG", e.getMessage());
}
}
#Nullable
private Bitmap loadBitmapFromAssets(Context context, String path) {
InputStream stream = null;
try {
stream = context.getAssets().open(path);
return BitmapFactory.decodeStream(stream);
} catch (Exception ignored) {
} finally {
try {
if (stream != null) {
stream.close();
}
} catch (Exception ignored) {
}
}
return null;
}
#Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(base));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
#Override
public void economiOnFragmentInteraction(Uri uri) {
}
#Override
public void tipsOnFragmentInteraction(Uri uri) {
}
#Override
public void otherOnFragmentInteraction(Uri uri) {
}
#Override
public void peopleOnFragmentInteraction(Uri uri) {
}
#Override
public void historyOnFragmentInteraction(Uri uri) {
}
#Override
public void geographyOnFragmentInteraction(Uri uri) {
}
#Override
public void summarizeOnFragmentInteraction(Uri uri) {
}
public class DetailTask extends AsyncTask<Void, Void, Boolean>{
#Override
protected Boolean doInBackground(Void... params) {
return null;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
}
}
Please help me, good friends. Thanks

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