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.
Related
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
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'm using Eclipse for windows 7 and I am making an informative application(just text and offline content).
In my app I have about 180 buttons. Each button will lead to another screen. I need to know how to make each button lead to a specific screen?
And also, is there a way to like duplicate the code and not spend hours copying and pasting the code 180 times?
Check my code below for the first two screens:
That's for the MainActivity.java:
public void addListenerOnButton() {
final Context context = this;
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(context, MainActivity2.class);
startActivity(intent);
}
});
}
I mean that code is only for one single button. Am I supposed to repeat this for every single button?
and also a question, how many classes should I do? 180 main activities, 180 fragment_main.xml and 180 activity_main.xml?
That's my idea, since your application is just a "informative application" you can create two activities:
Main activity with buttons
"Information page"
To do it i need info about how you get this informations:
In a SQLite Database.
In a string-array
Personally, i prefer a SQLite DB it allows you to improve it without problems in the future.
About the Information activity:
Example: in your layout you have a TextView where will be added the text which this activity should be passed.
To make it dynamic in your case we pass the string to show using Intents, in our onCreate we add something like this:
Intent intent = getIntents();
String stringToDisplay = null;
if (intent != null)
{
stringToDisplay = intent.getStringExtra (EXTRA_STRING_CONTENT);
}
getIntents will get the Intent object which is created and passed to it by our main activity. getStringExtra is a simple method which says to Android: i want to get the string which is saved with the key EXTRA_STRING_CONTENT (it's something like a Map)
EXTRA_STRING_CONTENT is a field which we used to make sure we don't make any error in passing data, since we need to use the same name when we pass it (in MainActivity) and when we read it (InformationActivity)
public static final String EXTRA_STRING_CONTENT = "EXTRA_STRING_CONTENT";
Ok, we are done.
We now only need to set the string to our TextView:
TextView infoTextView = (TextView) findViewById(R.id.infotextview);
infoTextView.setText (stringToDisplay);
Stop it.
Now we should go to our MainActivity code and modify our addListenerOnButton
final Context context = this;
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(context, MainActivity2.class);
startActivity(intent);
}
});
Well, i will focus on this two lines
Intent intent = new Intent(context, MainActivity2.class);
startActivity(intent);
We need to pass the string to display here, how?
Before we used getStringExtra now it's similar (note: it's the same Intent class) but now we need the putExtra method, the compiler will select the correct overload for us so we just need to do
String stringToDisplay = "Hello world";
intent.putExtra(InformativeActivity.EXTRA_STRING_CONTENT, stringToDisplay);
(Note: InformativeActivity.EXTRA_STRING_CONTENT)
With the current code we will always sent Hello world to the second activity but we need something of dynamic based on the button... well now this depends on how you get the data.
If it's a string-array, you can save the string-array in an array and then based on the button (if it's the first sent string index 0, etc.).
An example:
int buttonId = 1; // it will be a general variable, if it's button 1 it will be 0, if 2-1 etc.
String[] informations = getResources().getStringArray(R.array.infos); // in a real code you should move it outside the `onClick` code and put it in a static final field.
intent.putExtra(InformativeActivity.EXTRA_STRING_CONTENT, informations[buttonId]); // it's the same of above
If you understand the concept you will know how to adapt the code based on your needs.
There are some cases where you need more info or what you want to sent is something which is better if managed by the second activity (example: in a sqlite database you could sent only the id of the line and read lines in the second activity based on this id)
Some things which you could change:
Avoid to call it MainActivity2, it's not so helpful as name
You don't need really to save Context, you could just use MainActivity.this
Try to make your addListenerOnButton more general, example take as argument a Button and set the listener to it.. don't read it from XML you will end up with 180 methods for every button.
I am new to android and am working on a fairly basic android application where users are able to create items that are added to a ListView. On creation of each item I create a instance of the 'clicker' class which keeps track of each items name/tick count/other statistics.
when on of the items in the list are clicked it launches a general activity, used by all of the items. I pass the 'clicker' class object to the activity so that it may construct initialize the textviews.
This is what happens when a list item is clicked (the clicker instances are created in a hashmap named clickers, so I first retrieve the key, then call clickers.get(key))
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// pass along some ID so that the new activity can retrieve info
String clickedName = clickerListItems.get(arg2);
Intent intent = new Intent(MainActivity.this, ClickerActivity.class);
intent.putExtra("clickerName", clickers.get(clickedName));
startActivity(intent);
}
This is how the general activity receives the info
public class ClickerActivity extends Activity {
protected Clicker currentClicker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_clicker);
Intent i = getIntent();
currentClicker = (Clicker) i.getSerializableExtra("clickerName");
TextView clickerHeader = (TextView) findViewById(R.id.clickerHeader);
clickerHeader.setText(currentClicker.getName());
final TextView countDisplay = (TextView) findViewById(R.id.countText);
countDisplay.setText(Integer.toString(currentClicker.getCount()));
final Button incrementButton = (Button) findViewById(R.id.incrementButton);
final Button resetButton = (Button) findViewById(R.id.resetButton);
(continues)
here's what the general activity looks like to add some perspective. It's fairly plain right now seeing as I am just starting out.
The issue is that say I click on item A of the ListView and increment it's counter (one of the stats) and then press the back button to return to the List Activity. Now if I click on the same listitem to reload the activity none of the data seems to have been saved. Is the clicker class instance not actually being altered? How do I save the info or restore the info? I would do something onRestoreInstanceState but since this is an activity that may be loaded by any item in the list that wouldn't work, right?
If there any clarification is required please let me know, thank you.
You can use shared preferences, to preserve those values.
http://developer.android.com/reference/android/content/SharedPreferences.html
By using this, none of your data will be lost. Just make sure that when you are starting the app again after killing it, you reset the values stored, so that your values are saved for activity relaunch, but not for app relaunch (unless you want it for that too).
EDIT: You can also put all your main code into an Asynctask(), so that processing would be done in the background and it would be kept alive even when you come out of the app.
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