Guys I have watched tutorial on YouTube about android it has 200 videos but didn't explain what is Bundle, View and Context.
1st question what is Bundle?
2nd question what is bundle inside onCreate method where that come from? what inside that bundle?
3nd question what is Context? what I found is that Activity extends Context, so is it right to say that Context is the activity itself? or the Context of that activity?
4th question what is View? what I found is that TextView extends View and other widgets like Button EditText extend TextView so it means they also extends View.
I also found that the syntax of Button, EditText and other widgets is this...
TextView(Context);
Button(Context);
EditText(Context);
so my assumption here is that "Context = Activity = Screen" and that "View = Button = TextView = EditText"
so in this example
public Example extends Activity{
onCreate(){
Button buttonObj = new Button(this):
}
}
Button buttonObj = new Button(this);
"this keyword" here is refering to the Example class which extends Activity. Is this code here basically says "put this Button which is View inside the Context which is Activity which is the Screen"?
If I am right then why Activity passed inside Button? because it makes sense if button is passed inside Activity.
5th question what happen here?
add.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
//code here
}
});
What is new View.onclickListener() ?? is this a static method that returns an object who implements onClickListener??
Can you also suggest good books in learning android?
Bundle ~ a Bundle is a collection of data. When an Activity starts (via onCreate), the Android OS (or you!) can pass off some extra data to this activity via this bundle. Do you know what a HashMap is? A bundle is a glorified hashmap in that supports multiple different types.
OnCreate Bundle ~ This bundle comes from Android. Honestly, don't worry about it too much. If you want to start one activity from another, you use an intent (do you know this yet?). As such, you can "bundle" data into the intent (using the setExtra methods). This data from the intent will be included in this onCreate bundle, and you can access it through there.
Context ~ your running application and anything associated with it. When you run your application, everything associated with your application is referenced by this context. All of you activities, views, resources, EVERYTHING is associated with the context. Think of it as the word defines: It is the context of your application. Every application has a unique context.
View ~ A view is anything that can be drawn on screen.
OnCreate():
The entire lifetime of an activity happens between the first call
to onCreate() through to a single final call to onDestroy().
An activity does all its initial setup of "global" state in
onCreate(), and releases all remaining resources in
onDestroy(). For example, if it has a thread running in the
background to download data from the network, it may create
that thread in onCreate() and then stop the thread in
onDestroy().
OnCreate method is called when the activity is first
created. This is where you
should do all of your normal
static set up — create views,
bind data to lists, and so on.
This method is passed a Bundle
object containing the activity's
previous state, if that state was
captured.
Views:
The visual content of the window is provided by a hierarchy of views — objects derived from the base View class.
Each view controls a particular rectangular space within the window. Parent views contain and organize the layout of their children. Leaf views (those at the bottom of the hierarchy) draw in the rectangles they control and respond to user actions directed at that space. Thus, views are where the activity's interaction with the user takes place.
For example, a view might display a small image and initiate an action when the user taps that image. Android has a number of ready-made views(Widgets) that you can use — including buttons, text fields, scroll bars, menu items,check boxes, and more.
I would suggest that you look at some text based tutorials rather than video as it will be easier to look at things and reread when you are confused.
I'll get started to help you with figuring out what these terms means.
Bundle - not super important for you to understand. When an activity is called, you can add things to your bundle to be sent to the next activity so that the new activity has the information you want.
Context - each activity has its own context and its important to have a basic understanding of it. Your first applications will have one activity (or class) from which everything is done. In this case you only have to worry about the "this" context which means the current active activity. But if you use an application with multiple activities, some may be active and others not. The context tells your app which of the activities is requesting an action, such as showing text or an image on the screen.
Views are your basic UI elements. They can be simple like TextViews (just shows text), Buttons, or more complex like a layout which organizes the other views.
For your example :
public Example extends Activity{
onCreate(){
Button buttonObj = new Button(this):
}
}
Example is the name of your class which uses the Activity resources.
When the activity "Example" is started it calls the onCreate method first.
It then creates a button object that you can "attach" to a physical button found in your layout file.
The setOnClickListener method is used to ready your activity for a button click. The code that goes into the onClick section is what will happen if the user clicks the button.
If you want to get into android programming, you really should first read the FAQ on this site. You should only be posting answerable questions not asking for opinions such as what's a good book. Hundreds of people have already asked that question and if you can't do a simple google search, you might want to wait on learning to program.
But I"m nice so here are some online tutorials that will get you started and explain some of the things you are confused about:
http://developer.android.com/guide/index.html
http://www.codeproject.com/Articles/102065/Android-A-beginner-s-guide
Related
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.
I'm not sure the best way to go about what I intend to do. I have an app that involves three fragments, each navigated to by a single activity that has a navigation drawer.
I have a text to speech class that initialises the text to speech engine. The problem is, is that it needs to be used by multiple different fragments. My idea was to create an object of the TTS class in the main Activity and extend functions so that they can be called by the fragments, like so:
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mTextToSpeechService = ((NavigationActivity)this.getActivity()).GetTextToSpeechService();
}
The problem I see here is, what if I need to do something such as change the language within one fragment. That would mean I'd have to expose another function to set the TTS class within the activity, which doesn't seem right.
What is the best way to go about this?
There are three options:
Inherit from application and store singleton there. You can see how to do that here.
Create started service and use it from activity.(not bounded) See the link.
Store language setting in SharedPreferences and apply them to textspeech engine in activity lifecycle methods (onResume method).
Services are designed for tasks which are not connected to UI. If it's too much work to be done you may find third option to be a candidate for this particular problem.
I'm currently adding accessibility as a new feature inside my app.
My goal is that the user would be navigating it using the TalkBack service integrated by Android.
Everything is working well, since I'm setting content description on the elements that are inside my activity layout i.e.
<View
style="#style/custom.style"
android:contentDescription="#string/my_string_value"/>
This way, every time that my activity is displayed the TalkBack is reading the content description value.
I haven't had the same success using just one activity which is pushing several fragments on it. So if I try to set a content description on any element inside the fragment layout this is not gonna be read (automatically) till it detects a touch event (I'm expecting to the TalkBack does it automatically, just like the views that are in the activity layout)
In order to get a result as the one that I expect I this this inside the fragment class:
public abstract class myFragment extends Fragment {
...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
...
myCustomView = (LinearLayout) rootView.findViewById(R.id.duende);
myCustomView.requestFocus();
}
}
This haven't had success so far, same thing setting the accessibility as a content changed.
getWindow().getDecorView().sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
Does anyone had faced a similar issue?
Not sure your still looking for the solution but for future seekers :) -
Many times the focus request works only once called from within a post/postdelay function.
Example -
myCustomView.postDelayed(new Runnable() {
#Override
public void run() {
myCustomView.setFocusable(true);
myCustomView.requestFocus();
myCustomView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
}
},1000);
While working with fragments, I like calling both the focuses, input focus, like called by the guy in the previous answer, and the accessibility focus because while implementing accessibility onto fragments you can get pass some irritating problems. hence this always does the job for me.
First, it's important to note that Fragments function no different than layouts within normal activities. Fragments are just a convenient way of structuring the code. What Android/the Accessibility APIs see if you code up your application as a series of fragments, or a bunch of layouts within a single activity is identical. That being said, I believe what you're looking for is the following:
What you need to do is move accessibility focus.
myCustomView.requestFocus();
is moving what I consider input focus. This will have no effect on TalkBack, and is in fact all but completely meaningless, unless you are using keyboard navigation, or we are talking about an EditText box. What you want to do is move Accessibility/TalkBack focus. This can be accomplished with the following line of code:
myCustomView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
NOTE: Please keep in mind WCag 2.0 criteria, especially when it comes to moving focus around on TalkBack users automatically. This can become very confusing for non-sighted users!
I am developing a small A/B Testing library for Android. Library will only be initialised in application class. I need to change TextView values.
I will store all the data fetched from the in a file. But I am not able to track when ever a TextView gets into view and moves it.
For example TextView A is in X Activity, TextView B is in Y Activity and TextView C is in Z Activity. Since the variable I have is Context, how should I change TextView A, B, C values.
I need to figure out which Activity is Visible. From the Activity I will be able to get root view. And I will iterate over child views and change value. But How should i listen to Activity Change.
Is there any other approach to this ?
I know this is possible as many A/B testing library are doing this.
Here you go, check out my answer over Here
As you've mentioned, hooking into the activity lifecycle callbacks via AppContext is the best way to start. From there, you'll have all of the information you could possibly need. Every time the activity switches, you'll have the Activity object, and from there you can get the root view and apply changes as necessary.
I would advise against an iteration over the views though! If you have the rootview, you can just do a findViewId(textview C id) on that root view and you'll grab your view!
Since you are building a library, you can expose a function which can be called after onCreate of each activity, which will give you reference of the activity. Once you have the activity, you can get it's root view and do whatever magic you want to do.
That's the only other approach if you don't want to register LifeCycle callbacks for activity. The application needs to enter your library at least at some point of time. Either you can make the application do manually ( above approach ) or you can override all life cycle events of all activities ( registering lifecycle call back ).
I'm developing an application in which I build a treeView with some data. As the process is quite long I'd like to be able to save my built treeView (a LinearLayout) in some way to restore it when the activity is recalled.
Let's call my activity with the treeview T. I have Home->T->Resource and from Resource I go back Home. I implemented the onSaveInstance in T so there I can save in a bundle the variables I need when from Resource I go back Home and T is destroyed but the problem is that I'm not able to save all the linearLayout as a monolitic information in a bundle, the LinearLayout seems not to be parcelable.
So to summarize my cycle is:
Home-->T-->Resouce-->Home (T is destroyed and onSaveInstance is executed)-->T (I want to avoid the rebuilding of the LinearLayout).
Many thnaks
Don't do this. When you create any View, a layout or otherwise, it uses the inflating Activity's context to get and use system resources and internal app resources. When your Activity is destroyed, this context is no longer active.
If you do manage to save and load the LinearLayout back, you will get a lot of leaked windows, and other crashes, possible including NullPointerExceptions and Dead Objects.
You should always let Android recreate the layout for an Activity if the Activity is destroyed and started up again.
Why not save the resource elements of the 'treeView T' in some ordered data structure such as an ArrayList, HashMap etc... Save this data structure to a SharedPreference/Bundle etc... Whilst building the activity view, create the LinearLayout dynamically by reading the elements from the previously saved SharedPreference/Bundle.
/* Posting an example code below */
LinearLayout linLayout = new LinearLayout(this);
View childView = null; // read this childView in a sequential manner from the sharedPreference/Bundle
linLayout.addView(childView);