I am new to Android development and Software development too.
I keep seeing this term called - 'context' in Android code.
I know that it's a class in android.content package, but I don't understand what exactly is it and why is it needed in so many places, especially in the constructors.
Can someone please explain this term to me.
As the name suggests, its the context of current state of the application/object. It lets newly created objects understand what has been going on. Typically you call it to get information regarding another part of your program (activity, package/application)
You can get the context by invoking getApplicationContext(), getContext(), getBaseContext() or this (when in the activity class).
Typical use of context:
Creating New objects: Creating new views, adapters, listeners:
TextView tv = new TextView(getContext()); ListAdapter adapter = new SimpleCursorAdapter(getApplicationContext(),..);
Accessing Standard Common Resources: Services like LAYOUT_INFLATER_SERVICE, SharedPreferences:
context.getSystemService(LAYOUT_INFLATER_SERVICE)
getApplicationContext().getSharedPreferences(name, mode);
Accessing Components Implicitly: Regarding content providers, broadcasts, intent
getApplicationContext().getContentResolver().query(uri,...);
Its copy from here
Related
In .NET, how does one instantiate or get an instance of Android.Bluetooth.LE.ScanFilter class? It doesn't seem to have any constructors, and in two hours of Googling I have failed to turn up any examples or even mentions of it other than the Microsoft doc class definition. But the class seems to be necessary for calling BluetoothLeScanner.StartScan with any filters on it.
I found what I needed in a Java example, and translating the capitalization conventions this works in C#:
ScanFilter filter = new ScanFilter.Builder().SetServiceUuid(parcelUuid).Build();
Where the Set... calls are setting whichever filter properties are relevant to your case; in my case, obviously, I'm looking for a particular service UUID.
I need to use Toast.makeText(getApplicationContext()). The getApplicationContext() is what I am really after. I need a specific tutorial on passing Context around. Any sugestions? I see alot of developers answering questions with techo-speak like this and I would seriously like to advance to that stage. I have run into passing Context issues way too often and would like a deep understanding of this. Until I get this type of knowledge I will always consider myself a noob.
Thanks.
Do you have a problem with Activity being a Context ? (Activity.this)??
Android already does that for you so why do you want to bother your head.? When you create a View the Context is passed to the View eg; TextView textv = new TextView(Context); you can later retrieve that Context with View.getContext(). Honestly Context are everywhere so why do you really want to use the getApplicationContext(); why not getBaseContext()
I'm just starting Android development, so I'd like a little advice on code style. It seems nice to me to write Intent dispatchers in methods that are doing the dispatching, like
// in case it's not clear, names are meta-variables
public class MyService...
...
public static void sendMessage(Context ctx, MyArgClass myArg) {
Intent sendIntent = new Intent(ctx, MyService.class);
sendIntent.setAction("send message");
sendIntent.putExtra("my_arg", myArg);
ctx.startService(sendIntent);
}
}
then, any callees just run MyService.sendMessage(ctx, arg), instead of having the Intent creation code in their bodies.
It seems like a win: there's less stuff to remember when you want to e.g. sendMessage, and you don't have to synchronize names, like "send message" and "my_arg" across modules. However, I don't see it that often in Google's music app that they've open sourced, so I'm wondering if there are downsides, and I should stick to convention.
It is good practice. This pattern can be found in android developer guides (sample)
Please allow me to answer your question in a more general context, ie programming approach static vs singletin, since these are the alternatives I would consider.
I found that using static solutions for global access to methods, constants, etc.. seems to be a matter of taste.
One commonly used alternative is a singeton approach where you create only one instance of an obejct and use this to access your method. So also in your case you could use a sigleton instead - I have not looked at the Google code you referring to, but I wouldn't be surprised to see a singelton pattern instead.
You may find several discussions on that - but in general singletons allow you to reuse code and control object state much easier than static. The main difference is that singletons can implement interfaces, so you can pass them around.
However, in cases where I just need easy access to some utility methods I prefer static solutions - since they are easier and faster to implement and use IMHO.
This is like having a Utility method to take care of this.
In the example code for GCM from Android, they have done a similar thing.
I've recently been making a very data driven application in which I use a lot of arrays. I've tried searching for a solution, but the problem is quite difficult to word concisely so I haven't been able to find an answer. If there's an obvious one I apologize beforehand.
Currently I load a set of 30 arrays from multiple pre-made databases during an initial class, and I use intents to move this set of arrays back and forth between my classes. The problem is, this results in very long extra sequences of code in every single one of my classes. To give an example, after the initial screen I have to enter the code in every class:
Intent intent = new Intent (getApplicationContext(), NextScreen.class);
intent.putExtra("array1", Array1);
// ... 30 more arrays
and then
Bunble b = getIntent().getExtras();
Array1 = b.getStringArray("array1");
// ... 30 more arrays
I was hoping maybe there would be a way to store all the arrays in some resource or class to just reference later.
I suggest your create a Class that holds all your information , then make this class Parcelable so it can move throught activities : Parcelable example .
Instead of using arrays, create a class with static vector or arraylist.
create setter and getter methods which will update your arrays.
and directly call these methods from multiple classes,you don't need to pass values. just store them in one class, and use the same class, to read write from multiple places
Try using a singleton class. This will be like a "Model" class in MVC patter.
However, exercise caution when using this, as per this discussion:
Singletons vs. Application Context in Android?
I'm looking for guidance as to how to modularize my code. I have an activity and a listAdapter and they are getting pretty complex. I'm not sure what code should live where and how much knowledge each of these 2 classes should have of each other. How do you decide whether to put code in an activity or its adapter? And what patterns do you use to keep these classes as lean as possible?
Your description is too generic, so I cannot give you an exact answer (would be useful to explain why they are getting bigger and bigger, what is the extra code good for).
But generically speaking, just think about what each class supposed to do. The "Activity" (as I see it), is a main controller, it "knows everybody", and it connects the other components together (the ListView with the list adapter). The list adapter's purpose is simply to map data to views. If they are getting bigger, extract new (utility) classes.
For example assume a big part of the code in ListAdapter formats timestamps (eg. takes timestamp as long value, and based on current time creates a string like "2 hours ago"). Then it makes sense to create a new utility class called TimeFormat (with a constructor which takes a context, you'll need it later to fetch string resources). Then the ListAdapter will create an instance of this class.
Another example would be data saving. In that case you could create a class called "Model" or "Document" (again with a constructor taking a "Context" instance). It would be responsible (for example) to load the data by parsin XML files, and to save the data by generating XML files. In this case this class would be instantiated by the activity.
Also note that the ListAdapter should really do what it supposed to do: create/setup views based on data. It should never depend on other views (in other views it should work with any ListView in any layout file). So if you have "findViewById" call, which access a view outside of the ListView (or the ListView itself), then that code should be moved to the activity.
Also, when in doubt you can try to find an open source application, which is relatively mature, and does something similarn (and see how that is solving the problem).
Per the adapater documentation in android
An Adapter object acts as a bridge between an AdapterView and the underlying data for that view. The Adapter provides access to the data items. The Adapter is also responsible for making a View for each item in the data set.
So if your code has to do with getting the data to display or creating the views, then it goes in the adapter. Everything else goes in the Activity or else where. If you're spending a lot of code retrieving the information you want to display, consider using some sort of AsyncTaskLoader class. Note that loader classes can be accessed from API Levels less than 3.0 using the android compatibility package.