I set the background color of my app with this code:
RelativeLayout rl = (RelativeLayout)findViewById(R.id.layout);
rl.setBackgroundColor(Color.RED);
How could I have this carry over to the next activities that come after this one, without using XML because it is not always the color RED. This depends on a selection by the user. But once the user has selected RED I want this color to carry over to the next activities. Is there a way to go about this without doing something like this for all the actives.
Intent intent = new Intent(this, NextActivity.class);
intent.putExtra("Color", "RED");
startActivity(intent);
And then on the next activity use that Extra to set the color. Is there a way that I can just set it for all the following activities until the user changes it?
Thanks for the help in advance.
i think you need to get #Code for that color and use
To send value
Intent intent = new Intent(this, NextActivity.class);
intent.putExtra("Color", "#Code");
startActivity(intent);
In next activity..
RelativeLayout rl = (RelativeLayout)findViewById(R.id.layout);
rl.setBackgroundColor(Color.parseColor(intent.getExtra("Color")));
colors used in android are of int format not String
setBackgroundColor() takes a color in numeric form (e.g., 0xFFFF0000 for red)
So you can do this way:
Suppose from class A sending a int variable to class B
int bgColor=Color.RED; <---Change It with whatever you want(but should be numeric)
Intent bgIntent = new Intent(Background.this, MainScreen.class);
bgIntent.putExtra("background", bgColor);
startActivity(bgIntent);
and on class B
Intent bgIntent = getIntent();
bgGlobal = bgIntent.getExtras().getInt("background",-1);
if(bgGlobal != -1)
{
DetailsLayout.setBackgroundResource(Color.parseColor(bgGlobal));
}
else
{
DetailsLayout.setBackgroundResource(R.color.a1);
}
for more info please refer this
Put the setting of background color in a singleton class, say
public class ColorHolder {
public static ColorHolder instance=null;
private int color;
public static ColorHolder getInstance(){
if(instance==null){
instance=new ColorHolder();
}
}
public int getColor(){
return color;
}
public void setColor(int c){
color=c;
}
}
Then create a subclass of Activity, say
public class ColoredActivity extends Activity{
protected void onCreate(Bundle s){
super.onCreate(s);
RelativeLayout rl = (RelativeLayout)findViewById(R.id.layout);
rl.setBackgroundColor(ColorHolder().getInstance().getColor());
}
}
Then all the Activities which want to apply this setting should extend this "ColoredActivity"
Related
I am a new android programmer.
I have 4 activities: A B C D.
The order is A -> B -> C -> D -> A and A -> D using buttons.
I want to save data in ArrayList that is in activity D.
The problem is that when I move from D to A and come back to D, the data in the ArrayList didn't save.
Code for D activity here:
public class SchedulerActivity extends AppCompatActivity {
public String name = "";
public String number = "";
public String date = "";
public String hour = "";
public ArrayList<EventClass> scheduler = new ArrayList<>();
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scheduler);
Bundle extras = getIntent().getExtras();
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(SchedulerActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
finish();
}
});
if (extras != null) {
String sender = extras.getString("sender");
if(sender.compareTo("Hours") == 0) {
name = extras.getString("name");
number = extras.getString("number");
date = extras.getString("date");
hour = extras.getString("hour");
Date real_date = new Date();
SimpleDateFormat formatter1=new SimpleDateFormat("dd/MM/yyyy");
try {
real_date = formatter1.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
scheduler.add(new EventClass(real_date, name, number, "", hour));
for (EventClass event : scheduler){
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
final TextView t = new TextView(this);
t.setText(event.toString());
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linearLayout);
linearLayout.addView(t, params);
}
}
else{
for (EventClass event : scheduler){
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
final Button btn = new Button(this);
final TextView t = new TextView(this);
t.setText(event.toString());
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linearLayout);
linearLayout.addView(btn, params);
}
}
}
}
I want to change my ArrayList when C->D occurs and print it and when D->A occurs I just want to print it. I know that I can with SharedPreferences but for the first step, I want to do this with ArrayList.
What's the best way to do this?
Creating static objects is not a good approach. So you can use android activity stack in-place of using static Arraylist. Android activities are stored in the activity stack. Going back to a previous activity could mean two things.
You opened the new activity from another activity with startActivityForResult. In that case you can just call the finishActivity() function from your code and it'll take you back to the previous activity.
Keep track of the activity stack. Whenever you start a new activity with an intent you can specify an intent flag like FLAG_ACTIVITY_REORDER_TO_FRONT or FLAG_ACTIVITY_PREVIOUS_IS_TOP. You can use this to shuffle between the activities in your application.
The scheduler is a non-static field in the SchedulerActivity which means that its existance is tied to the instance of the activity. When the activity instance is destroyed, and that might happen for example when the screen orientation is destroyed or you move to another activity, so are all its non-static fields. You can change that by adding a static keyword before your field:
public static ArrayList<EventClass> scheduler = new ArrayList<>();
Now, your field is tied to the class itself, not the instance, whitch means it wont be destroyed along with the instance. But it also means that it is shared between all instances and must be referenced with the class name outside of the class body:
EventClass event = SchedulerActivity.scheduler.get(0)
A good approach is saving your data in a local database, like Room. You need to save before go to new activity, and get it back on OnResume().
I am trying to have what the user types in the textEdits in the StartScreen Activity to show up in my MainActivity.
First I created my 2 intents for the 2 users.
String playerOneContent = playerOneEditText.getText().toString();
String playerTwoContent = playerTwoEditText.getText().toString();
Intent intent = new Intent(StartScreen.this, GameView.class);
intent.putExtra("NAME", playerOneContent);
intent.putExtra("NAME2", playerTwoContent);
startActivity(intent);
Then in my GameView I have the following code:
public class GameView extends View {
Paint paint = new Paint();
Context context;
#Override
public void draw(Canvas canvas) {
super.draw(canvas);
paint.setColor(Color.YELLOW);
canvas.drawPaint(paint);
paint.setColor(Color.RED);
paint.setTextSize(20);
canvas.drawText("NAME",50, 50, paint);
}
}
How would I get the intents from the StartScreen and use it in the GameView?
This is the code I had in my Main Activity originally:
TextView playerOneTextView = (TextView)findViewById(R.id.playerOneTextView);
TextView playerTwoTextView = (TextView)
findViewById(R.id.playerTwoTextView);
playerOneTextView.setText(getIntent().getStringExtra("NAME"));
playerTwoTextView.setText(getIntent().getStringExtra("NAME2"));
Unfortunately, intents don't work in Android without extending the Activity class.
Therefore, what you can do is create an object of the MainActivity class in your GameView class and get the value of the variables.
So something like this in MainActivity.java:
public String playerOneContent;
public String playerTwoContent;
#Override
public void onCreate...... //blah blah blah
public void functionWhereYouSetValueofStrings(){
playerOneContent = playerOneEditText.getText().toString();
playerTwoContent = playerTwoEditText.getText().toString();
}
Now, in the GameView.java class do the following to get the values:
MainActivity ma = new MainActivity();
playerOneTextView.setText(ma.playerOneContent);
playerTwoTextView.setText(ma.playerTwoContent);
It's using the Object to refer to the public fields that you have in MainActivity.java. I believe that this should answer your question, and help you.
If not, then just make a comment with the problem below.
I've got 2 activities and a class that extends Application where I'm trying to store global variables with a kind of setter getter functions.
The main activity sets some views and a chart; then calls the second activity which should be setting values to be used afterwards on the previous chart.
Then pressing backbutton and returning to the previous activity onRestart is called and the chart is refreshed.
The problem is I lose my theorically global variables somewhere. Debugging i realized that the functions work perfectly fine while im adding values in the second activity but when I return to the first activity globalXCount returns '0' again. Why is that?
I think im missunderstanding some point regarding lifecycles.
I attach some fragments of the code.
First activity:
public class MainActivity extends Activity {
Global glObj = new Global();
CombinedChart mChart;
private int itemcount;
float displayed;
private final List<String> mMonthList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
itemcount = ((Global) this.getApplication()).getGlobalXCount();
displayed = itemcount/20;
mChart = (CombinedChart) findViewById(R.id.mchart);
populateHeaderList();
setChartSettings();
Intent intent = new Intent(MainActivity.this, QandA.class);
startActivity(intent);
}
#Override
protected void onRestart() {
super.onRestart();
itemcount = ((Global) this.getApplication()).getGlobalXCount();
displayed = itemcount/20;
populateHeaderList();
setChartSettings();
}
Second activity:
public class QandA extends Activity {
Global glObj = new Global();
ViewFlipper flipper;
private float lastX;
...
}else{
//TODO If all information if correctly filled
trainedmins = et1.getText().toString();
localLineValue = Integer.parseInt(trainedmins) * Integer.parseInt(statusQ1);
//Add values to lines
glObj.setLineXvalues(localLineValue);
// TODO Add new Bar value //
//Add 1 more value to count
glObj.addGlobalXCount();
}
...
Global class:
public class Global extends Application {
//TODO
public Integer globalXCount;
private List<Integer> lineXvalues = new ArrayList<>();
private List<Integer> barXvalues = new ArrayList<>();
//////
public Integer getGlobalXCount() {
if (this.globalXCount == null){
this.globalXCount = 0;
return this.globalXCount;
}else{
return this.globalXCount;
}
}
public void addGlobalXCount() {
if (this.globalXCount == null){
this.globalXCount = 0;
}else{
this.globalXCount = this.globalXCount + 1;
}
}
Thanks in advance.
First of all, register your custom Application context in AndroidManifest.xml within the <application>-tag.
<application
android:name="<your_package>.Global" ...>
Access the global application context within your activities like this:
Global glObj = (Global) getApplicationContext();
glObj.addGlobalXCount();
Do not create a new instance with new! Always retrieve the instance via getApplicationContext().
Furthermore, I would suggest you to initialize your class field glObj within the onCreate()-method of your Activities.
So say a user enters a total in an EditText field in my Incomings class, I then want this to be passed to my Results class. How do I go about this in Android? I know the best way is to use Accessor methods.
My Incomings class:
public void onClick(View v) {
String userLoan = etLoan.getText().toString();
String userGrant = etGrant.getText().toString();
String userFirst = etFirst.getText().toString();
float fUserLoan = Float.parseFloat(userLoan);
float fUserGrant = Float.parseFloat(userGrant);
float fUserFirst = Float.parseFloat(userFirst);
float totalIncomings = fUserLoan + fUserGrant + fUserFirst;
Intent intent = new Intent(v.getContext(), Outgoings.class);
startActivity(intent);
}
});
My results class has a blank function and will calculate the totals
I have tried using accessor methods in my MainAcivity class:
public float getTotalOutgoings() {
return totalOutgoings;
}
public void setTotalOutgoings(float totalOutgoings) {
this.totalOutgoings = totalOutgoings;
}
public float getTotalIncomings() {
return totalIncomings;
}
public void setTotalIncomings(float totalIncomings) {
this.totalIncomings = totalIncomings;
}
public float getTotalResult() {
return totalResult;
}
public void setTotalResult(float totalResult) {
this.totalResult = totalResult;
}
Any suggestions?
Pass Intent extras:
Intent intent = new Intent(v.getContext(), Outgoings.class);
intent.putExtra ("total",totalIncomings);
startActivity(intent);
Then access in your next Activity with
Intent i = getIntent();
float totalComings = i.getFloatExtra("total",-1.0);
Now about your Results class. It depends exactly what you want to do with that class. If all you need is a simple calculation, make a static method. And data passing is usually the other way around. The Activity calls a data class, gives it data, then the data class does whatever it needs to do and returns the result to the Activity.
use
Bundle bd = new Bundle();
bd.putFloat("key",value);
intent.putExtras(bd);
startActivityForResult(intent,1);
On other class
Bundle bund= getIntent().getExtras();
float value= bd.getFloat("key");
Are you trying to call a function on your MainActivity?
MainActivity m = (MainActivity) getActivity();
m.setTotalIncomings(XXX);
I'm a novice programmer and I'm trying to learn Android coding using Eclipse.
This is my first time using StackOverflow.
Just for tutorial purposes, I want to make a simple Animal Encyclopedia.
So in my Home class, there are some buttons: "Dog", "Cat", "Bird", etc. When I click the button, it will bring me to the same layout but of course with different content.
So I created a class named AnimalData that holds the
ArrayList<Integer> to store R.drawable.xxx and ArrayList<String>
to store the text that I will put below the picture (like "Bulldog"
or "Husky")
Then I created a class named ChangeContent to set all those drawable
and text to the XML
But whenever I click the button, it results in Stopped Unexpectedly Error
Below are the shortened Home class, The "crash-maker" isn't here. I have checked the whole code line per line using Thread.sleep(2000), so if my app crashes before 2 second, the error is before the sleep() code and vice versa.
public class Home extends Activity implements OnClickListener{
Button dog, cat, bird;
AnimalData ad;
ChangeContent cc;
private ArrayList<Integer> drawable;
private ArrayList<String> title;
public Home(){
ad = new AnimalData();
cc = new ChangeContent(ad);
drawable = new ArrayList<Integer>();
title = new ArrayList<String>()
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
//set the findViewById for all the buttons
//set onClickListener() to all the buttons
}
public void onClick(View v) {
switch (v.getId()){
case R.id.bDog:
drawable.add(R.drawable.xxx);
drawable.add(R.drawable.yyy);
title.add("Bulldog");
title.add("Husky");
break;
case R.id.Cat:
//same
break;
case R.id.bBird:
//same
break;
}
ad.setDrawable(drawable);
ad.setTitle(title);
Intent i = new Intent("animal.ChangeContent"); //from Manifest
startActivity(i);
}
}
The AnimalData is just a typical getter setter, so I will just skip the code for that
The error is right after ChangeContent started because even when I put the sleep() on the first line of constructor, it doesn't have any effect.
public class ChangeContent extends Activity {
TextView title1, title2;
ImageView pic1, pic2;
private ArrayList<Integer> drawable;
private ArrayList<String> title;
public ChangeContent(AnimalData data){
drawable = new ArrayList<Integer>();
title = new ArrayList<String>();
drawable = data.getDrawable();
title = data.getTitle();
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.animal_info);
//findViewById for the TextView and ImageView
//setText() for TextView and setImageResource() for ImageView
}
}
Sorry for the long question, I tried to make it as short as possible
Can you guys help me figure the error out?
Thanks before
You are trying to get arraylist from intent, whereas you are not putting putStringArrayList and putIntegerArrayList methods.
putIntegerArrayListExtra(String name, ArrayList<Integer> value)
putStringArrayListExtra(String name, ArrayList<String> value)
so Change calling activity to following:
Intent i = new Intent(Home.this, ChangeContent.class); //from Manifest
i.putIntegerArrayListExtra("drawables", drawable);
i.putStringArrayListExtra("titles", titles);
startActivity(i);
and get data from intent in onCreate method by following methods:
getIntegerArrayListExtra, and getStringArrayListExtra
you also can do following by making contentChanged method to static, by this you wont need to do much changes in your application code, just do following:
public class ChangeContent extends Activity {
TextView title1, title2;
ImageView pic1, pic2;
private static ArrayList<Integer> drawable;
private static ArrayList<String> title;
public static ChangeContent(AnimalData data){
drawable = new ArrayList<Integer>();
title = new ArrayList<String>();
drawable = data.getDrawable();
title = data.getTitle();
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.animal_info);
//findViewById for the TextView and ImageView
//setText() for TextView and setImageResource() for ImageView
}
}
See the answer by RajaReddy P here:
https://stackoverflow.com/a/9937854
In the send class use:
Intent intent = new Intent(PhotoActivity.this,PhotoActivity1.class );
intent.putIntegerArrayListExtra("VALUES", image);
startActivity(cameraIntent);
.. and in the receiver class use:
Intent i = getIntent();
ArrayList<Integer> img = i.getIntegerArrayListExtra("VALUES");
Your approach is wrong -
public Home(){
ad = new AnimalData();
cc = new ChangeContent(ad);
drawable = new ArrayList<Integer>();
title = new ArrayList<String>()
}
ChangeContent is a Activity class so, you don't pass parameter like this.
Passsing class should be serializable and use it -
startActivity(new Intent(this, ChangeContent.class)
.putExtra("key", ad);
And in your ChangeContent class extract the class from Intent
So, change your code design and go ahead.
Best of luck.