Android: Using button from a non-acitvity class in activity class - android

I am wondering if it is possible to access a button from a non-activity class using an activity class? The button is in a different xml file than the one of the activity class.
Also, is it possible to create options menu in the non-activity class?

Whenever you need to access any UI element from a non-activity class, you need to pass the context to your class. A rough method is:
in your activity's onCreate() method:
myInstance.setContext(this);
and in your Class, you have:
Context mContext;
public void setContext(Context c){
mContext = c;
}

I am wondering if it is possible to access a button from a
non-activity class using an activity class?
Yes, it's possible if the non-activity class can access the methods of an activity class. This can be done by passing the reference of an activity to that non-activity class in the onCreate() method. But remember to release that reference and any other reference to the activity Views when the Activity is destroyed, that is when it's onDestroy() method being called.
The button is in a different xml file than the one of the activity
class.
A button that is not added to an Activity's View Tree can be accessed. You can inflate the layout that contains the button and add the inflated View root to your Activity's ViewGroup.
Also, is it possible to create options menu in the non-activity class?
Yes, it's possible if the non-activity class can access the methods of an activity class.

Anyone can correct me if I'm wrong. But my assumption answer to your question and how I understand what you trying to achieve. Android has made it easy to access controls in other xml files. You have the < include> which you can include other non-activity(fragments) in your activity. Actually it's pretty easy to do this that is the first way to do it. I know they is another way still playing around with your xml files. There is resource to bring non-activity controls to activity layouts with having to do much programmatically. Look at resources available to you on your layout builder.

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.

What context to use in Multi activity android app?

I'm badly confused and hope to get your help understanding this concept.
I have an app with 3 activities, splash, login and main and the main activity is a multi fragment drawer activity that uses sqlite.
In my fragments i need to use context many places. I used to have a static context in my main activity defined and passed that around but in another questions someone suggested not to use static context to avoid leaks and i took the advice.
I had to change a few things and got things working. I use getapplicationcontext() but now my application now consistently crashes. The crashes are more prominent when the app is put in background.
My question is, which activity's context should i be using to start with? Splash? Login or main? How would you get access to the context in resume?
Thanks
If you are in A fragment you can use getActivity() to access its container activity context.
If you are try to access activity context from an adapter class or dialog, you must pass the activity context to the constructor of the adapter class or dialog
If you are in an activity you can use this or yourActivity.this as per the situation.
For example
1)If you want to access activity context from onResume() or onCreate() you can simply use this.
2)If you are try to access activity context from an inner class like retrofit call then you must use yourActivity.this for activiy context

android - Why should I implement interface while communicating between main activity and fragment

I do not understand something. Now, I am reading the documents in android developer site and there, it is written that in order to communicate with fragments, I should implement interface. However, now I can easily access the widgets, exist on fragment, in Main activitiy class.
For example, in main activity class, by issuing following line, I can access fragment´s TextView.
TextView t1 = (TextView) findViewById(R.id.t1);
In this condition, why do i need to implement interface? (forgive my ignorance and thanks)
On Fragment, how do you access a method of the Activity it is attached to? You could call getActivity() but that will only give access to the methods available to the parent Activity object, not your implementation of it with your own custom methods.
To access those custom methods, you need to tell Java that you know that the particular Activity you want to get is the one you created, lets call it MyActivity, which obviously extends Activity or some other implementation of it like ActionBarActivity. In this case you can call ((MyActivity)getActivity()).myMethod();
The problem now is that you are coupling your fragment to that particular activity. By doing so, you won't be able to use your fragment with any other activity in your project because that particular fragment will be looking for MyActivity.
So instead, you declare myMethod() in an interface and make your Activity implement it. If in the future you need to use the fragment with another Activity, all you have to do is make it implement the interface as well.

use android:onClick with methods from another activity?

I have menu xml which included in my activities, im using onClick attribute instead of binding on every startActivity.
My question is, how can I define on the xml onClick attr to call methods which is located on my mainActivity for example?
I thought about something like android:onClick="mainActivity.doSomething" but its doesnt work.
Using onclick in xml is a bad idea. The fact is it only tries to find the method that the current class is in which is using it. One way to do this IF you really want to do it this way is:
startActivity:
public void callOtherMethod(){
mainActivity.doStuff();
}
mainActivity:
public static void doStuff(){
//dosomething.
}
startActivity.xml:
android:onClick="callOtherMethod"
Your doStuff method must also be static, unless you can get a instance of the target method Activity.
I thought about something like
android:onClick="mainActivity.doSomething" but its doesnt work.
It's normal, Android looks for the onClick method declared in the xml layout only in the current activity where that layout file is used(and it wouldn't make sense anyway to look in other activities as those activities could be well destroyed when you call that method).
My question is, how can I define on the xml onClick attr to call
methods which is located on my mainActivity for example?
You should explain what you're trying to do. Accessing methods of an Activity from another Activity should be avoided, it's not the proper way of doing things in Android.

Android - Parent activity should determine what child activity had called it

I have 2 activities in my project, lets say Activity A, and Activity B. Both A and B extend the same superclass: BaseActivity.
We know that in this case, lets say if the Activity A is opened, then the superclass method onCreate() is called, and then the Activity A's onCreate() follows.
Being in the onCreate() method of the parent BaseActivity class, how can I determine which child activity has been started?
I would suggest a different approach. Basically don't do inheritance. Use composition instead. Remember most operations that you think you need to extend for really just need a reference to the context. Activities extend from context. So really you can provide most base functionality in any class that has reference to an active context. No need to do inheritance at all.
So if you want to share some functionality between ActivityA and ActivityB just put it in HelperC
HelperC.someOperation(Context c, otherParams)
HelperC can do anything that some base activity could do. Ultimately the base activity will never exist any way. It will always be an instantiated version A or B
I don't think you should do it this way.
As far as I remember the idea of extending, superclass method should contain only universal code. Puttin the differenting code in child classes would be much easier to do and as I believe more proper.
You can initilize some values in parent onCreate(), and then re-set it in childs'.

Categories

Resources