惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Threat Research - Cisco Blogs
C
CERT Recently Published Vulnerability Notes
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
S
Securelist
K
Kaspersky official blog
V
Vulnerabilities – Threatpost
C
Cisco Blogs
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Hacker News: Ask HN
Hacker News: Ask HN
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
S
Security Affairs
Forbes - Security
Forbes - Security
Spread Privacy
Spread Privacy
C
CXSECURITY Database RSS Feed - CXSecurity.com
P
Palo Alto Networks Blog
H
Hacker News: Front Page
L
Lohrmann on Cybersecurity
Cloudbric
Cloudbric
S
Schneier on Security
Simon Willison's Weblog
Simon Willison's Weblog
I
InfoQ
人人都是产品经理
人人都是产品经理
PCI Perspectives
PCI Perspectives
月光博客
月光博客
爱范儿
爱范儿
Jina AI
Jina AI
WordPress大学
WordPress大学
N
News and Events Feed by Topic
Cyberwarzone
Cyberwarzone
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
小众软件
小众软件
Google Online Security Blog
Google Online Security Blog
W
WeLiveSecurity
V
V2EX
阮一峰的网络日志
阮一峰的网络日志
美团技术团队
博客园 - 司徒正美
Scott Helme
Scott Helme
AI
AI
L
LangChain Blog
A
Arctic Wolf
博客园 - 【当耐特】
量子位
S
SegmentFault 最新的问题
The GitHub Blog
The GitHub Blog
MyScale Blog
MyScale Blog
腾讯CDC
博客园 - 叶小钗
Last Week in AI
Last Week in AI
S
Secure Thoughts

ashishb.net

A day in Luxembourg - the richest country in the world I was asked to install malware during a fake interview Book summary: Breakneck - China's quest to engineer the future by Dan Wang Book summary: How to Teach Your Baby to Read Book Summary: The Discontented Little Baby Book by Pamela Douglas Introducing Amazing Sandbox - run third-party tools and AI agents securely on your machine Why software outsourcing gets a bad reputation? Book summary: The Natural Baby Sleep Solution by Polly Moore A day in Antwerp, Belgium Journey of online influencers Two days in Brussels, Belgium Shortcuts - when we love them and when we don't A visit to Rakhigarhi Three days in overhyped Paris Empty Japan, crowded Tokyo The real lock-in in GitHub is not the code, but the stars 11-day Norwegian Breakaway East Caribbean cruise Sanskrit and Sri Lankan Air Force Use REST with Open API The Achilles heel of American capitalism Costa Rica in 4 days At a juice stall in Sri Lanka A short stay at Warsaw, Poland Best practices for using Python & uv inside Docker Two days in Vilnius, Lithuania How IntelliJ IDEs waste disk space Pregnancy Why there aren't many digital nomads from India Two days in Riga, Latvia To keep your machine secure, run third-party tools inside Docker Family Ties in Your DNA: Some relatives are closer than others Doctors per capita Two days in Tallinn, Estonia Ship tools as standalone static binaries Made in America Two days in Helsinki, Finland Maintaining an Android app is a lot of work The land of good deals Two days in Oslo, Norway FastAPI vs Flask performance comparison Google Search is losing to Perplexity Two days in Dublin, Ireland Continuous integration ≠ Continuous delivery World's simplest project success heuristic London in 5 days It is hard to recommend Python in production Inflation, IRS, Credit cards, and Vendors Temu and the Chinese approach Things to do in Miami Florida Revenue vs Cost Axis Language learning as an adult The unanchored babies of the green card limbo Price variance in the United States A day in Louisville, Kentucky A surprisingly positive experience with Air India Unhospitable Airports Android: Don't use stale views USA = Union of Sales and Advertisement A day in Nashville, Tennessee Minimize Javascript in your codebase A day in Birmingham, Alabama In defense of ad-supported products Real vs artificial world The science behind Punjabi singers Hiking Mt. Fuji The Indian startup bubble is insane Repairing database on the fly for millions of users Book Summary: One up on Wall Street by Peter Lynch It is hard to recommend Google Cloud At the Prague airport Kyoto in three days Migrating from WordPress to Hugo Book summary: Sick Societies by Robert B. Edgerton Statistical outcomes require statistical games Illegal immigrants to Europe via Cairo Tokyo in three days Mobs are Status Games Writing Script matters as much as the spoken language Sri Lanka in 5 days LLMs: great for business but bad business Book Summary: Safe Haven by Mark Spitznagel Mac shortcut for typing Avagraha symbol On a bus with an asylum seeker Nicaragua in 5 days When to commit Generated code to version control Why I always buy a local SIM in a foreign country Use Makefile for Android Four days in Guadalajara, Mexico Android Navigation: Up vs Back Hotels vs Airbnb vs Hostels Currency issues in Argentina Abstractions should be deep not wide Some data on podcasting Always support compressed response in an API service A day in El Calafate - Patagonia, Argentina Hermetic docker images with Hugging Face machine learning models American Elections The sound of "ch" API services should always have usage Limits Hiking in El Chaltén - trekking capital of Argentina
Android: Fragment related pitfalls and how to avoid them
Ashish Bhatia · 2019-02-10 · via ashishb.net
  1. Don’t use platform fragments (android.app.Fragment), they have been deprecated and can trigger version-specific bugs. Use the support library fragments ( android.support.v4.app.Fragment) instead.

  2. A Fragment is created explicitly via your code or recreated implicitly by the FragmentManager. The FragmentManager can only recreate a Fragment if it’s a public non-anonymous class. To test for this, rotate your screen while the Fragment is visible.

  3. FragmentTransaction#commit can fail if the activity has been destroyed. “java.lang.IllegalStateException: Activity has been destroyed” Why - This can happen in the wild where say right before FragmentTransaction#commit() executes, the user gets a phone call and your activity is backgrounded and destroyed. How to trigger manually - The easy way to manually test this is to add a call to Activity#finish() right before FragmentTransaction#commit. Fix - Before doing FragmentTransaction#commit(), check that the activity has not been destroyed - Activity#isDestroyed() should return false.

  4. FragmentTransaction#commit can fail if onSaveInstanceState has been called. “java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState” Why - This can happen in the wild where say right before FragmentTransaction#commit() executes, the user gets a phone call and your activity is backgrounded and paused. How to trigger manually - The easiest way to manually trigger this behavior is to call Activity#onSaveInstanceState in your uncommitted code right before the call to FragmentTransaction#commit Fix 1 - call FragmentTransaction#commitAllowingStateLoss but that implies that your fragment would be in a different state then the user expects it to be. Fix 2 - The better way is to ensure that the code path L which leads to FragmentTransaction#commit is not invoked once Activity’s onSaveInstanceState has been called but that’s not always easy to do.

  5. FragmentManager is null after Activity is destroyed. “java.lang.NullPointerException: … at getSupportFragmentManager().beginTransaction()” Why - This can happen when the activity has been destroyed before getSupportFragmentManager() is invoked. The common cause of this is when a new fragment has to be added in response to a user action and the user immediately backgrounds the app, again, say due to a phone call, after clicking the button before getSupportFragmentManager() is invoked. Another common case is where an AsyncTask which will call getSupportFragmentManager() in onPostExecute and while the task is engaged in the background processing (doInBackground), the activity is destroyed. How to trigger manually - call `Activity#finish()` before `getSupportFragmentManager().beginTransaction()` Fix- If getSupportFragmentManager() is being invoked in the Activity, check if it’s null. If it is being invoked inside a Fragment check if isAdded() of the Fragment returns true before calling this.

  6. Avoid UI modifications that are not related to a FragmentTransaction with FragmentTransaction committed using commitAllowStateLoss Why - Any UI modifications like modifications of the text in a TextView are synchronous while the execution of a FragmentTransaction via `FragmentTransaction#commitAllowStateLoss()` is asynchronous. If the activity’s onSaveInstanceState is invoked after the UI changes have been made but before commitAllowStateLoss is called then the user can end up seeing a UI state which you never expected them to see. Fix - use commitNow() or hook into FragmentManager.FragmentLifecycleCallbacks#onFragmentAttached(). I will admit this I haven’t found a simpler fix for this. And this issue is definitely an edge case.

  7. Saving Fragment State As mentioned earlier, a Fragment is re-created on activity recreation by FragmentManager which will invoke its default no-parameter constructor. If you have no such constructor then on Fragment recreation, the app will crash with “java.lang.InstantiationException: MyFragment has no zero-argument constructor”. If you try to fix this by adding a no-argument constructor then the app will not crash but on activity recreation say due to screen rotation, the Fragment will lose its state. The right way to serialize a Fragment’s state is to pass arguments in a Bundle via setArguments.

    1
    2
    3
    
    MyFragment myFragment = new MyFragment();
    myFragment.setArguments(mBundle);
    return myFragment;

    The Fragment code should then use the getArguments() method to fetch the arguments. In fact, I would recommend a Builder pattern to hide all this complexity.

    Consider this complete example,

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    
    public class MyFragment {
    
        private static final String KEY_NAME = "name";
    
        public static class MyFragment.Builder {
           private final Bundle mBundle = new Bundle();
    
           public Builder setName(String username) {
               mBundle.putInt(KEY_NAME, clickCount);
               return this;
           }
    
           public MyFragment build() {
              MyFragment myFragment = new MyFragment();
              // Set the username
              myFragment.setArguments(mBundle);
              return myFragment;
           }
        }
    
        public MyFragment() {
          // Get the user name
          @Nullable String username = getArguments() != null ? getArguments().getString(KEY_NAME, null) : null;
        }
      }
    
      if (!isDestroyed()) {
         // Create the Fragment
        MyFragment myFragment = new MyFragment().Builder().setName(username).build();
        // Add the Fragment
        FragmentTransaction ft = getSupportFragmentManager().beingTransaction();
        ft.add(myFragment);
        ft.commitNowAllowingStateLoss();
      }
  8. Inside your Fragment code, if you want to decide whether it is safe to execute a UI code or not, rely on isAdded(), if it returns true, it is safe to perform UI modifications, if it returns false, then your Fragment has been detached from the activity either because it has been removed or because the host (Fragment/Activity) is being destroyed.

  9. Callbacks To callback into the parent activity/fragment in case of action inside your Fragment, say, a user clicks, provide an interface (say, MyFragmentListener) which the holding activity/Fragment should implement. In Fragment#onCreateView() get the host via getHost(), cast it to MyFragmentListener, and store it in the instance variable of your Fragment class. Set that instance variable to null in Fragment#onDestroyView(). Now, you can invoke callbacks on this MyFragmentListener instance variable.

  10. Backstack Backstack is nuanced and my grasp of it is still limited. What I do understand is that if you want your Fragment to react to the back key press then you should call FragmentTransaction#addToBackStack(backStackStateName) while adding the Fragment via FragmentTransaction and remove it while removing it. Removal from the back stack is a bit more nuanced. Note that, manual removal of a fragment from the back stack is not required in Activity#onBackPressed() as long as your Activity inherits from FragmentActivity.

    1
    2
    3
    4
    5
    6
    
    SupportFragmentManager manager = getSupportFragmentManager();
      FragmentManager.BackStackEntry entry = manager.getBackStackEntryAt(manager.getBackStackEntryCount() - 1);
      if (backStackStateName.equals(entry.getName())) {
         manager.popBackStack(backStackStateName, FragmentManager.POP_BACK_STACK_INCLUSIVE);
      }
    }