How create a global function to initiallize all UI widgets in android - android

I am new to android . My application contains several activities and each activity view contains several widgets. So at onCreate callback I am initiallizing all widgets like (TextView) findViewById(R.id.txt_id) and this is required in almost all activities and it is lengthy too. Since it is more like a common process in all activities , is it possible to create a function globally to perform this widget initiallization , and call this from activities with corresponding layout?

If all this widget have similar name, you can create BaseActivity class and replace all this thinks in onCreate of BaseActivity.
If all this widget different, you can try to use AndroidAnnotation
For example, if you want to inject some view in your activity:
#EActivity(R.layout.activity_main)
public class MainActivity extends AppCompatActivity {
#ViewById(R.id.txt_id)
TextView text; //Must be default, protected or public
#AfterViews
void initViews() {
//Start point, where you can use injected Views, NOT IN onCreate();
text.setText("Some text");
}}

Related

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 is the correct way to define a BaseActivity

This Question i specific to Android and the use of a Base Activity that can be extended by all other Activities. In general w.r.t Java i understand the use and functioning of abstract classes. I my case i have a Base Activity with some common constants ,functions and implements some Interfaces. My Question is should it be abstract or can i leave it as a normal Activity. Is there a specific reason for it to be abstract.
//Standard BaseActivity
public abstract class BaseActivity extends Activity {
//common code
}
//Usage
public class MyActivity extends BaseActivity {
}
This also seems to work if i defined BaseActivity as follows
//Non Abstract Class
public class BaseActivity extends Activity {
}
Hence the question is there a specific reason to use abstract.
In both cases i dont define the BaseActivity in Manifest.
You can refer the following way for defining a BaseActivity.
It’s always been a good idea to make a baseActivity in android
project.
What, I am suggesting is to create an activity from android.app.Activity called baseActivity and make the 3 custom activity to extend from baseActivity.
For example,
public abstract class MyAppBaseActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
And your custom activity
public class MyCustomActivity extends MyAppBaseActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
Notice that, MyAppBaseActivity is an abstract class. The reason is, we are not going to instantiate it. That’s why you don’t need to add the MyAppBaseActivity class in AndroidManifest.xml file.
Now the question is, why would you do that? Means, why you need to
make an baseActivity class and then make your other activities as a
subclass of it?
Well, here are few very generic reasons
1. You can avoid code duplication of you application wise common ui tasks. Suppose you want to show progressDialog in different activities. Just write code to show a progressDialog in your baseActivity and call that method from other activity.
2. Your application menu should be consistent across different application. For example, you have a settings screen. Option menu is containing the navigation to settings screen. You should display the settings throughout the application, means regardless of activity. User want to access the settings screen from anywhere in application. This feature can be easily achieved, but you have to override onCreateOptionsMenu in each of your activity or, you can override it once in your baseActivity.

Inheritance between activities in Android

I am having trouble applying the concept of inheritance to Android Activities - eg.
ActivityA extends Activity and
ActivityB extends ActivityA , then if I launch with ActivityB then onCreate() method for both Activities (A then B) is called .
My question is, in typical Java , onCreate from ActvityA should be over-ridden - but onCreate is rather behaving as a constructor even though its a function. How does inheritance work in Android, esp. wrt other functions like onPause(),onResume etc. ?
EDIT: I also noticed that ActivityA may have many abstract methods called in its onCreate() whose definitions are provided in ActivityB. How does this work ?
If you have your base Activity and then extend it like so Activity -> Activity A it means that when your onCreate of Activity A is called and you call super.onCreate(); then the onCreate() method of the original Activity is also called.
If you then extend Activity A into Activity B the calls work like so...
Activity B.onCreate() - super.onCreate();-->Activity A.onCreate() - super.onCreate()-->Activity.onCreate().
Its not a constructor, its a method thats called to create the Activities. If you then extend them from other Activities its superclass is going to be called via its super method. It doesn't mean that the Activities you have inherited from are going to be created too. Activity B will be your created Activity.
EDIT: This page on the Android Developer website is very useful as it visually explains the Android Activity lifecycle.
Yes as a typical java function onCreate should have been inherited but it doens't get : why? - because it's not just a method, it's a life cycle stage.
AFAIK, Activity is not just a java class but it's a special type of a JAVA Class which has it's own life cycle and Life Cycle stages are meant to be called each and every time you use that class/activity even if you have declared or not those methods onCreate(), onPause() etc gets called for sure.
So every time the base activity will get created and destroyed. That's it's nature.
If you have problem with that you can try using Abstract classes, Interfaces and any other public class to have common code inherited in your all activities.
How does Inheritance work in Android?
There nothing special about Android. It works exactly as it should.
Example?
Lets create a BaseActivity which listens to a BroadcastReceiver (SCAN_RESULTS_AVAILABLE).
So common functions are,
Register a BroadcastReceiver in onCreate()
Unregister a BroadcastReceiver in onDestroy()
BaseClass:
public class BaseActivity extends AppCompatActivity{
private WifiScanReceiver wifiScanReceiver;
#Override
public void onCreate(Bundle sis)
{
super.onCreate(sis);
// Don't call setContentView() because no layout is needed
}
#Override
public void onDestroy(){
super.onDestroy();
unregisterReceiver(wifiScanReceiver);
}
private void registerMyReceiver(){
wifiScanReceiver = new WifiScanReceiver();
registerReceiver(wifiScanReceiver, new
IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
manager.startScan();
}
}
Child class:
public class BlahBlahActivity extends BaseActivity{
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState); // this will call BaseActvity method which will call AppcompatActivty method
setContentView(R.layout.yourlayout);
}
}

android how to create my own Activity and extend it?

I need to create a base class that extends Activity which does some common tasks in my application and extend my activities from it,in the following form:
public BaseActivity extends Activity{....}
public SubActivity extends BaseActivity{...}
in SubActivity I need to give values to some variables and UI components defined in BaseActivity, I may need to define a different layout for SubActivity according to some flag value, also(in SubActivity ) I want to execute asyncTask that is defined in BaseActivity.
is this possible? if yes, is there any tutorial that may help?
thank you in advance
What exactly are you trying to achieve? Having two different activities with a common ui, except for some variables or parts of the layout?
In this case, I suggest having a base abstract activity, and two concrete inherited subclasses. You define all the common behaviour in the base activity, and have abstract methods for the differences, which you then override in your actual implementations.
For example, for two activities with different layout resources:
public abstract class BaseActivity extends Activity {
#Override
public void onCreate(bundle) {
super.onCreate(bundle);
setContentView(getLayoutResourceId());
}
protected abstract int getLayoutResourceId();
}
public class Activity1 extends BaseActivity {
#Override
public void onCreate(bundle) {
super.onCreate(bundle);
// do extra stuff on your resources, using findViewById on your layout_for_activity1
}
#Override
protected int getLayoutResourceId() {
return R.layout.layout_for_activity1;
}
}
You can have a lot more abstract methods, for every bit you want specific to your subclasses.
Doing that is, in my opinion, a lot better than having a concrete subclass to a concrete superclass: that can lead to many problems and is usually difficult to debug.
This question already has very good answers.
However. my answer is for those people who are looking for some working example.
Here is the full working -> CODE
We are not doing anything new here, it is just like any other inheritance scenario (You want some common behavior at multiple places but you want to write that behavior only once).
ADVANTAGE:
It does provide better code readability, maintainability and blah blah. But are not after these -ibility, They won't matter to you if your brain runs like a gazelle.
We are after the real power of inheritance “CONTROL”. (That’s what happens in real life too. Parent controlling child :) ) .
In my example, I have two Activities MainActivity and OtherActivity.
Both Activities has a different layout but I want both of them to start with some animation or some welcome message.
Our first task is to find out the common behavior.
here -> Start Activity with animation.
We have found the common “thing”, now we will write that behavior in BaseClass (AnimationActivity).
MainActivity and OtherActivity will inherit AnimationActivity.
So the code would look like `
BaseActivity
AnimationActivity {
startAnimation()
{
....
}
}
Child Activities
MainActivity extends AnimationActivity{
}
OtherActivity extends AnimationActivity{
}
This design approach provides a lot of Control and Flexibility (POWER OF MODIFIER).
1) CONTROL: Keep animation method inside onCreate()
When you decide that Activities should be started with Animation.
Keep your method inside onCreate(Bundle bundle) method. Now just by changing the modifier, you can control the child Activities.
If you keep modifier as
final: Child activities will start with parent Animation.
abstract: Child activities will have to give their own animation.
no modifier: Child activities can have their own animation by overriding animation method, Otherwise the child will have parent animation.
2)Flexibility: Don't keep animation method inside onCreate()
You can provide child activities flexibility by not keeping animation method inside onCreate(Bundle bundle).
Now activities can have the flexibility to have parent Animation or their own animation or no animation at all.
Hope it helps.
Happy learning.
`
Yes you can, you should just keep in mind the basic inheritance rules. You will inherit the inner AsyncTask activity and the properties defined in the BaseActivity if you make them protected instead of private. From what I see now I think you should make BaseActivity an abstract class, as only instances of subActivities will be really used.
You should just start and try it, it'll come and work easier than you think. If you stumble upon any problems, just ask.
I have found an easier way to #Guillaume's solution. Set ContentView only once in your BaseActivity and do not set it in the activities that extend it:
public abstract class BaseActivity extends Activity {
#Override
public void onCreate(bundle) {
super.onCreate(bundle);
setContentView(activity_main);
}
}
public class Activity1 extends BaseActivity {
#Override
public void onCreate(bundle) {
super.onCreate(bundle);
// setContentView(activity_activity1) // Do NOT call this.
}
}

How to always run some piece of code in android regardless of which activity or service run first in android?

I would like to run a piece of code every time any activity or service is started. In this piece of code, I might do things such as set the default uncaught exception handler and manage log levels.
The problem is that I have an activity which starts with the user clicking the application icon. I have another which starts if a certain intent is broadcasted, possibly from another app and possibly called before the user click the launch icon. Same goes for services.
I need to guarantee that a certain piece of code will be run while keeping the code clean; that is to say, without having to manually add that snippet of code to every activity and service class that I have.
Could you not extend the basic Activity class for Android like this:
public class MyClass extends Activity {
public void onCreate(Bundle bundle) {
//Add custom code here
}
}
Then have all of your actual "Activity"'s in your application extend the custom class?
public class MyInterfaceClass extends MyClass {
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
//Other code here
}
}
That way all your custom code will be called when the Activity starts up.
For an application called Wibble...
public class Wibble extends Application {
protected static void DoSomething()
{
// Do your common code here
}
}
Then extend Activity...
public class WibbleActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Wibble.DoSomething();
}
}
Then derive all activity classes from WibbleActivity...
public class Whatever extends WibbleActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// WibbleActivity calls Wibble.DoSomething()
// so the 'Whatever' class doesn't have to.
}
}
Any Activity derived from WibbleActivity will run Wibble.DoSomething() implicitly.
If you want Services in the mix I can't help - I'm an Android 'rookie' and haven't got on to Services yet but I suspect extending your own app-level Service class might work in the same way.
You could extend Application and do it in its onCreate() method.
You have two choices
A) You can manually add the code - it might be only two lines importing and instantiating something from a source file you copy in unmodified - to every separate component that you write. It will only be in your projects, not in other people's unless they do it too.
B) You can, after no small difficulty, learn to make your own custom version of android that automatically does this each time it starts up a suitable component, and install this customized version on developer phones or hacked consumer phones.
"started" is ambiguous - what are you referring to? onCreate? onResume?
In any case, your best bet is to have a separate class with a static method that does the code you are talking about, and you call that in every single onCreate (or onResume, whichever you need) of each one of your activities.
That, or you create your own Activity subclass and derive all your activites from it, and override onCreate (or onResume). All your onCreate/onResume implementations are required to call the superclass' implementation, so you're guaranteed to have your code caled.

Categories

Resources