Variable not updating value - android

This is strange, maybe someone can help with this. I have two classes and when I try to access variable from main class, value is always 0.0
MAIN CLASS
public class MainActivity extends Activity {
public float angleCurrent;
- do something whith angleCurrent
//System.out.println(angleCurrent); - I get right values
}
SECOND CLASS
public class SecondClass extends ImageView {
public float curAngle = new MainActivity().angleCurrent;
//System.out.println(curAngle); - I get 0.0 all the time
}
Code is just illustration.

There are a couple big issues at play here. First, why the behavior is occurring:
You are not accessing the variable from the first MainActivity instance inside of SecondClass, you have created a new second instance of MainActivity, so you are getting access to a different variable than the original.
Now, the second issue surrounds the correct way to do this in Android. You should NEVER directly instantiate Activity instances. It is also not good practice to pass references to an Activity around any more than the framework already does. If your Activity needs to pass some information to your custom ImageView, you should create a method on your ImageView that you can use for the Activity to pass the value forward (i.e. SecondClass.setCurrentAngle(angleCurrent))

If you are looking to a View to access variables in the activity, it's not going to work. You need to add a setMethod to your custom view and set the value from the activity. Chthlu is right about why you aren't getting a value: new creates a different instance than the one you have on screen. You should never call new on an Activity class. You shouldn't even HAVE a constructor for an Activity, you should setup everything in the onCreate method.

Related

Define MainActivity as static variable in order to access findViewById method

While I was coding, I wanted to use findViewById method to find a view that cant access in the current view but can be accessed via the MainActivity. So two options came to my mind. One is creating a static method from that object in the MainActivity class and access the static object. The second method is to create a static object form MainActivity class itself(this) and access the findViewById method by calling the static object. Please answer the method I should use.
And apart from that, it got me thinking that whether an Android developer should come across this type of scenario or whether I have done some improper coding to access findViewById method in MainActivity while I was in a different view.
You can take a look at the code in the below repo.
https://github.com/chrish2015/ExpenseTrackerLatest
Thanks
If you are inside a class that is neither a Context nor an Activity and you need to use a method which exists inside the activity or context, then simply pass the activity as a parameter to that class and take an instance to that activity inside your class.
public class MyAdapter extends ArrayAdapter { // this is not activity
private Activity mActivity; // activity is a member of this class.
public MyAdapter(Activity activity, List<String> data) {
mActivity = activity;
}
public View getView(...) {
// if you need to use findViewById:
View view = mActivity.findViewById(R.id.some_id);
}
}
Don't use any of your two methods.
I might be misunderstanding your first sentence, but just to be sure, are you asking for a way to access a View that exists in the MainActivity, while you're inside of a Fragment?
If that's what you're asking, then yes, as an Android Developer, there will definitely be moments where we come across this scenario. However, the solution is definitely NOT by making your Views or Context static.
This is one of the easiest ways to cause bugs to appear throughout your app, with a very high chance to cause memory leaks too. Here's an Article from Google talking about memory leaks related to keeping a reference to a Context: https://android-developers.googleblog.com/2009/01/avoiding-memory-leaks.html
Rather than your two options, there are better solutions that developers typically use.
First of all, keep in mind that you should NOT be directly accessing any Views from outside of your current layout... meaning, that if you're in a second Activity, you don't directly access Views from the first Activity, or if you're in a Fragment, you don't directly access Views that belong to it's FragmentActivity.
Instead, you let the Activity or Fragment handle it's own Views.
So for example, if you're in another Activity and you want to update some data in the previous Activity, you can take advantage of an Activity's startActivityForResult() and onActivityResult() to obtain the data necessary to update the Activity immediately upon returning to the app.
For Fragments, there's actually a tutorial from the Android Documentation that describes a very good way to communicate between other Fragments: https://developer.android.com/training/basics/fragments/communicating
This method is to use interfaces as a callbacks, so another Fragment or the Activity will be able to receive data and update it's Views within it's own layout.
So for your case, if you're using Fragments and an Activity, you can easily have your fragments and activities communicate to each other in a safer and more reliable way.
Also, make sure you read up more on static and it's effects on your code, especially the side effects on Android components. Do not carelessly use static without considering some of the effects it might cause, because that would cause an endless amount of trouble to your code.

How to access activity resource from another activity?

I want to change textView(in mainActivity)'s property like textSize, or textColor.
Then I tried to use it at setting activity.
View view = getLayoutInflater().inflate(R.layout.activity_main, null);
readTextView = view.findViewById(R.id.textView);
And It doesn't work.
Also, I tried to How to update a TextView of an activity from another class this answer. But isn't it can only change the text? If I need to change much property, I have to make a method in my activity.
Android access main activity variables from another class
I referenced this answer.
Declare public static the resource which you want to change.
Use like [Your Activity].[The Resource] at your setting Activity.
I really sorry to question like this... Sorry.
You must not using a public variable as a mechanism to update your View inside an activity because of the following:
You can't ensure that the activity is always exist. There is a probability that the activity is killed by system because of error or you're finishing the activity.
You're coupling your activity with another class. So, each time you're changing the activity there is probability that your change propagate to another class. This probably will introduce bugs to multiple classes.
You better strictly access the View from another class by sending only the view as a parameter. For example, if you have the following activity:
public class YourActivity extends AppCompatActivity {
private TextView mTvName;
...
}
to change the properties of mTvName, you need to create something like this:
public class TextChanger {
public static void maximizeTextSize(TextView tv) {
tv.setTextSize(30);
}
}
then you can use it in your Activity:
TextChanger.maximizeTextSize(mTvName);
If you want to update the TextView from another Activity, you can use startActivityForResult for starting the another Activity. Then you need to receive the result to change your TextView by overriding onActivityResult in your activity.
In case you need to update the TextView without any coupling with another class or Activity, you can use Event Bus mechanism. You can use EventBus library.

What's the difference between 'this' and 'getActivity()'?

I have an idea they both get the 'context' so that functions know how they fit into the scheme of things, is this right?
Any clues for the evolving ape?
this is a reference to the current class you are. It can be an Activity, Fragment, Adapter, View, etc. And when you use it what you are doing is just passing a reference of the current object of that class.
Let's say you are working on a custom View. Anywhere in the code of that view where you call this will be interpreted as the View itself, so the value of this changes depending on what class you are.
The method getActivity() is defined only in the Fragment class and any other class extending Fragment and this method returns and Object of the type Activity.
On Android development is very common mixing those two because most of the applications code is in Activity classes, and calling this on an Activity class will return an Activity object but as you can see they are not the same thing.
You can read more here

Pass parameter by reference using intent

Using itent.putExtra makes a copy of my object. So changes make on this object on the activity that recive this itent does no reflect on others activity.
In my case will be good have reference to this object instead a copy, this is possible ?
ps: I know i can use onActivityResult to retrive the changes make on the object, but in my case the changes make on the object need to be done before the end of the activity.
Other way is: set a reference to a common property from activity1 (I am using MyApplication). The activity2 knows where to find that reference via a getter and it will use it. Decide if you want to modify the properties in activity2, when finished / every time you can have the reference in activity1.
This way is not needed to serialize / deserialize the object either. ( performance improvement too)
You can just store a reference to the object in a static member variable, like this:
public class Globals {
public static MyObject myObject;
}
Now, in the code that has the object, you just do:
Globals.myObject = object;
and in the new activity, you can get it like this:
doSomethingWith(Globals.myObject);
Now, having said that, you need to be aware of the following:
Android can kill your process if your application is in the background pretty much any time it wants to. When the user then returns to your application, Android will create a new process for your application and then it will recreate only the activity that was on the top of the activity stack (ie: the one that was showing). In that case, the newly created activity will not be able to get the iobject by accesing Globals.myObject because the process has been newly created and that member variable is null.
You should use an Application class, which you can get a reference to using the getApplicationContext() method.
Bottom line, create an Application class, which you will be able to reference from any class in your App, then you can reference a variable that is local to that class.
Here is a good SO question about this:
Using the Android Application class to persist data

Android Base Activity: Base's Global Variables, Can't get from some activites

I'm taking an android class now, so I am somewhat new to android app development.
My first assumption for a Base Activity is that it's Global Variables and it's values would be available to all activities. I have found that it is available to my Main Activity, but not any activities after that.
In the Base Activity I am storing an ArrayList of Objects. I also load data from an xml in there that adds objects to the arrayList. Once in the Main Activity I still have access to that arrayList and it's values. I use it to fill a list. But when I go to the next activity, it knows about the arrayList but thinks it is empty.
Do I need to create methods in the base activity to retrieve the arrayList and to add objects to the array list?
Any help would be appreciated.
Thank you,
Michelle
Global variables need to be declared static. Then they would be accessible from any class. Example:
public class Globals {
public static String myString;
}
Any class can read/write the myString like this:
Globals.myString = "foo";
or
String bar = Globals.myString;
From experience I believe the variables of one activity is only avaliable to the other while the activity is active, which means between onCreate and onDestroy, other then that you will probably get a null pointer exception, what you really should be doing is sending the data, or arrays, along with the intent to the other activity.
I dont think you should be calling on other activities variables, although it is possible as stated above. I believe when the activity has had it's onDestroy method called the objects in the activity are destroyed to and are removed from memory. Destroying anything that they held.
What is this base activity? Does it just extend activity? And then MainActivity is extending Activity as well? Only one activity is usable at any one time, if your doing what I think your doing you should have a service which can provide you with everything over the cycle of the application, just remember to stop it when your done with it.

Categories

Resources