Skip to content Skip to sidebar Skip to footer

Android Edittext Memory Leak

Alot of people are noticing EditText in an activity is holding a Strong Reference to an Activity even once its finished. To be clear this EditText is inside a layout and inflated,

Solution 1:

It is because EditText references the context of Activity. When the Activity is destroyed, Activity cannot be recycled normally because Edittext holds a reference to the context of activity. Answer : Rewrite EditText, change the reference to the Context in Activity to the reference to ApplicationContext.

Instructions:

https://programming.vip/docs/solve-the-memory-leak-problem-caused-by-edittext-in-android.html

Solution 2:

I was confused about this memory leak for a very long time. But recently I found two ways to fix this problem.

  1. I found that if your TextView/EditText has the android:hint property, this cannot happen. So the easiest way is give every TextView/EditText the hint property.

  2. The most forceful way is to reflect over TextLine and find the ChangeWatcher listener, then kill this listener.

Solution 3:

I solved the problem by changing the activity context to application context.

Solution 4:

Try to use Application Context instead of Activity Context in onCreateView() for this particular View (which contain any android:textIsSelectable="true" components).

// SingletonclassMyApplicationextendsApplication {
    privatestatic MyApplication mApp;

    @OverridepublicvoidonCreate() {
        mApp = this;
    }

    publicstatic MyApplication getApp() {
        return mApp;
    }
}

@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Suggested inflater use Activity Context// So we must tu use Application ContextContextcontext= MyApplication.getApp().getApplicationContext();
    LayoutInflatermyLayoutInflater= LayoutInflater.from(context);

    Viewview= myLayoutInflater.inflate(R.layout.my_view, container, false);
    return view;
}

Post a Comment for "Android Edittext Memory Leak"