How to recreate/Restart application when Android app language is changed?

382 Views Asked by At

I have created an application which asks for user preferred language in the Loginfragment .I need to kill and restart the app after setting the language. I tried using recreate but it results in the following error

android.view.WindowLeaked: Activity xxx.presentation.activity.MainActivity has leaked window DecorView@aea6bb8[MainActivity] that was originally added here

My LoginFragment looks like below :

public class LoginFragment extends Fragment implements View.OnClickListener,LoginView{

//Some code

private void setListeners(View view) {

//Some code
view.findViewById(R.id.change_lang_btn).setOnClickListener(this);
    }

@Override
    public void onClick(View v){
        switch(v.getId()){
            case R.id.change_lang_btn:
                Log.v("LOGIN","Change Language button clicked");
                GeneralUtils.setupAppLanguageDialog(getActivity());
                getActivity().recreate();  //Creates memory leak
                break;
        }
    }

My GeneralUtils class which contains the language change dialog looks like :

public class GeneralUtils {

//Some code

public static void setupAppLanguageDialog(Context context)
    {
        AlertDialog langChangeDialog;
        CharSequence[] changeLangList = {"English", "हिन्दी"};
        AlertDialog.Builder mBuilder = new AlertDialog.Builder(context);
        mBuilder.setTitle("Choose language");
        mBuilder.setSingleChoiceItems(changeLangList, -1, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                if (i==0)
                {
                    DataRepository.setLocale("en", ((ContextWrapper)context).getBaseContext());

                }
                else
                {
                    DataRepository.setLocale("hi",((ContextWrapper)context).getBaseContext());
                }
                dialogInterface.dismiss();
                Toast.makeText(context, context.getString(R.string.Language_change_done),Toast.LENGTH_LONG).show();
            }
        });
        langChangeDialog =mBuilder.create();
        langChangeDialog.show();
}
    }

The SetLocale function does necessary configuration and shared preferences update to change the language. How should I deal with the memory leak issue here if I recreate the application ? What is the cause ? Is there a better approach? Any suggestion to build/improve functionality is welcome.

Edit : I checked a related answer for memory leaks but I need to understand how to use it in my scenario.

0

There are 0 best solutions below