Change background using shared preference - java

I have an application that allows my users to customize the background of my application using buttons. My app works like this: First it will lead them to my main activity, where there is a button that they can press to customize the background. When they pressed that button, it will lead them to a dialog fragment that will give users an option to choose which background image they want. I'm able to change my background, however, the shared preference is not functioning correctly. When I close my app and open it, it changes back to my default background, but when I press the dialog fragment button, it then updates the background to whatever they chose.
So basically, the background only updates when I open the button that offers the background images.
I'm not sure if I explained it well so here is a gif of my
problem
The background only updates when I press the terrain button, does anyone have an idea to fix this? I'm still very new to android and java so I'm not sure if I'm just missing something...
PopupTheme.java
public class PopupTheme extends DialogFragment implements View.OnClickListener {
private ImageButton btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btn10;
private static final String BG_NAME = "bgName";
private static final String BG_KEY = "bg";
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.activity_popup_theme, container, false);
btn1 = view.findViewById(R.id.btn1);
btn2 = view.findViewById(R.id.btn2);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
if (getBackground() != R.drawable.bgscreen1 ){
MainActivity.mainLayout.setBackgroundResource(getBackground());
}
return view;
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn1:
MainActivity.mainLayout.setBackgroundResource(R.drawable.bgscreen1);
Toast.makeText(getContext(), "Clicked", Toast.LENGTH_SHORT).show();
storeBackground(R.drawable.bgscreen1);
break;
case R.id.btn2:
MainActivity.mainLayout.setBackgroundResource(R.drawable.bgscreen2);
Toast.makeText(getContext(), "Clicked", Toast.LENGTH_SHORT).show();
storeBackground(R.drawable.bgscreen2);
break;
}
}
public void storeBackground(int background) {
SharedPreferences sharedPreferences = getActivity().getSharedPreferences(BG_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit(); //accessing the shared pref
editor.putInt(BG_KEY, background);
editor.apply();
}
// getting the background
public int getBackground() {
SharedPreferences sharedPreferences = getActivity().getSharedPreferences(BG_NAME, Context.MODE_PRIVATE);
int selectedBG = sharedPreferences.getInt(BG_KEY, R.drawable.bgscreen1);
return selectedBG;
}
}
Main Activity.java
public class MainActivity extends AppCompatActivity {
private Button btnWatch, btnReadStory, btnFavorites, btnAbout, btnListen;
private ImageButton btnTheme;
static ConstraintLayout mainLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnTheme = findViewById(R.id.btnTheme);
mainLayout = findViewById(R.id.layoutMain);
btnTheme.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupTheme popupTheme = new PopupTheme();
popupTheme.show(getSupportFragmentManager(), "Popup Theme");
}
});
}
}

The problem is that you update background of your MainActivity only if you opened the PopupTheme dialog, So you need to move getBackground and update code from PopupTheme to the onCreate method on MainActivity so the code will executed when the user launch the app
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnTheme = findViewById(R.id.btnTheme);
mainLayout = findViewById(R.id.layoutMain);
int background = getBackground();
if (background != R.drawable.bgscreen1 ){
mainLayout.setBackgroundResource(background);
}
// Other code on onCreate
}
// Move getBackground method here from PopupTheme
Note: you can use -1 as default value of background and check if it's -1 that mean the user use the default background

Related

How can i implement dark mode on the first activity while the application launched for the first time

I implement dark mode with SwitchPreference in the second activity and in the first activity just a button take me to the second activity (Setting) the problem is when the app destroyed and i launched it again the dark mode not implemented until the second activity launched.
//First Activity
public class MainActivity extends AppCompatActivity {
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences( this/* Activity context */);
Boolean theme = sharedPreferences.getBoolean("darkMode", false);
button=findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent2=new Intent(MainActivity.this,Settings.class);
startActivity(intent2);
}
});
}
}
i have some idea that i should use sharedpreferences but i don't know how can i set it
//Second Activity
public class MySettingsFragment extends PreferenceFragmentCompat {
#Override
public void onCreatePreferences(#Nullable Bundle savedInstanceState, #Nullable String rootKey) {
setPreferencesFromResource(R.xml.preferences,rootKey);
SwitchPreference switchPreference=findPreference("darkMode");
if (switchPreference.isChecked()){
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
}else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
}
}
Overview:-
You can change dark mode or light mode via this function.
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.HERE_YOUR_MODE);
You can access the mode like this:
AppCompatDelegate.MODE_NIGHT_YES // for dark mode
AppCompatDelegate.MODE_NIGHT_NO // for light mode
AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM // for set as your devices theme
AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM // when you are in battery saver
Implementation:-
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
Boolean theme = sharedPreferences.getBoolean("darkMode", false);
if (theme){
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES); // implement here.
}else{
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO); // implement here.
}
}
Well as per your code , you are just one step away from achieving result
you just need to use below code in every activity's onCreate method
if (isDarkMode){ // isDarkMode is boolean which we can get from preference
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
}else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
```

set Title for popup in android

I want to build application in which I've search button when I clicked on this I get popup where I can search for student name.
I created all of this but I want to set Title for this dialog like "search for student by name"
this is my code
public class pop_up extends DialogFragment implements View.OnClickListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.popup,container,false);
Button btn_search = view.findViewById(R.id.btn_search);
Button btn_close = view.findViewById(R.id.btn_close);
TextView result = view.findViewById(R.id.txt_found);
EditText text = view.findViewById(R.id.txt);
btn_search.setOnClickListener(this);
btn_close.setOnClickListener(this);
getDialog().setTitle("Search for Student by Name");
return view;
}
#Override
public void onClick(View view) {...}
}
and this is code in MainActivity
final FragmentTransaction fragment = getFragmentManager().beginTransaction();
final pop_up pop = new pop_up();
Button btn = findViewById(R.id.btn_student);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pop.show(fragment,null);
}
});
Dialog appears but without title, so How can I set Title for it ?
you are crating dialog on completely wrong way
at first you should use onCreateDiolog insted of onCreatView
you should call AlertDialog.Builder to make dialog
read this doc to know how to use dialogs:https://developer.android.com/guide/topics/ui/dialogs#java
i have project that have bunch of dialog i leave a link if you want more example:
https://github.com/ErfanDP/Erfan_Delavari_HW13_Maktab36

Access method from Dialog to MainActivity

I have a main Activity in which I created a ViewPager that instantiate 3 other Fragments. One of these is a GridView which makes a popup appear when the user click on one item. Then, in this popup, I have a simple button.
What I want to do is: when the user click on this button, I would like to access a method in my main Activity (that should change the current item of my ViewPager) and then dismiss the popup.
I tried everything I could, but I cannot achieve this... I can set up the click event on my popup and dismiss it easily, but I didn't find out how I can access a method (or even a variable) from my popup to my main Activity.
I will put my most relevant code in here so you can understand the structure of my classes (hopefully...).
My main Activity:
public class MainActivity extends FirstActivity{
private ViewPager mViewPager;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewPager = (ViewPager) findViewById(R.id.viewpager);
// Set an Adapter on the ViewPager
mViewPager.setAdapter(new MainActivity_Adapter(getSupportFragmentManager()));
public void onSaveInstanceState(Bundle savedInstanceState)
{
menuBar.onSaveInstanceState(savedInstanceState);
}}
My ViewPager activity:
public class MainActivity_Adapter extends FragmentPagerAdapter{
public MainActivity_Adapter(FragmentManager fm)
{
super(fm);
}
#Override
public Fragment getItem(int position)
{
// Set the color background for each page
switch (position)
{
case 0:
return MainActivity_Inventory.newInstance();
case 1:
return MainActivity_Map.newInstance();
default:
return MainActivity_AR.newInstance();
}
}
// The number of Splash Screens to display
#Override
public int getCount()
{
return 3;
}}
My "Inventory" Fragment
public class MainActivity_Inventory extends Fragment implements View.OnClickListener{
public static MainActivity_Inventory newInstance()
{
MainActivity_Inventory frag = new MainActivity_Inventory();
Bundle b = new Bundle();
frag.setArguments(b);
return frag;
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// Select the layout
int layout;
layout = R.layout.activity_inventory_01;
// Inflate the layout resource file
View view = getActivity().getLayoutInflater().inflate(layout, container, false);
// Set the grid view
GridView gridview = (GridView) view.findViewById(R.id.inventory_gridView);
gridview.setAdapter(new InventoryImageAdapter(super.getActivity()));
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView parent, View v, int position, long id)
{
// Create a popup to show item details
createPopup();
}
});
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
}
public void createPopup()
{
DialogFragment newFragment = new PopupActivity_Inventory();
newFragment.show(getFragmentManager(), "itemDetails");
}
#Override
public void onClick(View v)
{
}}
And my popup dialog fragment:
public class PopupActivity_Inventory extends DialogFragment{
#Override
public Dialog onCreateDialog(final Bundle savedInstanceState)
{
// Build the alert dialog
final Dialog dialog = new Dialog(this.getActivity());
// Get the layout inflater
final LayoutInflater inflater = getActivity().getLayoutInflater();
// Set up the dialog box
dialog.setContentView(inflater.inflate(R.layout.activity_inventory_popup_01, null));
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.getWindow().setGravity(Gravity.TOP);
//dialog.getWindow().getAttributes().y = 100;
(dialog.findViewById(R.id.brick_button_01)).setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
// When button is clicked, ACCESS MAIN ACTIVITY!
dialog.dismiss();
}
});
return dialog;
}}
I really hope you can help me with this... I really need to get it working. Thank you very much!
If you need further details or explanation, please just tell me.
The best thing to do is use EventBus library. I have a demo app in which you can add items to RecyclerView from anywhere within the app using EventBus. You can use it as a reference to simply do something else instead of current task. Here is the link to the repo:
https://github.com/code-crusher/android-demos/tree/master/EventBusDemo
And if you want to understand how it works you can refer to my article, it explains how to make communications like this easy:
https://medium.com/#code_crusher/eventbus-for-android
Hope it helps. Happy coding :)
Read this https://developer.android.com/training/basics/fragments/communicating.html
Look for "To allow a Fragment to communicate up to its Activity, you can define an interface in the Fragment class and implement it within the Activity...."
Another way to achieve it is using an EventBus and post events by Fragments to be caught by Activities.

ImageButton changing an Image of another ImageButton causes unintended cycle

Aftermath of this: Image for ImageButton doesn't change as intended
When ImageButton of "ibChamp" is clicked, it opens up champions.xml. In that layout, there is an Imagebutton called "ibAnnie". What I want that to do when clicked is, to change the image of "ibChamp", and to switch to that layout. What happened here is that after "ibAnnie" is clicked, it switches to "create_build_page.xml", and in that is a changed picture of "ibChamp". But that only happens for a split second before changing back to the original, unchanged picture, "create_build_page.xml" layout. When I click the back button, it goes to the "create_build_page.xml" layout with the changed picture, but the buttons do not work. I would gladly provide any additional information required.
I'm still not entirely clear on what you're trying to achieve... but if my understanding is correct, this should get you closer:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.champions);
ImageButton ibAnnie = (ImageButton) findViewById(R.id.ibAnnie);
ibAnnie.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
RelativeLayout test = (RelativeLayout) findViewById(R.id.layoutChampions);
LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View createView = layoutInflater.inflate(R.layout.create_build_page, null);
test.addView(createView);
ImageButton img = (ImageButton) view.findViewById(R.id.ibChamp);
img.setImageResource(R.drawable.ic_launcher);
img.setTag(R.drawable.ic_launcher); // so you can retrieve it later
img.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// this will set the imageView of ibAnnie
ibAnnie.setImageView((Integer)view.getTag());
// this will remove the selection view from your layout
((RelativeLayout) findViewById(R.id.layoutChampions)).removeChild(createView);
}
});
// this opens another Activity... you don't want that, at least not for what you seem to be trying to do.
/*try {
Intent open = new Intent("android.intent.action.CREATE");
startActivity(open);
} catch (Exception e) {
}*/
}
});
}

Using android-color-picker in a fragment?

I am fairly new to android development and want to use the Android-Color_picker "AmbilWarna" inside a fragment. I am getting the error:
The constructor AmbilWarnaDialog(HomeFragment, int, new OnAmbilWarnaListener(){}) is undefined.
Is this because I am using a Fragment instead of a Fragment activity The tutorial I was using uses an Activity.
I am using the following tutorial:
http://wptrafficanalyzer.in/blog/android-color-picker-application-using-ambilwarna-color-picker-library/
public class HomeFragment extends SherlockFragment implements TabListener {
private View homeView;
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
homeView = inflater.inflate(R.layout.homefragment, container, false);
Button sColorBtn = (Button) homeView.findViewById(R.id.button2);
OnClickListener clickListener = new OnClickListener() {
#Override
public void onClick(View v) {
colorpicker();
}
};
// Setting click event listener for the button
sColorBtn.setOnClickListener(clickListener);
return sColorBtn;
}
public void colorpicker() {
// initialColor is the initially-selected color to be shown in the rectangle on the left of the arrow.
// for example, 0xff000000 is black, 0xff0000ff is blue. Please be aware of the initial 0xff which is the alpha.
AmbilWarnaDialog dialog = new AmbilWarnaDialog(this, 0xff0000ff, new OnAmbilWarnaListener() {
// Executes, when user click Cancel button
#Override
public void onCancel(AmbilWarnaDialog dialog){
}
// Executes, when user click OK button
#Override
public void onOk(AmbilWarnaDialog dialog, int color) {
Toast.makeText(getBaseContext(), "Selected Color : " + color, Toast.LENGTH_LONG).show();
}
});
dialog.show();
}
Use this:
AmbilWarnaDialog dialog = new AmbilWarnaDialog(getActivity().getApplicationContext(), 0xff0000ff, new OnAmbilWarnaListener() {
// Executes, when user click Cancel button
#Override
public void onCancel(AmbilWarnaDialog dialog){
}
// Executes, when user click OK button
#Override
public void onOk(AmbilWarnaDialog dialog, int color) {
Toast.makeText(getBaseContext(), "Selected Color : " + color, Toast.LENGTH_LONG).show();
}
});
So you have to use getActivity().getApplicationContext() instead of this. It will return with the Context.
If you want a fragment solution for Color Picker, I have made a fork of android-color-picker where DialogFragment is used and is re-created on configuration change. Here's the link: https://github.com/lomza/android-color-picker

Categories