I create an application with MVVM concept, there is fragment for viewpager in my Activity. some data changed when I change my language in my application, but the data that showed by webservices is not change. so I try to add android:configChanges="locale" in my every Activity and I already add this code on my Activity class :
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
recreate();
}
}
But its make my UI recreate every configuration change, including Screen Rotation while I just want to recreate if Language is changed.
this is my fragment code :
public class CatalogueFragment extends BaseFragment<FragmentCatalogueBinding, CatalogueViewModel>
implements CatalogueNavigator, CatalogueAdapter.CatalogueAdapterListener {
#Inject
CatalogueAdapter adapter;
#Inject
LinearLayoutManager mLayoutManager;
#Inject
ViewModelProvider.Factory factory;
FragmentCatalogueBinding fragmentCatalogueBinding;
private CatalogueViewModel catalogueViewModel;
public static CatalogueFragment newInstance(int Pos) {
Bundle args = new Bundle();
CatalogueFragment fragment = new CatalogueFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public int getBindingVariable() {
return BR.viewModel;
}
#Override
public int getLayoutId() {
return R.layout.fragment_catalogue;
}
#Override
public CatalogueViewModel getViewModel() {
catalogueViewModel = ViewModelProviders.of(this, factory).get(CatalogueViewModel.class);
return catalogueViewModel;
}
#Override
public void handleError(String error) {
// handle error
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
catalogueViewModel.setNavigator(this);
adapter.setListener(this);
}
#Override
public void onRetryClick() {
catalogueViewModel.fetchData();
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
fragmentCatalogueBinding = getViewDataBinding();
setUp();
}
#Override
public void updateData(List<Movie> movieList) {
adapter.addItems(movieList);
}
private void setUp() {
mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
fragmentCatalogueBinding.recyclerCatalogue.setLayoutManager(mLayoutManager);
fragmentCatalogueBinding.recyclerCatalogue.setItemAnimator(new DefaultItemAnimator());
fragmentCatalogueBinding.recyclerCatalogue.setAdapter(adapter);
}
}
and this is my ViewModel class
public class CatalogueViewModel extends BaseViewModel {
private final MutableLiveData<List<Movie>> movieListLiveData;
public CatalogueViewModel(DataManager dataManager, SchedulerProvider schedulerProvider) {
super(dataManager, schedulerProvider);
movieListLiveData = new MutableLiveData<>();
fetchData();
}
public void fetchData() {
setIsLoading(true);
getCompositeDisposable().add(getDataManager()
.getApiHelper().doMovieCall(URLConfig.API_KEY, getDataManager().getLanguage())
.subscribeOn(getSchedulerProvider().io())
.observeOn(getSchedulerProvider().ui())
.subscribe(movieResponse -> {
if (movieResponse != null && movieResponse.getResults() != null) {
movieListLiveData.setValue(movieResponse.getResults());
}
setIsLoading(false);
}, throwable -> {
setIsLoading(false);
// getNavigator().handleError(throwable);
}));
}
public LiveData<List<Movie>> getMovieListLiveData() {
return movieListLiveData;
}
}
Can anybody show me where is my wrong? Thank you very much
You can use: ACTION_LOCALE_CHANGED
Here an example:
private BroadcastReceiver mLangReceiver = null;
protected BroadcastReceiver setupLangReceiver(){
if(mLangReceiver == null) {
mLangReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// do what you want
}
};
registerReceiver(mLangReceiver, new IntentFilter(Intent.ACTION_LOCALE_CHANGED));
}
return mLangReceiver;
}
Related
I want to send a String from service to fragment with EventBus.
Here is the global EventBus :
public class Singleton {
private static EventBus eBus;
public static EventBus getEventBus() {
if (eBus == null)
eBus = EventBus.getDefault();
return eBus;
}
}
Here is the model class which I put String here :
public class Model {
public String mystring;
public void setMystring(String mystring) {
this.mystring = mystring;
}
public String getMystring() {
return mystring;
}
}
Here I send my String with EventBus from service :
public class Sample_Service extends Service {
Model model;
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
model = new Model();
String action = intent.getAction();
if(action!=null) {
switch (action) {
case "send":
model.setName("Hello");
Singleton.getEventBus().postSticky(model);
break;
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
Inside subscribe method I receive the String correctly.
The problem is that outside this method my String is null.
In this fragment I receive the String :
public class Sample_Fragment extends Fragment {
public String mystring;
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
service_intent.setAction("send");
ContextCompat.startForegroundService(context,service_intent);
// Here String is null when I want to show it on toast.
Toast.makeText(context,mystring,Toast.LENGTH_SHORT).show();
}
#Override
public void onStart() {
super.onStart();
//registering EventBus
Singleton.getEventBus().register(this);
}
#Override
public void onDestroyView() {
super.onDestroyView();
Singleton.getEventBus().unregister(this);
}
#Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
public void Get_Data (Model model) {
Model stickyEvent = EventBus.getDefault().getStickyEvent(Model.class);
mystring=model.get;
// Here I receive data successfully
Singleton.getEventBus().removeStickyEvent(stickyEvent);
}
}
What is a problem?
I have a working AsyncTask to get data from a server and display it in a TextView. But is it possible to output the data into a TextView which is located in a fragment? So let's say, the AsyncTask is loaded in the MainActivity and the output will be in a fragment.
This is my AsyncTask:
private static class FtpDownload extends AsyncTask<String, String, String> {
private WeakReference<GuidanceActivity> activityWeakReference;
FtpDownload(GuidanceActivity activity) {
activityWeakReference = new WeakReference<>(activity);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... FTPconnection) {
GuidanceActivity activity = activityWeakReference.get();
if (activity == null || activity.isFinishing()) {
return null;
}
try {
FTPClient ftpClient = new FTPClient();
ftpClient.connect("", 21);
System.out.println(ftpClient.getReplyString());
ftpClient.enterLocalPassiveMode();
ftpClient.login("anonymous", "");
ftpClient.changeWorkingDirectory("/");
InputStream inStream = ftpClient.retrieveFileStream(".html");
activity.contents = IOUtils.toString(inStream, StandardCharsets.UTF_8);
System.out.println(activity.contents);
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String output) {
GuidanceActivity activity = activityWeakReference.get();
if (activity == null || activity.isFinishing()) {
return;
}
TextView textView = activity.findViewById(R.id.text_view);
textView.setText(Html.fromHtml(activity.contents));
}
}
In your fragment:
public class MyFragment extends Fragment {
TextView myTextView;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = View root = inflater.inflate(R.layout.my_frag_layout, null);
myTextView = (TextView) view.findViewById(R.id.myTextView);
//rest of your implementation of onCreateView
return view;
}
//this will be called from activity
public void updateTextView(String text) {
myTextView.setText(text);
}
}
in your activity:
public class MyActivity extends AppCompatActivity {
private final String FRAGMENT_TAG = "myFragment";
private static class FtpDownload extends AsyncTask<String, String, String> {
//rest of your FtpDownload class
#Override
protected void onPostExecute(String output) {
GuidanceActivity activity = activityWeakReference.get();
if (activity == null || activity.isFinishing()) {
return;
}
MyFragment fragment = (MyFragment) getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG );
/* or
MyFragment fragment = (MyFragment) getSupportFragmentManager().findFragmentById(R.id.fragment );
if your fragment is in an xml layout */
fragment.updateTextView(Html.fromHtml(activity.contents));
}
}
}
Yes, it is possible. This is a sample for WiFi scanning from MainActivity and the results are show at fragment. I believe you can understand the logic and convert it for your project
MainActivity:
public class MainActivity extends AppCompatActivity implements FragmentDiscoverWiFi.ScanWiFi;
//public variable
FragmentDiscoverWiFi fragmentDiscoverWiFi;
//This will be called from your fragment
#Override
public void onScanWiFi(FragmentDiscoverWiFi fragment) {
fragmentDiscoverWiFi = fragment;
}
//use something like this when your want to update fragment
fragmentDiscoverWiFi.onScanWiFiComplete();
Fragment:
public class FragmentDiscoverWiFi extends Fragment {
private Context mContext;
public interface ScanWiFi {
public void onScanWiFi(FragmentDiscoverWiFi fragment);
}
public FragmentDiscoverWiFi() {
// Required empty public constructor
}
#Override
public void onAttach(Context context) {
mContext = context;
super.onAttach(context);
}
public void onScanWiFiComplete() {
if (!isDetached()) {
//Access your data from MainActivity like this:
Log.d(TAG, "Total APs:" + ((MainActivity) mContext).wifiScanResults.size());
}
}
#Override
public void onResume() {
super.onResume();
if (!getUserVisibleHint()) {
return;
}
pullToRefreshText = rootView.findViewById(R.id.pullToRefreshText);
pullToRefresh = rootView.findViewById(R.id.pullToRefresh);
pullToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
Log.d(TAG, "refreshing...");
pullToRefresh.setRefreshing(true);
((MainActivity)mContext).onScanWiFi(FragmentDiscoverWiFi.this);
}
});
}
}
I'm trying using ReferenceQueue to check Activity if the activity is destory,Whether this activity is recycled.
I just using intent to Main2Activity.class:
switch (v.getId()){
case R.id.btn_turn_two:
Intent intent=new Intent(MainActivity.this,Main2Activity.class);
startActivity(intent);
break;
default:
break;
}
when I press to return MainActivity.class, the Main2Acitivity.class will be destroyed, so I using registerActivityLifecycleCallbacks watch activity in application,
public class MainApplication extends Application{
private watche watche;
#Override
public void onCreate() {
super.onCreate();
watche=new watche(this,getApplicationContext());
}
this class is check the Activity is destoryed.
public class watche {
KeyRefrence ref;
private Context context;
private final Set<String> retainedKeys = new CopyOnWriteArraySet<>();
private final ReferenceQueue<Object> referenceQueue=new ReferenceQueue<>();
public watche(Application application, Context context){
application.registerActivityLifecycleCallbacks(lifecycleCallbacks);
this.context=context;
}
Application.ActivityLifecycleCallbacks lifecycleCallbacks=new Application.ActivityLifecycleCallbacks() {
#Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
#Override
public void onActivityStarted(Activity activity) {
}
#Override
public void onActivityResumed(Activity activity) {
}
#Override
public void onActivityPaused(Activity activity) {
}
#Override
public void onActivityStopped(Activity activity) {
}
#Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
#Override
public void onActivityDestroyed(Activity activity) {
//weakrefrence to this activity
String key = UUID.randomUUID().toString();
retainedKeys.add(key);
final KeyRefrence weakReference=new KeyRefrence(activity,key,activity.getPackageName(),referenceQueue);
final MyAyTask myAyTask=new MyAyTask(weakReference,activity,context);
myAyTask.doInBackground(null);
}
};
public class MyAyTask extends AsyncTask {
private Activity activity;
private KeyRefrence keyRefrence;
private Context context;
public MyAyTask(KeyRefrence keyRefrence, Activity activity,Context context){
this.activity=activity;
this.context=context;
this.keyRefrence=keyRefrence;
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
}
#Override
protected Object doInBackground(Object[] objects) {
gc();
ref=(KeyRefrence)referenceQueue.poll();
if (ref==null){
Log.d(TAG, "onActivityDestroyed:Acitivty is not destory");
}
else if (ref!=null){
Log.d(TAG, "doInBackground: "+ref);
}
return null;
}
}
I have create KeyReference implement WeakReference,and I didn't do anything in Main2Activity.class, I just press the phone return,I check the gc,is working ,but the referencequeue always empty, I'm sure the Activity is destoryed.
Good day, I have a fragment called MainFragment called from MainActivity. Inside MainFragment I have private OnProgressUpdateListener progressListener; this interface instance helps me talk to ProgressDialog Fragment.
I'm able to initialize interface instance inside my activities but I'm getting ClassCastException when I attempt to initialize the interface instance inside MainFragment
Below are my classes:
--------------------------------------------------------------------------------
Interface
--------------------------------------------------------------------------------
public interface OnProgressUpdateListener
{
void onProgressUpdate(String message);
void onDismissDialog();
}
--------------------------------------------------------------------------------
Child Fragment to MainFragment
--------------------------------------------------------------------------------
public class ProgressbarDialog extends DialogFragment implements OnProgressUpdateListener
{
TextView progressMessage;
ProgressBar progressBar;
View dialogView;
LayoutInflater inflater;
AlertDialog alertDialog;
AlertDialog.Builder dialogBuilder;
public ProgressbarDialog()
{
}
public static ProgressbarDialog newInstance(String title, String message)
{
ProgressbarDialog fragment = new ProgressbarDialog();
Bundle args = new Bundle();
args.putCharSequence("title", title);
args.putCharSequence("message", message);
fragment.setArguments(args);
return fragment;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
dialogBuilder = new AlertDialog.Builder(getActivity());
inflater = getActivity().getLayoutInflater();
dialogView = inflater.inflate(R.layout.content_progressdialog,null);
dialogBuilder.setView(dialogView);
progressBar = dialogView.findViewById(R.id.pbProgressSpinner);
progressMessage = dialogView.findViewById(R.id.tvProgressMessage);
dialogBuilder.setTitle(getArguments().getString("title"));
progressBar.setIndeterminate(true);
progressMessage.setText(getArguments().getString("message"));
alertDialog = dialogBuilder.create();
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.show();
return alertDialog;
}
#Override
public void onProgressUpdate(String message)
{
progressMessage.setText(message);
}
#Override
public void onDismissDialog()
{
alertDialog.dismiss();
}
}
--------------------------------------------------------------------------------
MainFragment - Parent Fragment To ProgressbarDialog
--------------------------------------------------------------------------------
public class MainFragment extends Fragment
{
private View mainView;
private CheckBox rememberMe;
private boolean stayLoggedIn;
private CountDownLatch latch;
private FragmentManager manager;
private OnMainListener mListener;
private EditText email, password;
private ProgressbarDialog progressDialog;
private OnProgressUpdateListener progressListener;
private final int REGISTER_CODE = 1, RESET_CODE = 2;
private FloatingActionButton fabRegister, fabLogin, fabReset;
public MainFragment()
{}
public static MainFragment newInstance()
{
MainFragment fragment = new MainFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
if (getArguments() != null)
{}
manager = getChildFragmentManager();
progressDialog = ProgressbarDialog.newInstance("Authentication", "Connecting To Server, Please Wait...");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
// Inflate the layout for this fragment
mainView = inflater.inflate(R.layout.main_fragment, container, false);
stayLoggedIn = false;
rememberMe = mainView.findViewById(R.id.cbRememberMe);
email = mainView.findViewById(R.id.edtLoginEmail);
password = mainView.findViewById(R.id.edtLoginPassword);
fabRegister = mainView.findViewById(R.id.fabRegister);
fabLogin = mainView.findViewById(R.id.fabLogin);
fabReset = mainView.findViewById(R.id.fabReset);
return mainView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
email.setTag("Account Email Required!");
password.setTag("Account Password Required!");
}
#Override
public void onStart()
{
super.onStart();
rememberMe.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
stayLoggedIn = b;
}
});
fabRegister.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
mListener.onFABInteraction(REGISTER_CODE);
}
});
fabLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
onLoginRequest();
}
});
fabReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
mListener.onFABInteraction(RESET_CODE);
}
});
}
#Override
public void onAttach(Context context)
{
super.onAttach(context);
try
{
if (context instanceof OnMainListener)
{
mListener = (OnMainListener) context;
}
else
{
throw new RuntimeException(context.toString()
+ " must implement OnMainListener");
}
}
catch (Exception e)
{
Log.e(MainFragment.class.getName(), e.getMessage());
}
}
**#Override
public void onAttachFragment(Fragment childFragment) {
super.onAttachFragment(childFragment);
if(childFragment instanceof OnProgressUpdateListener)
{
progressListener = (OnProgressUpdateListener) childFragment;
//This code is never executed
}
}**
#Override
public void onDetach()
{
super.onDetach();
mListener = null;
}
interface OnMainListener
{
void onLoginSuccess(BackendlessUser user);
void onFABInteraction(int option);
}
private class OnAuthentication extends AsyncTask<String, String, BackendlessUser>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
latch = new CountDownLatch(1);
progressDialog.show(manager, MainFragment.class.getName());
Code Fails here, null pointer exception is thrown because progressListener interface instance is not initialised.
progressListener.onProgressUpdate("Authenticating User, Please Wait...");
}
#Override
protected void onProgressUpdate(String... values)
{
super.onProgressUpdate(values);
progressListener.onProgressUpdate(values[0]);
}
#Override
protected BackendlessUser doInBackground(String... strings)
{
try
{
Backendless.UserService.login(
Utility.getText(email),
Utility.getText(password),
onLoginCallback, stayLoggedIn);
publishProgress("Validating Credentials, Please Wait...");
latch.await();
}
catch (InterruptedException e)
{
publishProgress(e.getMessage());
}
return Utility.loginUser;
}
#Override
protected void onPostExecute(BackendlessUser user)
{
super.onPostExecute(user);
Utility.clearViews(email, password, rememberMe);
progressListener.onDismissDialog();
if(user != null)
{
if(((MainActivity)getActivity()).onRoleValidation(user))
{
mListener.onLoginSuccess(user);
}
else
{
//send a push notification to master channel
Utility.sendNotification(getActivity(),
"New Application User",
"New Registration",
"New User Awaiting Role Assignment", "Master",
"Role Assignment Pending For User :"
+ user.getEmail()
+ ":" + user.getProperty("name").toString()
+ " " + user.getProperty("surname").toString());
}
}
}
}
private void onLoginRequest()
{
if(Utility.hasText(email, password))
{
if(Utility.isEmailValid(Utility.getText(email)))
{
new OnAuthentication().
execute(Utility.getText(email),
Utility.getText(password));
}
else
{
Utility.showToast(getActivity(), "Invalid Email");
Utility.clearViews(email);
}
}
}
private AsyncCallback<BackendlessUser> onLoginCallback = new AsyncCallback<BackendlessUser>()
{
#Override
public void handleResponse(BackendlessUser backendlessUser)
{
latch.countDown();
Utility.loginUser = backendlessUser;
Log.i(MainFragment.class.getName(), "Login Successful!\n" + backendlessUser.getUserId());
}
#Override
public void handleFault(BackendlessFault backendlessFault)
{
latch.countDown();
progressListener.onProgressUpdate("Login Unsuccessful!");
Log.e(MainFragment.class.getName(), "Login Failed!\n" + backendlessFault.getMessage());
}
};
}
Well, the question is something which is similar to already asked questions on the forum but I couldn't find a suitable answer to my problem.My usersettingactivity class-
public class UserSettingActivity extends PreferenceActivity implements View.OnClickListener,
SharedPreferences.OnSharedPreferenceChangeListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PreferenceScreen screen = getPreferenceScreen();
PreferenceCategory langCategory=(PreferenceCategory)findPreference("change_lang");
if(PrefSettings.getInstance().getUserCountry().equalsIgnoreCase("NA"))
screen.removePreference(langCategory);
PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(this);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
ViewGroup root = (ViewGroup) findViewById(android.R.id.content);
LayoutInflater.from(this).inflate(R.layout.user_preference_layout, root, true);
Toolbar toolbar = (Toolbar) root.findViewById(R.id.toolbar);
toolbar.setNavIconClickListener(this);
TextView version = (TextView) root.findViewById(R.id.build_version);
version.setText("v" + BuildConfig.VERSION_NAME);
getFragmentManager().beginTransaction().replace(R.id.fragment, new MyPreferenceFragment()).commit();
}
#Override
public void onClick(View v) {
finish();
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
AppTracker.btnClicked(key);
if ("prefNotification".equals(key)) {
Utils.configureServiceAlarm(this);
}
}
public static class MyPreferenceFragment extends PreferenceFragment {
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
}
#Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
if (preference.getKey().contains("whitelist_paths")) {
startActivity(new Intent(getActivity(), FolderChooserActivity.class));
}
if(preference.getKey().contains("change_language"))
LanguageDialog languageDialog=new LanguageDialog(UserSettingActivity.this); //Here is the problem
languageDialog.langDialogFragment();
return true;
}
}}
My LanguageDialog class-
public class LanguageDialog {
private Activity a = null;
HashMap<String, String> lang;
public LanguageDialog(Activity activity){
a=activity;
}
public void langDialogFragment()
{
lang = new HashMap<String, String>();
lang.put("English","en");
lang.put("Bengali","bn");
lang.put("Hindi","hi");
lang.put("Kannada","kn");
lang.put("Marathi","mr");
lang.put("Tamil","ta");
lang.put("Telugu","te");
final CharSequence[] inlang = {"English","Hindi","Bengali","Kannada","Marathi","Tamil","Telugu"};
AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(a, R.style.AlertDialog));
builder.setTitle(R.string.select_language)
.setIcon(R.mipmap.ic_launcher)
.setSingleChoiceItems(inlang, -1, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String lang_code=lang.get(inlang[which].toString());
Logger.d(inlang[which].toString());
updateLocale(lang_code);
}
})
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Utils.navigateToActivity(a);
a.finish();
}
})
.show();
}
public void updateLocale(String lang)
{
Locale locale;
if(lang.equalsIgnoreCase("en")) {
locale = new Locale(lang,"US");
PrefSettings.getInstance().setUserlanguage(lang);
}
else {
locale = new Locale(lang,"IN");
PrefSettings.getInstance().setUserlanguage(lang);
}
Logger.d(lang);
Locale.setDefault(locale);
Configuration config = a.getResources().getConfiguration();
config.locale = locale;
a.getBaseContext().getResources().updateConfiguration(config,
a.getBaseContext().getResources().getDisplayMetrics());
} }
The problem is occurring in the UserSettingActivity where I am not able to create a object of LanguageDialog in the fragment class. It is showing the error -
UserSettingActivity cannot be referenced from a static context. I have already tried all the possible answers to the questions similar to this problem but none could help me out.Thanks in advance for the help!
You can try getActivity() instead of using .this
your
MyPreferenceFragment is static, you cannot refer a non- static class from static fragment
public static class MyPreferenceFragment extends PreferenceFragment remove static from here