Ive been working on learning how to make games and Id like to understand how to add Adverts. The advert shows? But only after I close and reopen, "SMART_BANNER" doesnt work either. What am I doing wrong?
public class MainActivity extends FragmentActivity {
public GoogleApiClient apiClient;
private MainActivity main = this;
public GameSurface gameSurface;
RelativeLayout layout;
RelativeLayout adlayout;
private Saver saver;
private static final String HIGHSCORE = "highscore";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
apiClient = new GoogleApiClient.Builder(this)
.addApi(Games.API)
.addScope(Games.SCOPE_GAMES)
.enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Toast.makeText(getBaseContext(), "Connection To Google Games Failed, No App Found Or No Internet", Toast.LENGTH_SHORT).show();
}
}).build();
MobileAds.initialize(this, getString(R.string.adappid));
apiClient.connect();
saver = Saver.getInstance(this);
playerscores();
// fullscreen
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
layout = new RelativeLayout(this);
layout.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
AdView adView = new AdView(this);
adView.setAdSize(AdSize.BANNER);
adView.setAdUnitId("ca-app-pub-3940256099942544/6300978111");
AdRequest.Builder adRequestBuilder = new AdRequest.Builder();
adRequestBuilder.addTestDevice(AdRequest.DEVICE_ID_EMULATOR);
adView.loadAd(adRequestBuilder.build());
//ads
gameSurface = new GameSurface(this, main);
layout.addView(gameSurface);
layout.addView(adView);
setContentView(layout);
}
// Set No Title
//this.setContentView(new GameSurface(this));
public void playerscores() {
if (apiClient != null && apiClient.isConnected()) {
Games.Leaderboards.loadCurrentPlayerLeaderboardScore(apiClient, "CgkI08DA0-sZEAIQAQ", LeaderboardVariant.TIME_SPAN_ALL_TIME, LeaderboardVariant.COLLECTION_PUBLIC).setResultCallback(
new ResultCallback<Leaderboards.LoadPlayerScoreResult>() {
#Override
public void onResult(Leaderboards.LoadPlayerScoreResult arg0) {
LeaderboardScore c = arg0.getScore();
String score = c.getDisplayScore();
saver.saveString(HIGHSCORE, score);
}
});
}
}
public void gameover() {
if (apiClient != null && apiClient.isConnected()) {
Games.Leaderboards.submitScore(apiClient, getString(R.string.leaderboard_highscores), GameSurface.HighScore);
}
}
public void showLeaderboard() {
if (apiClient != null && apiClient.isConnected()) {
startActivityForResult(Games.Leaderboards.getLeaderboardIntent(apiClient, "CgkI08DA0-sZEAIQAQ"), 1);
} else {
apiClient.connect();
}
}
}
Basically I want the advert to show as soon as the app opens. Id Also like it to be fixed to the bottom, I cant find a way to do this, I've tried adding gravity but adview doesn't have this attribute.
Any advice as to what Im doing wrong will be greatly appreciated.
Part Answer I worked out how to get the advert align to the bottom and Center it.
RelativeLayout.LayoutParams viewParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);viewParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);viewParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
adView.setLayoutParams(viewParams);
EDIT [SOLVED]
added an adview listener, reading through admob docs and seeing various listeners gave me an idea!
then just made it redraw its self.
adView.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
adView.setVisibility(View.GONE);
adView.setVisibility(View.VISIBLE);
}
});
you should add the view before loading the ad, if you want to show the ad faster just call setContentView() as soon as possible and then load the ad
Related
I am learning RecyclerView in MVVM pattern from a youtube video. I create a recycler view to load very simple items. It works fine, but when I navigate to a new activity and then come back to the activity using Recycler View. My items in the list is duplicated. For example, my recycler view shows 2 items like Item1 and Item2. After I move to a new activity and return back, the list become Item1, Item 2, Item1 and Item2. So, each time I move to the new activity and return back, it keep doubling more and more. I only want the recycler view load one time, how can I solve this problem? Thank you.
My repo:
public class DWCategoryRepository {
private static DWCategoryRepository instance;
private ArrayList<DWCategories> dataSet = new ArrayList<>();
public static DWCategoryRepository getInstance() {
if (instance == null){
instance = new DWCategoryRepository();
}
return instance;
}
public MutableLiveData<List<DWCategories>> getDWCategories(){
setDWCategories();
MutableLiveData<List<DWCategories>> data = new MutableLiveData<>();
data.setValue(dataSet);
return data;
}
private void setDWCategories() {
dataSet.add(new DWCategories("Item1"));
dataSet.add(new DWCategories("Item2"));
}
}
My ViewModel:
public class MainWalletViewModel extends ViewModel {
private MutableLiveData<List<DWCategories>> mCategories;
private DWCategoryRepository mRepo;
public void init(){
if (mCategories != null) {
return;
}
mRepo = DWCategoryRepository.getInstance();
mCategories = mRepo.getDWCategories();
}
public LiveData<List<DWCategories>> getDWCategories(){
return mCategories;
}
}
View:
public class MainWalletActivity extends DWBaseActivity implements WalletCategoryAdapter.OnCategoryListener {
private WalletCategoryAdapter mWalletCategoryAdapter;
private MainWalletViewModel mMainWalletViewModel;
private RecyclerView mRecyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initializeDataBinding();
}
private void initializeDataBinding() {
MainWalletActivityBinding dataBinding = DataBindingUtil.setContentView(this, R.layout.main_wallet_activity);
setSupportActionBar(dataBinding.walletToolbar);
//Enable Back button on Toolbar
showBackArrowOnToolbar();
//Get Categories from View Model
initCategories();
//Set up adapter
mWalletCategoryAdapter = new WalletCategoryAdapter(this, mMainWalletViewModel.getDWCategories().getValue(), this);
//Set adapter to Recycler view
mRecyclerView = dataBinding.walletCategoryRV;
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setAdapter(mWalletCategoryAdapter);
//Add divider to Recycler view
mRecyclerView.addItemDecoration(new DividerItemDecoration(MainWalletActivity.this,
DividerItemDecoration.VERTICAL));
}
private void initCategories(){
mMainWalletViewModel = ViewModelProviders.of(this).get(MainWalletViewModel.class);
mMainWalletViewModel.init();
mMainWalletViewModel.getDWCategories().observe(this, new Observer<List<DWCategories>>() {
#Override
public void onChanged(#Nullable List<DWCategories> dwCategories) {
mWalletCategoryAdapter.notifyDataSetChanged();
}
});
}
}
You are calling setDWCategories in your getter.
public MutableLiveData<List<DWCategories>> getDWCategories(){
setDWCategories(); // <- Remove this line!
MutableLiveData<List<DWCategories>> data = new MutableLiveData<>();
data.setValue(dataSet);
return data;
}
You should only initialize your repo data once. Maybe do it in your getInstance() method if you are ok, starting over every time you run the app.
I try to put advanced ads inside the dialog box when you close the application, but when you open a dialog box does not load the ad for the first time. ... I am worried that I load the ad inside the application
without appearing and at closing I put it in the dialog box for fear that the agent considers it a google violation to download the ad without its appearance
Constant code from android developer
public class MainActivity extends AppCompatActivity {
private static final String ADMOB_AD_UNIT_ID = "ca-app-pub-3940256099942544/2247696110";
private static final String ADMOB_APP_ID = "ca-app-pub-3940256099942544~3347511713";
AdLoader.Builder builder;
UnifiedNativeAdView adView;
private Button refresh;
private CheckBox startVideoAdsMuted;
private TextView videoStatus;
private UnifiedNativeAd nativeAd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize the Mobile Ads SDK.
MobileAds.initialize(this, ADMOB_APP_ID);
refresh = findViewById(R.id.btn_refresh);
startVideoAdsMuted = findViewById(R.id.cb_start_muted);
videoStatus = findViewById(R.id.tv_video_status);
refresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View unusedView) {
refreshAd();
}
});
refreshAd();
}
/**
* Populates a {#link UnifiedNativeAdView} object with data from a given
* {#link UnifiedNativeAd}.
*
* #param nativeAd the object containing the ad's assets
* #param adView the view to be populated
*/
private void populateUnifiedNativeAdView(UnifiedNativeAd nativeAd, UnifiedNativeAdView adView) {
// Set the media view. Media content will be automatically populated in the media view once
// adView.setNativeAd() is called.
MediaView mediaView = adView.findViewById(R.id.ad_media);
adView.setMediaView(mediaView);
// Set other ad assets.
adView.setHeadlineView(adView.findViewById(R.id.ad_headline));
adView.setBodyView(adView.findViewById(R.id.ad_body));
adView.setCallToActionView(adView.findViewById(R.id.ad_call_to_action));
adView.setIconView(adView.findViewById(R.id.ad_app_icon));
adView.setPriceView(adView.findViewById(R.id.ad_price));
adView.setStarRatingView(adView.findViewById(R.id.ad_stars));
adView.setStoreView(adView.findViewById(R.id.ad_store));
adView.setAdvertiserView(adView.findViewById(R.id.ad_advertiser));
// The headline is guaranteed to be in every UnifiedNativeAd.
((TextView) adView.getHeadlineView()).setText(nativeAd.getHeadline());
// These assets aren't guaranteed to be in every UnifiedNativeAd, so it's important to
// check before trying to display them.
if (nativeAd.getBody() == null) {
adView.getBodyView().setVisibility(View.INVISIBLE);
} else {
adView.getBodyView().setVisibility(View.VISIBLE);
((TextView) adView.getBodyView()).setText(nativeAd.getBody());
}
if (nativeAd.getCallToAction() == null) {
adView.getCallToActionView().setVisibility(View.INVISIBLE);
} else {
adView.getCallToActionView().setVisibility(View.VISIBLE);
((Button) adView.getCallToActionView()).setText(nativeAd.getCallToAction());
}
if (nativeAd.getIcon() == null) {
adView.getIconView().setVisibility(View.GONE);
} else {
((ImageView) adView.getIconView()).setImageDrawable(
nativeAd.getIcon().getDrawable());
adView.getIconView().setVisibility(View.VISIBLE);
}
if (nativeAd.getPrice() == null) {
adView.getPriceView().setVisibility(View.INVISIBLE);
} else {
adView.getPriceView().setVisibility(View.VISIBLE);
((TextView) adView.getPriceView()).setText(nativeAd.getPrice());
}
if (nativeAd.getStore() == null) {
adView.getStoreView().setVisibility(View.INVISIBLE);
} else {
adView.getStoreView().setVisibility(View.VISIBLE);
((TextView) adView.getStoreView()).setText(nativeAd.getStore());
}
if (nativeAd.getStarRating() == null) {
adView.getStarRatingView().setVisibility(View.INVISIBLE);
} else {
((RatingBar) adView.getStarRatingView())
.setRating(nativeAd.getStarRating().floatValue());
adView.getStarRatingView().setVisibility(View.VISIBLE);
}
if (nativeAd.getAdvertiser() == null) {
adView.getAdvertiserView().setVisibility(View.INVISIBLE);
} else {
((TextView) adView.getAdvertiserView()).setText(nativeAd.getAdvertiser());
adView.getAdvertiserView().setVisibility(View.VISIBLE);
}
// This method tells the Google Mobile Ads SDK that you have finished populating your
// native ad view with this native ad. The SDK will populate the adView's MediaView
// with the media content from this native ad.
adView.setNativeAd(nativeAd);
// Get the video controller for the ad. One will always be provided, even if the ad doesn't
// have a video asset.
VideoController vc = nativeAd.getVideoController();
// Updates the UI to say whether or not this ad has a video asset.
if (vc.hasVideoContent()) {
videoStatus.setText(String.format(Locale.getDefault(),
"Video status: Ad contains a %.2f:1 video asset.",
vc.getAspectRatio()));
// Create a new VideoLifecycleCallbacks object and pass it to the VideoController. The
// VideoController will call methods on this object when events occur in the video
// lifecycle.
vc.setVideoLifecycleCallbacks(new VideoController.VideoLifecycleCallbacks() {
#Override
public void onVideoEnd() {
// Publishers should allow native ads to complete video playback before
// refreshing or replacing them with another ad in the same UI location.
refresh.setEnabled(true);
videoStatus.setText("Video status: Video playback has ended.");
super.onVideoEnd();
}
});
} else {
videoStatus.setText("Video status: Ad does not contain a video asset.");
refresh.setEnabled(true);
}
}
/**
* Creates a request for a new native ad based on the boolean parameters and calls the
* corresponding "populate" method when one is successfully returned.
*
*/
private void refreshAd() {
refresh.setEnabled(false);
builder = new AdLoader.Builder(this, ADMOB_AD_UNIT_ID);
builder.forUnifiedNativeAd(new UnifiedNativeAd.OnUnifiedNativeAdLoadedListener() {
// OnUnifiedNativeAdLoadedListener implementation.
#Override
public void onUnifiedNativeAdLoaded(UnifiedNativeAd unifiedNativeAd) {
// You must call destroy on old ads when you are done with them,
// otherwise you will have a memory leak.
if (nativeAd != null) {
nativeAd.destroy();
}
nativeAd = unifiedNativeAd;
FrameLayout frameLayout =
findViewById(R.id.fl_adplaceholder);
adView = (UnifiedNativeAdView) getLayoutInflater()
.inflate(R.layout.ad_unified, null);
populateUnifiedNativeAdView(unifiedNativeAd, adView);
frameLayout.removeAllViews();
frameLayout.addView(adView);
}
});
VideoOptions videoOptions = new VideoOptions.Builder()
.setStartMuted(startVideoAdsMuted.isChecked())
.build();
NativeAdOptions adOptions = new NativeAdOptions.Builder()
.setVideoOptions(videoOptions)
.build();
builder.withNativeAdOptions(adOptions);
AdLoader adLoader = builder.withAdListener(new AdListener() {
#Override
public void onAdFailedToLoad(int errorCode) {
refresh.setEnabled(true);
Toast.makeText(MainActivity.this, "Failed to load native ad: "
+ errorCode, Toast.LENGTH_SHORT).show();
}
}).build();
adLoader.loadAd(new AdRequest.Builder().build());
videoStatus.setText("");
}
Now I'm trying to put the code refresh method insaid dialog box instead of refresh method
public void showdilog(){
builder = new AdLoader.Builder(this, ADMOB_AD_UNIT_ID);
builder.forUnifiedNativeAd(new UnifiedNativeAd.OnUnifiedNativeAdLoadedListener() {
// OnUnifiedNativeAdLoadedListener implementation.
#Override
public void onUnifiedNativeAdLoaded(UnifiedNativeAd unifiedNativeAd) {
// You must call destroy on old ads when you are done with them,
// otherwise you will have a memory leak.
if (nativeAd != null) {
nativeAd.destroy();
}
nativeAd = unifiedNativeAd;
FrameLayout frameLayout =
findViewById(R.id.fl_adplaceholder);
adView = (UnifiedNativeAdView) getLayoutInflater()
.inflate(R.layout.ad_unified, null);
populateUnifiedNativeAdView(unifiedNativeAd, adView);
frameLayout.removeAllViews();
frameLayout.addView(adView);
}
});
VideoOptions videoOptions = new VideoOptions.Builder()
.setStartMuted(startVideoAdsMuted.isChecked())
.build();
NativeAdOptions adOptions = new NativeAdOptions.Builder()
.setVideoOptions(videoOptions)
.build();
builder.withNativeAdOptions(adOptions);
AdLoader adLoader = builder.withAdListener(new AdListener() {
#Override
public void onAdFailedToLoad(int errorCode) {
refresh.setEnabled(true);
Toast.makeText(MainActivity.this, "Failed to load native ad: "
+ errorCode, Toast.LENGTH_SHORT).show();
}
}).build();
adLoader.loadAd(new AdRequest.Builder().build());
AlertDialog.Builder builder = new AlertDialog.Builder(this);
bulider.setView(adView);
builder.setMessage(R.string.onfirm_exit)
.setCancelable(false)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
What you're doing is that you're building and showing your dialog box at the same time. So, at the time you show your dialog box you're also loading your native ad.
You should BUILD your dialog box in advance, and don't call alert.show() in your build function.
So, call your buildDialog() in MainActivity in advance.
In your onBackPressed function call alert.show().
Hope it helps.
I'm trying to make messages like in messenger. They must appear one after another. So I use the LinearLayout and add the TextView to it. But the appear all at once. I use the loop, but it looks like it doesn't work!
Here is the code
final LinearLayout lm = (LinearLayout) findViewById(R.id.line_layout);
final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
params.setMargins(10, 10, 500, 50);
int i = 0;
for (final Task task : tasks) {
i = i + 1;
for (int j = 0; j < 1; j++) {
final TextView message = new TextView(TaskActivity.this);
message.setText(task.getName());
message.setId(task.getId());
message.setLayoutParams(params);
message.setTextSize(30);
message.setBackground(getApplicationContext().getDrawable(R.drawable.task_text));
Toast.makeText(TaskActivity.this, "Text loaded",
Toast.LENGTH_SHORT).show();
lm.addView(message);
SystemClock.sleep(1000);
}
}
The TextViews appear at once no matter the timer. The app waits while the Timer for every circle of the loop and returns the hole messengers at once!
See the screenshot of the app:
So how would you do this task and resolve the problem? Thank you!
If you want the behaviour as in Messenger , you should use RecyclerView in android.
https://developer.android.com/guide/topics/ui/layout/recyclerview
With the time interval to add a new message, you can use recyclerview notify methods to show the new messages.
define a layout in which you need to add your textView and then do the following
LayoutParams lparams = new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
TextView tv=new TextView(this);
tv.setLayoutParams(lparams);
tv.setText("test");
this.parentLayout.addView(tv);
Your code is running on the uiThread so the UI doesn't update until the loop is complete. Have a look at using an AsyncTask to pause the app in the background and do the update after finishing. Try something like this:
public class TestActivity extends Activity
{
Queue<String> messages = new LinkedList<String>();
class PushNextMessage extends AsyncTask<Void, Void, Void>
{
#Override
protected Void doInBackground(Void... params)
{
try
{
Thread.sleep(1000);
}
catch (Exception ex)
{
ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void _void)
{
String message = messages.remove();
//this is where you add the view to the base layout
if (messages.size() > 0)
{
new PushNextMessage().execute();
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
messages.add("message 1");
messages.add("message 2");
messages.add("message 3");
new PushNextMessage().execute();
}
}
I am a beginner-intermediate android developer. I started working with fragments in my this app. The structure of the app is:
Main activity where some important links are embedded with buttons
On clicking button from main activity, some DB tasks completed (with Room Library so all tasks are using AsyncTask) and new activity opens with link in intent extra
On getting the link, the new activity-2 adds a fragment (in itself) and also performs some DB tasks in background and then opens the link in webview of fragment.
The problem is, from 1-2 it is taking merely 0.1-0.15 seconds while on starting the task 3, it is taking 0.3-0.45 seconds so on clicking from main activity, user is getting the link opened in fragment (which has webview) in about 0.6 seconds which is making feel like app is freezing.
Here are some codes:
Activity-2:
#Override
protected void onCreate(Bundle savedInstanceState) {
prefSingleton = PrefSingleton.getInstance();
if (prefSingleton.getStorage().getBoolean(Constants.STORAGE_ENABLE_NIGHTMODE,false)){
setTheme(R.style.DarkTheme);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_website_view);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
closeWebview = toolbar.findViewById(R.id.closeWebview);
downArrow = toolbar.findViewById(R.id.downArrow);
allTabs = toolbar.findViewById(R.id.allTabs);
searchIcon = toolbar.findViewById(R.id.search);
clearEditText = toolbar.findViewById(R.id.clearEditText);
selectedSEImage = toolbar.findViewById(R.id.selectedSEImage);
searchEditText = toolbar.findViewById(R.id.searchEditText);
searchEngineFrame = toolbar.findViewById(R.id.searchEngine);
searchBarLayout = toolbar.findViewById(R.id.searchBarLayout);
toolbarTitle = toolbar.findViewById(R.id.toolBarTitle);
navFrame = findViewById(R.id.navFrame);
navRecView = findViewById(R.id.navRecView);
if (prefSingleton.getStorage().getBoolean(Constants.STORAGE_ENABLE_NIGHTMODE,false)){
navFrame.setBackgroundColor(getResources().getColor(R.color.night_mode_toolbar));
}
//Activity toolbar views
closeWebview.setOnClickListener(this);
closeWebview.setOnLongClickListener(this);
downArrow.setOnClickListener(this);
allTabs.setOnClickListener(this);
searchIcon.setOnClickListener(this);
clearEditText.setOnClickListener(this);
searchEngineFrame.setOnClickListener(this);
searchEditText.setOnClickListener(this);
searchEditText.setOnKeyListener(this);
//Intent from main activity
Intent i = getIntent();
String urlType = i.getStringExtra(String.valueOf(EnumVal.SiteInfoToSend.TYPE));
final String url = i.getStringExtra(String.valueOf(EnumVal.SiteInfoToSend.URL));
String title = i.getStringExtra(String.valueOf(EnumVal.SiteInfoToSend.TITLE));
String searchedText = i.getStringExtra(String.valueOf(EnumVal.SiteInfoToSend.SEARCHED_TEXT));
fragCounter = 0;
fragTags = new ArrayList<>();
//Fragment opening
if (savedInstanceState == null){
openFragment(url, EnumVal.FragStatus.NEW, null);
}
//AdMob Ads
if (!BuildConfig.PAID_VERSION){
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId(getResources().getString(R.string.interstitial_webview));
mInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdFailedToLoad(int errorCode) {
if(ConsentInformation.getInstance(WebsiteView.this).getConsentStatus() ==
ConsentStatus.NON_PERSONALIZED){
Bundle extras = new Bundle();
extras.putString("npa", "1");
mInterstitialAd.loadAd(new AdRequest.Builder()
.addNetworkExtrasBundle(AdMobAdapter.class,extras).build());
} else {
mInterstitialAd.loadAd(new AdRequest.Builder().build());
}
}
});
if(ConsentInformation.getInstance(WebsiteView.this).getConsentStatus() == ConsentStatus.NON_PERSONALIZED){
Bundle extras = new Bundle();
extras.putString("npa", "1");
mInterstitialAd.loadAd(new AdRequest.Builder()
.addNetworkExtrasBundle(AdMobAdapter.class,extras).build());
} else {
mInterstitialAd.loadAd(new AdRequest.Builder().build());
}
}
//Toolbar search edit text will be enabled in below case
if (urlType.equals(EnumVal.Type.SEARCHED_TEXT.toString())){
searchBarLayout.setVisibility(View.VISIBLE);
searchIcon.setImageResource(R.drawable.close_icon);
searchEditText.setText(searchedText);
searchEditText.clearFocus();
searchEditText.setCursorVisible(false);
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
if (searchEditText.hasFocus())
searchEditText.setCursorVisible(true);
}
searchEditText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
clearEditText.setVisibility(View.VISIBLE);
}
});
//Navigation view in toolbar
navRecView.setLayoutManager(new LinearLayoutManager(this));
mViewModel = ViewModelProviders.of(this).get(DbViewModel.class);
mViewModel.getSitesWithClicksByIsShown().observe(this, new Observer<List<SitesWithClicks>>() {
#Override
public void onChanged(#Nullable List<SitesWithClicks> sitesWithClicks) {
if (sitesWithClicks!= null && sitesWithClicks.size()>0){
int reArrSite = prefSingleton.getStorage().getInt(Constants.STORAGE_REARRANGESITE_NAV,
Constants.SORTING_PRIORITY);
sitesWithClicks = Utility.sortSitesData(reArrSite, sitesWithClicks);
navAdapter = new ListRecViewAdapter(EnumVal.DialogType.NAVBAR_ITEMS,
sitesWithClicks, WebsiteView.this);
navRecView.setAdapter(navAdapter);
}
}
});
}
Open-fragment method:
public void openFragment(String url, EnumVal.FragStatus fragStatus, String toOpenTag){
if(navFrame.getVisibility() == View.VISIBLE)
downArrow.performClick();
if(fragStatus == EnumVal.FragStatus.NEW){
String fragTag = getNextFragTag();
WebsiteViewFragment fragment = WebsiteViewFragment.newInstance(url, fragTag);
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
if(fragCounter == 1){
fragmentTransaction.replace(R.id.fragment, fragment, fragTag);
currentFrag = fragTag;
} else {
if(getSupportFragmentManager().findFragmentByTag(currentFrag) != null){
fragmentTransaction.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out);
fragmentTransaction.hide(getSupportFragmentManager().findFragmentByTag(currentFrag));
}
fragmentTransaction.add(R.id.fragment, fragment, fragTag);
currentFrag = fragTag;
}
fragmentTransaction.commit();
fragTags.add(new TabDetail(fragTag,"Tab - 1",null));
} else if (fragStatus == EnumVal.FragStatus.OLD){
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
if(getSupportFragmentManager().findFragmentByTag(currentFrag) != null){
fragmentTransaction.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out);
fragmentTransaction.hide(getSupportFragmentManager().findFragmentByTag(currentFrag));
}
fragmentTransaction.show(getSupportFragmentManager().findFragmentByTag(toOpenTag));
fragmentTransaction.commit();
currentFrag = toOpenTag;
}
}
And Fragment has just Webview in it where webview is loading lot of websettings. But thing is reaching till fragment is taking time ,like user clicks from main activity and after about 0.6 seconds, fragment is opening while activity which has fragment is taking just 0.1 second to open so this time is (maybe) related to attaching fragment or something?
Can anyone please explain me, where am I making mistake?
I had some doubt regarding this:
Is the problem webview (in fragment), which has a bunch of websettings ?
Is attaching fragment to activity-2 taking more time?
Is UI part of activity-2 taking time (like toolbar setup which has 4 buttons) and after that fragment is attaching to it, which is resulting in more time consumption ?
Or it is a normal situation ?
Can someone, please, explain me the way to make it to <0.2 seconds for whole tasks? Thanks in advance.
I am facing a strange problem in my material design app . Some thumbnails are opening and loading details activity as expected , but some are not opening instead there is crash happening . in this video u can see the problem I am facing .
I am attaching the link to my project ZIP file link with this ,My Project
this is the main activity ....
public class MainActivity extends AppCompatActivity implements ReaderAdapter.ReaderOnClickItemHandler {
public final static String READER_DATA = "reader";
public final static String POSITION = "position";
private final static String TAG = MainActivity.class.getSimpleName();
private static final String SAVED_ARRAYLIST = "saved_array_list";
private static final String SAVED_LAYOUT_MANAGER = "layout-manager-state";
private ApiInterface mApiInterface;
private List<Reader> mNetworkDataList;
#BindView(R.id.main_recycler_view)
RecyclerView mRecyclerView;
#BindView(R.id.main_linear_layout)
LinearLayout mErrorLinearLayout;
#BindView(R.id.main_progress_bar)
ProgressBar mProgressBar;
#BindView(R.id.toolbar_main)
Toolbar toolbar;
#BindView(R.id.main_reload_button)
Button mButton;
private ReaderAdapter mReaderAdapter;
private Parcelable onSavedInstanceState = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
if (null != toolbar) {
setSupportActionBar(toolbar);
toolbar.setTitle(getResources().getString(R.string.app_name));
}
mApiInterface = ApiClient.getApiClient().create(ApiInterface.class);
mReaderAdapter = new ReaderAdapter(this, this);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this,
LinearLayoutManager.VERTICAL, false);
mRecyclerView.setAdapter(mReaderAdapter);
mRecyclerView.setLayoutManager(linearLayoutManager);
// getting the data from api using retrofit interface ApiInterface
if (savedInstanceState != null) {
onSavedInstanceState = savedInstanceState.getParcelable(SAVED_LAYOUT_MANAGER);
mNetworkDataList = savedInstanceState.getParcelableArrayList(SAVED_ARRAYLIST);
}
if (null == mNetworkDataList) {
loadData();
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loadData();
}
});
}else {
loadAdapter();
}
}
public void loadData() {
final Call<List<Reader>> listCall = mApiInterface.getAllReaderData();
// now binding the data in the pojo class
listCall.enqueue(new Callback<List<Reader>>() {
//if data is successfully binded from json to the pojo class onResponse is called
#Override
public void onResponse(Call<List<Reader>> call,
Response<List<Reader>> response) {
Log.d(TAG, "Response : " + response.code());
mNetworkDataList = response.body();
loadAdapter();
}
//if data binding is not successful onFailed called
#Override
public void onFailure(Call<List<Reader>> call, Throwable t) {
//cancelling the GET data request
listCall.cancel();
showError();
}
});
}
private void loadAdapter() {
if (null != mNetworkDataList) {
showReaderList();
mReaderAdapter.ifDataChanged(mNetworkDataList);
if (onSavedInstanceState != null) {
mRecyclerView.getLayoutManager().onRestoreInstanceState(onSavedInstanceState);
}
}
}
/**
* this method is for showing the error textview and making all other views gone
*/
private void showError() {
mRecyclerView.setVisibility(View.GONE);
mProgressBar.setVisibility(View.GONE);
mErrorLinearLayout.setVisibility(View.VISIBLE);
}
/**
* this method is for showing the recyclerview and making all other views gone
*/
private void showReaderList() {
mRecyclerView.setVisibility(View.VISIBLE);
mProgressBar.setVisibility(View.GONE);
mErrorLinearLayout.setVisibility(View.GONE);
}
private int numberOfColumns() {
DisplayMetrics displayMetrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
// You can change this divider to adjust the size of the poster
int widthDivider = 400;
int width = displayMetrics.widthPixels;
int nColumns = width / widthDivider;
if (nColumns < 2) return 2;
return nColumns;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable(SAVED_LAYOUT_MANAGER, mRecyclerView.getLayoutManager()
.onSaveInstanceState());
if (mNetworkDataList != null)
outState.putParcelableArrayList(SAVED_ARRAYLIST, new ArrayList<Parcelable>(mNetworkDataList));
}
#Override
public void onClickItem(int position, Reader reader, ImageView mImage, TextView mTitle) {
// Check if we're running on Android 5.0 or higher
Intent readerIntent = new Intent(this, ReaderDetailsActivity.class);
Bundle mBundle = new Bundle();
mBundle.putParcelable(READER_DATA, reader);
mBundle.putInt(POSITION, position);
readerIntent.putExtras(mBundle);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// Apply activity transition
ActivityOptionsCompat activityOptions = ActivityOptionsCompat.makeSceneTransitionAnimation(
this,
// Now we provide a list of Pair items which contain the view we can transitioning
// from, and the name of the view it is transitioning to, in the launched activity
new Pair<View, String>(mImage,
ReaderDetailsActivity.VIEW_NAME_HEADER_IMAGE),
new Pair<View, String>(mTitle,
ReaderDetailsActivity.VIEW_NAME_HEADER_TITLE));
ActivityCompat.startActivity(this, readerIntent, activityOptions.toBundle());
} else {
// Swap without transition
startActivity(readerIntent);
}
}
}
this is details activity ......
public class ReaderDetailsActivity extends AppCompatActivity {
private static final String TAG = ReaderDetailsActivity.class.getSimpleName();
private static final String SAVED_ARRAYLIST = "saved_array_list";
private static final String SAVED_LAYOUT_MANAGER = "layout-manager-state";
private final static String ARTICLE_SCROLL_POSITION = "article_scroll_position";
// View name of the header image. Used for activity scene transitions
public static final String VIEW_NAME_HEADER_IMAGE = "detail:header:image";
// View name of the header title. Used for activity scene transitions
public static final String VIEW_NAME_HEADER_TITLE = "detail:header:title";
private int position;
private Reader reader;
private int[] scrollPosition = null;
#BindView(R.id.scrollView_details)
ScrollView mScrollView;
#BindView(R.id.details_fragment_title)
TextView mTitle;
#BindView(R.id.imageView_details)
ImageView mImageView;
#BindView(R.id.textView_author_details)
TextView mAuthor;
#BindView(R.id.textView_published_date)
TextView mPublishDate;
#BindView(R.id.textView_description)
TextView mDescription;
#BindView(R.id.floatingActionButton_Up)
FloatingActionButton mFloatingActionButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reader_details);
ButterKnife.bind(this);
Bundle bundle = getIntent().getExtras();
position=0;
mFloatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mScrollView.scrollTo(0,0);
}
});
ViewCompat.setTransitionName(mImageView, VIEW_NAME_HEADER_IMAGE);
ViewCompat.setTransitionName(mTitle, VIEW_NAME_HEADER_TITLE);
if (null != bundle) {
position = bundle.getInt(MainActivity.POSITION);
reader = bundle.getParcelable(MainActivity.READER_DATA);
if(null != reader) {
mTitle.setText(reader.getTitle());
mPublishDate.setText(reader.getPublishedDate());
mAuthor.setText(reader.getAuthor());
GlideApp.with(this)
.load(reader.getPhoto())
.into(mImageView);
mDescription.setText(reader.getBody());
}
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
scrollPosition = savedInstanceState.getIntArray(ARTICLE_SCROLL_POSITION);
if (scrollPosition != null) {
mScrollView.postDelayed(new Runnable() {
public void run() {
mScrollView.scrollTo(scrollPosition[0], scrollPosition[0]);
}
}, 0);
}
}
}
Json link I am parsing for this project .
Here is a screen recording of my project where u can see the problem I am facing , recording
this is a console log when I am trying to debug ....
when it is working fine the console log is 08/09 20:31:31: Launching app
No apk changes detected since last installation, skipping installation of /home/soumyajit/AndroidStudioProjects/MaterialReader/app/build/outputs/apk/debug/app-debug.apk
$ adb shell am force-stop lordsomen.android.com.materialreader
$ adb shell am start -n "lordsomen.android.com.materialreader/lordsomen.android.com.materialreader.activities.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER -D
Connecting to lordsomen.android.com.materialreader
Connected to the target VM, address: 'localhost:8601', transport: 'socket'
and when it is crashing the console log is
08/09 20:31:31: Launching app
No apk changes detected since last installation, skipping installation of /home/soumyajit/AndroidStudioProjects/MaterialReader/app/build/outputs/apk/debug/app-debug.apk
$ adb shell am force-stop lordsomen.android.com.materialreader
$ adb shell am start -n "lordsomen.android.com.materialreader/lordsomen.android.com.materialreader.activities.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER -D
Connecting to lordsomen.android.com.materialreader
Connected to the target VM, address: 'localhost:8601', transport: 'socket'
Disconnected from the target VM, address: 'localhost:8601', transport: 'socket'
thanks in advance ..
Maximum Parcelable size should not be exceed 1mb. In you app it is 2.1 Mb. Without passing app date to the next activity you can try to pass item id and load data in next activity. Otherwise you can cache the list data and you can load the data from the local database in the details activity. If you cannot see crash log in android studio it because it set as "show only selected activity". In this case app get close and then this type of logs doesnot show in the android studio. switch that to No Filter and you can see the all logs.