Basically i want a Button to change to another one depending on the int Value stored in sharedprefs.
I have stage select in my game, if the user got enough score in level, then he can start the next one and i want to change the Button depending on that.
I'm setting up my Button's with custom Background created in XML Selector file located in drawable folder.
After that how i can call it in Java?
I tried a bit with if statement but cant find the right solution.
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
Button button = (Button) findViewById(R.id.button_id);
if (settings.getBoolean("nextLevel", true) {
button.setText("Level_2");
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
}
});
}
else {
//Everything should be the same.
}
Check also the developer docs concerning SharedPreferences in android: http://developer.android.com/guide/topics/data/data-storage.html#pref
Related
I am creating an android application, I am displaying images from drawable folder based on the numbering, my activity start showing images from number 1 and I am using buttons to show next or previous image.
I am trying to save the value of image user was viewing while pressed back button using shared preferences. my code looks like this
private int currentPage = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_read);
final Button btnNext = findViewById(R.id.btnNext);
final Button btnBack = findViewById(R.id.btnBack);
listOfObjects = getResources().getStringArray(R.array.object_array);
images = getResources().obtainTypedArray(R.array.object_image);
itemImage = (ImageView)findViewById(R.id.imgSpace);
final Spinner spinner = (Spinner)findViewById(R.id.spinner);
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,R.layout.my_spinner, listOfObjects);;
spinnerAdapter.setDropDownViewResource(R.layout.my_spinner);
spinner.setAdapter(spinnerAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
itemImage.setImageResource(images.getResourceId(spinner.getSelectedItemPosition(), -1));
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
final ImageView img = findViewById(R.id.imgSpace);
PhotoView photoView = (PhotoView) findViewById(R.id.imgSpace);
img.setImageResource(getResources().getIdentifier("page_"+currentPage,"drawable",getPackageName()));
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(spinner.getSelectedItemPosition() < spinner.getAdapter().getCount()){
spinner.setSelection(spinner.getSelectedItemPosition()+1);
}
}
} );
}
currentPage is the variable which I want to save after pressing back button or to go to any other activity and also if user minimises the application, I want to pass it to main activity in order to show the extra button of resume activity and also to show the exact image the user was seeing before pressing the back button when user clicks on resume activity button.
I am using Chris Banes's photoview to show the image. I know how to pass variables and et them in PHP however android is new for me. ANy help would be appreciated.
SharedPreferences prefs = getSharedPreferences("nameOfSharedPreference", MODE_PRIVATE);
SharedPreferences.Editor editor = getSharedPreferences("nameOfSharedPreference", MODE_PRIVATE).edit();
editor.putInt("image", R.imageID).commit();
#Override
onBackPressed(){
image = prefs.getInt("image", defaultValue) //Default value is taken if the pref doesn't exist yet
}
onBackPressed() is called automatically by android when pressing the phone back button. You can call it manually:
onBackPressed();
I don't understand the question completely but you could write:
SharedPreferences prefs = getSharedPreferences("nameOFPref", MODE_PRIVATE);
private int currentPage = prefs.getInt("image", 1);
The way it works is it saves a file in nameOfPref in the "image" section so you get it back when the program launches. Here we put 1 as default value so the value it will take is 1 the first time you launch the program. You should write:
SharedPreferences.Editor editor = getSharedPreferences("nameOfSharedPreference", MODE_PRIVATE).edit();
editor.putInt("image", idOFImageCurrentlyVIewed).commit();
Later in the program each time the user changes image. So it will change the preference and will make sure that when you launch the program back currentImage will take the right value.
In android studio you can look at the file system of emulated phones. For preferences you need to go in Android/data/com.yourPackageName/preferences and you should see your file there if everything goes fine.
I have two activities, in activity(1) I have a TextView, in activity(2) I have a button. I want to change the TextView color in activity(1) by clicking the button in activity(2) and save this color. How can I do this?
You can save your color with Shared Preferences when your button is clicked and later get it :
In activity 2 when your button is pressed :
PreferenceManager.getDefaultSharedPreferences(MainActivity.this)
.edit()
.putString(key, value).apply();
And in activity 1 get the value that you saved:
PreferenceManager.getDefaultSharedPreferences(DriverScreen.this).getString(key, "default value")
You must use a database for keep the textview color and get the color from database. when click the button you can change it in the database.
There are many solutions to your problem
You can use sharepreference.
You can use a singleton class.
You can use a eventlistener.
You can use intent.putExtra() for this purpose
there will be many ways to achieve what you want, use one of them as per your choice.
To store text color :
Use SharedPreference
Use Room or SQLite Database
Save color in Singleton class
or open second activity using startActivityForResult() if you're coming back to 1st activity after completion of 2nd activity work.
To Change Text Color:
Use Listener to change text color when you press button from 2nd activity
Use EventBus if you already have implemented it in your project
Using Local Broadcast Receiver (Send broadcast to 1st activity after click on button of 2nd activity)
there is many ways to change text color from another activity.
First
pass color value using intent
Code
Main2Activity.java
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int color=getResources().getColor(R.color.colorAccent);
Intent intent=new Intent(Main2Activity.this,MainActivity.class);
intent.putExtra("color",color);
startActivity(intent);
}
});
MainActivity.java
android_text=findViewById(R.id.android_text);
color=getIntent().getIntExtra("color",0);
android_text.setTextColor(color);
Second way
use static variable
code
MainActivity.java
static int color;
android_text=findViewById(R.id.android_text);
android_text.setTextColor(color);
Main2Activity.java
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//set color
MainActivity.color=getResources().getColor(R.color.colorAccent);
Intent intent=new Intent(Main2Activity.this,MainActivity.class);
startActivity(intent);
}
});
after update
I Hope its work for you
Currently i managed to create the buttons dynamically on a view
Here is the my code to create the buttons;
public void Add_on(View v) {
AlertDialog.Builder mbuilder = new AlertDialog.Builder(Mb.this);
View mview = getLayoutInflater().inflate(R.layout.activity_mb1, null);
EditText number = (EditText) mview.findViewById(R.id.etnum);
Button Create = (Button) mview.findViewById(R.id.etcreate);
Button Cancel = (Button) mview.findViewById(R.id.etcancel);
Create.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
if (!number.getText().toString().isEmpty())
{
Toast.makeText(Mb.this, "Number can be NULL",Toast.LENGTH_SHORT).show();
LinearLayout yenilayout = new LinearLayout(Mb.this);
int n =1;
for(int i=0; i<n; i++)
{
Button yeniButton = new Button(Mb.this);
yenilayout.addView(yeniButton);
yeniButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(Mb.this, "Button is working",Toast.LENGTH_SHORT).show();
}
});
}
altlayout.addView(yenilayout);
} else {
Toast.makeText(Mb.this, "Number cannot be NULL",Toast.LENGTH_SHORT).show();
}
}
});
But whenever i recall the activity, the buttons are no longer exist. So May i know can i place the button there permanently?
Thank you for suggestions
You can use Bundle to save an activity's state and recreate it in the onCreate() method. This works for a particular instance of Activity, so can be used to save data concerning selection, or user input etc., but not data that you need to be persistent across application launches.
To use the Bundle, override the onSaveInstanceState(Bundle) and onRestoreInstanceState(Bundle) methods in the Activity class. You can use methods from Bundle to save whatever data you like in a map, and get it back in onRestoreInstanceState(Bundle), which is called in onStart().
The default implementations already handle most UI stuff though, and I would have thought this would keep track of your buttons for you, so it may be that your question is actually about associating some persistent data with your application. (this also means that if you do override the above methods, you should make sure to call the super methods in the first line of your implementation).
If you need persistent data across application launches, then the quickest and easiest way would be to use SharedPreferences, see this answer for an example.
I have an app where in the mainActivity the user has about 5 options to choose from. Clicking one of them opens a new activity but essentially all 5 opens up identical activities with different headings. In the newly opened activities, users use multiple rating bars to delegate points to some specified attributes. Using SharedPreference, can I save the entire activity so when I back out, click on the same option everything isn't gone? Or do I need to save let's say, the individual rating bar values using the SharedPreference?
Here is some code for one of the activities that opens from a button click. Something is terribly wrong because it is crashing now. Any suggestions?
public class MageSkillScreen extends AppCompatActivity
{
public float skillPoints = 10;
public float strengthRating;
public float intellectRating;
public float wisdomRating;
public float dexterityRating;
public float totalSkill;
public float mageStrength;
public float mageDexterity;
public float mageIntellect;
public float mageWisdom;
public RatingBar strengthBar;
public RatingBar intellectBar;
public RatingBar wisdomBar;
public RatingBar dexterityBar;
Button submit;
//preferences
SharedPreferences magePref;
boolean rememberRatings = true;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mage_skill_screen);
strengthBar = (RatingBar) findViewById(R.id.mageStregth);
intellectBar = (RatingBar) findViewById(R.id.mageInt);
wisdomBar = (RatingBar) findViewById(R.id.mageWisdom);
dexterityBar = (RatingBar) findViewById(R.id.mageDext);
submit = (Button) findViewById(R.id.submit);
}
#Override
public void onPause()
{
SharedPreferences.Editor edit = magePref.edit();
edit.putFloat("strengthPts", strengthBar.getRating());
edit.putFloat("dexterityPts", dexterityBar.getRating());
edit.putFloat("intellectPts", intellectBar.getRating());
edit.putFloat("wisdomPts", wisdomBar.getRating());
//edit.putString("pointsLeft", ptsRemaing.getText().toString());
edit.commit();
super.onPause();
}
#Override
public void onResume()
{
super.onResume();
rememberRatings = magePref.getBoolean("mageRatings", true);
mageStrength = magePref.getFloat("strengthPts", 0.0f);
mageDexterity = magePref.getFloat("dexterityPts", 0.0f);
mageIntellect = magePref.getFloat("intellectPts", 0.0f);
mageWisdom = magePref.getFloat("wisdmPts", 0.0f);
}
}
update view activity in function onResume
#Override
protected void onResume() {
super.onResume();
//load SharedPreferences again and update view
}
Okay, let's go step by step.
So I have an app where in the mainActivity the user has about 5
options to choose from.
Okay, sounds good, so you have 5 buttons in MainActivity for users.
Clicking one of them opens a new activity but essentially all 5 opens
up identical activities with different headings.
Can, you please be more specific here, click on one button should launch one single activity not all 5. And this is not possible at a time only one activity exists for the user to view or interact with. Others, goes in the backstack.
Please read about activity lifecycle for the same.
https://developer.android.com/guide/components/activities/activity-lifecycle.html
Using SharedPreference, can I save the entire activity so when I back
out, click on the same option everything isn't gone?
No, you can't save the whole activity inside Sharedpreference. SharedPref is used to store key value pairs, like hashMap and only primitive values, you can store activities and you should never do it.
https://developer.android.com/reference/android/content/SharedPreferences.html
Now, coming back to the solution for the same.
It totally depends on the usecase you are trying to implement, if you are launching different activities on each button click and want to persist some data across other activities, store the primitive values in sharedpref
and then access it in other activities.This also holds, true if you want to persist the same data in app re-launch.
If not, then you can have a singleton object and modify it and access it, across other activities, make sure to make it null to avoid memory leak.
I hope it clears your doubt.
Cheers..!!
I have a problem. I have 3 activities (MainActivity, DetailsActivity, SettingsActivity) and in SettingsActivity I have a Togglebutton "Nightmode". What I want is, when the button is changed, change background of all three activities on gray color.
public class SettingsActivity extends AppCompatActivity {
//This is SettingsActivity(not Main one)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
TextView SettingsTitle = (TextView) findViewById(R.id.SettingsTitle);
TextView NightText = (TextView) findViewById(R.id.NightmodeText);
ToggleButton toggleNightMode = (ToggleButton) findViewById(R.id.toggleNightmode);
final RelativeLayout NightBG = (RelativeLayout) findViewById(R.id.NightBG);
final LinearLayout DetailsBG = (LinearLayout) findViewById(R.id.mainBG);
final LinearLayout HomeBG = (LinearLayout) findViewById(R.id.HomeBG);
toggleNightMode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NightBG.setBackgroundColor(Color.parseColor("#545657"));
HomeBG.setBackgroundColor(Color.parseColor("#545657"));
DetailsBG.setBackgroundColor(Color.parseColor("#545657"));
}
});
NightBG is in the same activity as that java file (SettingsActivity). But HomeBG is in MainActivity and DetailsBG is in the DetailsActivity. Everytime I start the app, and press on that button, app craches. If I delete HomeBG and DetailsBG from this file, it works just fine with changing current layout's color to gray. Please help me.
One easy way to store little settings like this across multiple activities that may not be open/active at the time of the button click would be to use SharedPreferences.
It might be a little overkill for such a simple piece of code but you can always give it a try if you don't find anything else.
Your code could look something like this:
toggleNightMode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Set the color of this activity
int color = Color.parseColor("#545657")
View view = SettingsActivity.this.getWindow().getDecorView();
view.setBackgroundColor(color);
// Save color preference
SharedPreferences sharedPref = SettingsActivity.this.getSharedPreferences("bgColorFile",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("color", color);
editor.apply();
}
});
And then when you open your activities you place something like this in the onStart() or onCreate() method of your activity:
// Get the color preference
SharedPreferences sharedPref = getSharedPreferences("bgColorFile",Context.MODE_PRIVATE);
int colorValue = sharedPref.getInt("color", 0);
View view = this.getWindow().getDecorView();
view.setBackgroundColor(colorValue);
So what you're actually doing is storing the background color as persistent data and fetching it once you reopen/open the activity that you want to have the color on. The benefit of this method is that whenever you close your app the preferred background color will be remembered. I hope this helps.
Change background for current activity in the same activity. Since DetailsActivity is not running, you can't do that, it gives you null pointer. Is kind of you are trying to eat 3 apples and you have just one. After current activity is started, change background.
Update:
You can do that in current activity and just in current activity:
findViewById(android.R.id.content).setBackground(getColor(R.color.your_color));
Don't try to call this in other activities that are not running.
setBackground()
or
setBackgroundColor()
If your other activities are open, you should send a message to the other activities by using an Intent.
How to send string from one activity to another?
When you receive the Intent you could then set the background of the activity.
If your other activities are not open yet, you will not be able to send an Intent to them. In this case you could have each Activity reference a static value in your main activity that could contain the current background color. You would want to reference that value on the other activities on create functions.
Here is an example on how to reference a variable from another activity.
How do I get a variable in another activity?
This might not be the most pretty way to handle it but it should work.
as Ay Rue said you have 2 options: use static variable for that button, and then in onResume of each activity, check the value of the static variable (true or false). or you can save a private variable nightMode and then pass this value in the intent when you need to move to the other two activities.
don't set the background color if you already set before and have an updated background color.