There are some callback methods in android, like "onCreate" or "onClick".
I have a question about them.
When those callback methods show up in programs,
their parameters are not assigned by programmer.
Should they be assigned first?
For example,
Bundle saveInstanceState = something;
//assign parameter saveInstanceState first. (yet not assigned in real case)
public void onCreate(Bundle saveInstanceState) {
// do something .....
};
or
View v = something;
//assign parameter v first. (yet not assgned in real case)
public void onClick(View v) {
// do something .....
};
All the codes I have read so far don't assign "saveInstanceState"(of onCreate) or
"v"(of onClick) by the programmers.
Does that mean "android will assign those parameters of callback methods itself"?
If so, are all parameters of all callback methods the same case?
For example, "data and camera in onPictureTaken(byte[] data, Camera camera) {};",
are they assigned by android system automatically and programmer doesn't need to assign them?
I can't find relative details in android developer website so far.
If a parameter is assigned by system, not by programmer,
why is there no relative guideline or note about that in android developer website document?
Thanks for reply.
The parameters of a function are assigned by the caller of the function. Example:
int x = 0;
public void test(int x)
{
System.out.println(x);
System.out.println(this.x);
}
test(2);
//prints
//2
//0
So in your case
View v = something;
//assign parameter v first. (yet not assgned in real case)
public void onClick(View v) {
// do something .....
};
v and this.v would reference different objects inside the onClick method body.
Related
I've read hundreds of explanations on "this" in java and I'm really having trouble grasping it. I'm learning android and java side-by-side, I know it's harder that way but I'm enjoying it. The one thing I'm getting killed on is "this"... I'm pasting code from a tutorial below that utilizes "this" one time. I was going to just put a piece of the code but want to be as helpful as possible.
I'm looking for a good explanation of "this" that I can add to my notes. Any and all help is appreciated. Thanks in advance.
example code starts below:
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
import android.view.View;
import android.content.DialogInterface;
import android.app.Dialog;
import android.app.AlertDialog;
public class DialogActivity extends Activity {
CharSequence[] items = { "Google", "Apple", "Microsoft" };
boolean[] itemsChecked = new boolean [items.length];
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void onClick(View v) {
showDialog(0);
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case 0:
return new AlertDialog.Builder(this)
.setIcon(R.drawable.ic_launcher)
.setTitle("This is a dialog with some simple text...")
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
Toast.makeText(getBaseContext(),
"OK Clicked!", Toast.LENGTH_SHORT).show();
}
}
)
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
Toast.makeText(getBaseContext(),
"Cancel clicked!", Toast.LENGTH_SHORT).show();
}
}
)
.setMultiChoiceItems(items, itemsChecked,
new DialogInterface.OnMultiChoiceClickListener() {
public void onClick(DialogInterface dialog,
int which, boolean isChecked) {
Toast.makeText(getBaseContext(),
items[which] + (isChecked ? " checked!":" unchecked!"),
Toast.LENGTH_SHORT).show();
}
}
).create();
}
return null;
}
}
this refers to the current Object's reference.
Read this for more understanding.
To give an example from the link:
public class Point {
public int x = 0;
public int y = 0;
//constructor
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
Here, to differentiate from the x of the Point and x of the argument, you need to tell the compiler the difference. You achieve that using this. Meaning, when I write, this.x it means, the particular x belongs to the current Object, which in the case is Point.
Taking example from the code that you have provided:
AlertDialog.Builder(this)
AlertDialog.Builder() takes in a Context as a parameter in its constructor. But here, you don't do Context someContext = new Context(); and pass that as the parameter, because you simply need to pass your current Activity's Context. So you simply use this.
Think of this as "itself". If you pass this to a method, you're simply passing an instance of the object to the method.
ie: Student is an object, as is Classroom. If I want to add a Student to the Classroom, I might tell Student to add itself to the classroom (classrooms can't find students, can they?). So, I will say student.addToClassroom(new Classroom(), this);
The keyword this, like others have said, is just a reference to the current object. This is usually implicit, such that if you have a class as so:
class ThisExample{
int x;
public ThisExample(int x){
this.x = x;
someMethod();
this.someMethod();
}
void someMethod()
{
...
}
}
Using this.x = x helps to differentiate between the member variable owned by the class and the variable being passed into the constructor. Also, calling this.someMethod() and someMethod() does exactly the same thing because the this is implied.
In Android, sometimes you will see a method with this being passed in like someMethod(this). What happens here is that this is referring to the current Activity's Context, which is just a bunch of information explaining everything about the Activity.
Ok I'll see how I go :P
Think of a Java object (class) as an individual entity, which has certain things which define what it IS (properties) and certain things it can DO (methods)
For example, take a (very abstract) class named Machine
class Machine {
Piston piston1;
ArrayList<Gear> gears;
public void addSomeNewGears(ArrayList<Gear> gears)
{
for(int i = 0; i < gears.size(); i++)
{
this.gears.Add(gears[i]);
}
}
}
In the Method addSomeNewGears we actually have access to TWO Lists named gears:
The Machine object's current gears,
The new ones we want to add.
Because they are both called gears it can be ambiguous as to which one we want to access, however the new List will take priority as it is declared locally in the method.
To access the Machine's gears, we need to use the this keyword, which tells the compiler we are looking for the class's gears, not the method's
Hope this helps!
Instance methods (those not declared static) of a class can only be executed by reference to some instance of the class. For example:
class Foo {
public void doSomething() {
// "this" refers to the current object
. . .
}
. . .
}
// then later:
Foo aFoo = new Foo();
aFoo.doSomething(); // "this" will be equal to "aFoo" for this call
// The following is illegal:
doSomething();
// so is this:
Foo.doSomething();
Inside the method doSomething(), the variable this refers to the specific instance of Foo that was used to invoke the method (in this example, the current object referenced by aFoo).
this is none other than the reference of current object. this will be very useful to identify that the members belongs to the current class.
For example,
Class Sample{
int a;
Sample(int a){
this.a=a;
}
}
"this" will differentiate current class variable and other variable
Can I break the set-listener line into smaller pieces?
Here is the code I have:
protected void onCreate(Bundle savedInstanceState) {
Preference button = (Preference)getPreferenceManager().findPreference("exitlink");
button.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference arg0) {
finish();
return true;
}
});
I would like this to look something like:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Preference button = (Preference)getPreferenceManager().findPreference("exitlink");
if(button != null) {
button.setOnPreferenceClickListener(onPreferenceClick);
}
}
public boolean onPreferenceClick(Preference arg0) {
finish();
return true;
}
You can also create a variable outside of your method:
private Preference.OnPreferenceClickListener listener = new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference arg0) {
finish();
return true;
}
};
Then you use it as a variable: setListener(listener). This would allow you to have multiple instances of the same listener class in your Activity.
Your code above nearly works already. Use your above code with this tiny change:
button.setOnPreferenceClickListener(this);
Then you just let your class implement the specific interface needed, in this case Preference.OnPreferenceClickListener.
In addition to dmon's suggestion below about using variables for this, it is also possible to write a function that returns a listener, which is very useable when you want to have similar listeners but with slight changes, like in the example below.
private Preference.OnPreferenceClickListener getListener(int listenerId) {
return new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference arg0) {
Log.i("MyTag", "Listener " + listenerId + " invoked!");
finish();
return true;
}
};
}
As others have mentioned, even though you cannot pass a method name to setOnPreferenceClickListener you can create a variable of a type that extends Preference.OnPreferenceClickListener. In your original code, that is actually exactly what you are doing: you are creating an object of an anonymous inner class.
The advantage of this approach, say over Simon André Forsberg's answer above is of scope: it keeps the listener functionality in that small block, instead of potentially all over the class.
Creating a separate variable outside the method as in dmon's answer loses one big benefit of the anonymous inner class, that they can access the variables in the containing scope: in your original code, the listener can access the variables button and savedInstanceState. This is not possible with a separate variable defined outside the function.
None of this means that you must use anonymous inner class. Oracle has an excellent tutorial titled General Information about Writing Event Listeners that you will greatly benefit from.
Not exactly. The set-listener requires an instance of listener, so you always need to create one. And I don't think it's a good manner for activity implementing listener interfaces.
The workaround is that you can use annotations with reflection, such as http://code.google.com/p/roboguice/. This may make the code cleaner, but also introduces dependencies.
I've read hundreds of explanations on "this" in java and I'm really having trouble grasping it. I'm learning android and java side-by-side, I know it's harder that way but I'm enjoying it. The one thing I'm getting killed on is "this"... I'm pasting code from a tutorial below that utilizes "this" one time. I was going to just put a piece of the code but want to be as helpful as possible.
I'm looking for a good explanation of "this" that I can add to my notes. Any and all help is appreciated. Thanks in advance.
example code starts below:
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
import android.view.View;
import android.content.DialogInterface;
import android.app.Dialog;
import android.app.AlertDialog;
public class DialogActivity extends Activity {
CharSequence[] items = { "Google", "Apple", "Microsoft" };
boolean[] itemsChecked = new boolean [items.length];
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void onClick(View v) {
showDialog(0);
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case 0:
return new AlertDialog.Builder(this)
.setIcon(R.drawable.ic_launcher)
.setTitle("This is a dialog with some simple text...")
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
Toast.makeText(getBaseContext(),
"OK Clicked!", Toast.LENGTH_SHORT).show();
}
}
)
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
Toast.makeText(getBaseContext(),
"Cancel clicked!", Toast.LENGTH_SHORT).show();
}
}
)
.setMultiChoiceItems(items, itemsChecked,
new DialogInterface.OnMultiChoiceClickListener() {
public void onClick(DialogInterface dialog,
int which, boolean isChecked) {
Toast.makeText(getBaseContext(),
items[which] + (isChecked ? " checked!":" unchecked!"),
Toast.LENGTH_SHORT).show();
}
}
).create();
}
return null;
}
}
this refers to the current Object's reference.
Read this for more understanding.
To give an example from the link:
public class Point {
public int x = 0;
public int y = 0;
//constructor
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
Here, to differentiate from the x of the Point and x of the argument, you need to tell the compiler the difference. You achieve that using this. Meaning, when I write, this.x it means, the particular x belongs to the current Object, which in the case is Point.
Taking example from the code that you have provided:
AlertDialog.Builder(this)
AlertDialog.Builder() takes in a Context as a parameter in its constructor. But here, you don't do Context someContext = new Context(); and pass that as the parameter, because you simply need to pass your current Activity's Context. So you simply use this.
Think of this as "itself". If you pass this to a method, you're simply passing an instance of the object to the method.
ie: Student is an object, as is Classroom. If I want to add a Student to the Classroom, I might tell Student to add itself to the classroom (classrooms can't find students, can they?). So, I will say student.addToClassroom(new Classroom(), this);
The keyword this, like others have said, is just a reference to the current object. This is usually implicit, such that if you have a class as so:
class ThisExample{
int x;
public ThisExample(int x){
this.x = x;
someMethod();
this.someMethod();
}
void someMethod()
{
...
}
}
Using this.x = x helps to differentiate between the member variable owned by the class and the variable being passed into the constructor. Also, calling this.someMethod() and someMethod() does exactly the same thing because the this is implied.
In Android, sometimes you will see a method with this being passed in like someMethod(this). What happens here is that this is referring to the current Activity's Context, which is just a bunch of information explaining everything about the Activity.
Ok I'll see how I go :P
Think of a Java object (class) as an individual entity, which has certain things which define what it IS (properties) and certain things it can DO (methods)
For example, take a (very abstract) class named Machine
class Machine {
Piston piston1;
ArrayList<Gear> gears;
public void addSomeNewGears(ArrayList<Gear> gears)
{
for(int i = 0; i < gears.size(); i++)
{
this.gears.Add(gears[i]);
}
}
}
In the Method addSomeNewGears we actually have access to TWO Lists named gears:
The Machine object's current gears,
The new ones we want to add.
Because they are both called gears it can be ambiguous as to which one we want to access, however the new List will take priority as it is declared locally in the method.
To access the Machine's gears, we need to use the this keyword, which tells the compiler we are looking for the class's gears, not the method's
Hope this helps!
Instance methods (those not declared static) of a class can only be executed by reference to some instance of the class. For example:
class Foo {
public void doSomething() {
// "this" refers to the current object
. . .
}
. . .
}
// then later:
Foo aFoo = new Foo();
aFoo.doSomething(); // "this" will be equal to "aFoo" for this call
// The following is illegal:
doSomething();
// so is this:
Foo.doSomething();
Inside the method doSomething(), the variable this refers to the specific instance of Foo that was used to invoke the method (in this example, the current object referenced by aFoo).
this is none other than the reference of current object. this will be very useful to identify that the members belongs to the current class.
For example,
Class Sample{
int a;
Sample(int a){
this.a=a;
}
}
"this" will differentiate current class variable and other variable
I am kind of a newbie so excuse me if this question is too simple or too hard.
I have this code in my java file:
public void button_baby_clicked(View v)
{
//do something here
}
this gets called when someone clicks the imagebutton in my xml file, but how do I call this from the java file itself?
Because it's expecting a View object... and I'm guessing I need to recreate that? How?
Edit:
Ok, to clarify, I want to be able to call the above function via a click in my xml file as well as a function under it.
For example:
public void button_baby_clicked(View v)
{
//do something here
}
public void someFunction()
{
x = 10;
button_baby_clicked(); // This should call the above function.
}
In ur ImageButton you have to add an attribute: android:onClick="button_baby_clicked"
In the java file, you have added:
public void button_baby_clicked(View v)
{
//do something here
}
The logic behind this is:
Upon clicking ur imagebutton, this method will automatically get called, i.e "v" argument will be having ur imagebutton.
The advantage of giving like this is: You no need to initialize the imagebutton in ur activity and no need to set click listener too for this imagebutton.
Alright, if you want to have the method invoked every time the view is clicked, do what the others have said.
Alternatively, you can do something like this.
ImageView globalReference;
#Override
public void onCreate(Bundle icicle){
*** CODE ***
globalReference = (ImageView) findViewById(R.id.myImageView);
*** CODE ***
}
Then, whenever you want that to be called with that particular View, simply call
button_baby_clicked(globalReference);
You can also do this with any View object you create dynamically.
View myTv = new TextView(context);
View myLl = new LinearLayout(context);
button_baby_clicked(myTv);
button_baby_clicked(myLl);
Just get a valid View reference within the same scope as the method, and pass it in like any other method. It can even be null if the method is capable of handling it.
Can't you use it like -
mButton.setOnClickListener(new OnClickListener{
#Override
public void onClick(View v) {
button_baby_clicked(v);
}
}
);
??
EDIT :
If you need to call someFunction() from the onClick of a button,and from there,you need to call button_baby_clicked(),you have to get View v object in someFunction. This link might help you. Please refer Start a service on onClick. You can change appropriately.
I believe its best if you refactor your code and put the code in the event handler into a global method that can be called from anywhere. like this:
public void button_baby_clicked(View v)
{
taskToPerform(); // Perform a certain task
}
public void someFunction()
{
x = 10;
taskToPerform(), // Perform the same task again
}
public void taskToPerform()
{
//This is where you write the task you want to perform
}
This way you can reuse the code in the taskToPerform() method anywhere, anytime.
I am really struggling with linking menus together. The app I want to create os a collection of menus that leads to url links to various sites I plan to open within the application. I have created a list activity menu with 8 options and I have eight classes with further options. My problem is how to link the menus together.
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
// Create an array of Strings, that will be put to our ListActivity
String[] names = new String[] { "P", "Ch", "Le", "Le", "B", "Sk", "Awa", "Tra"};
// Create an ArrayAdapter, that will actually make the Strings above
// appear in the ListView
this.setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_checked, names));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
// Get the item that was clicked
Object o = this.getListAdapter().getItem(position);
String keyword = o.toString();
Toast.makeText(this, "You selected: " + keyword, Toast.LENGTH_LONG)
.show();
}
}
At the moment all this does is print the selection using the toast method but how do I get it to switch to the p.java class when I have selected it. In basic I would take the names variable and say if names = p goto p.java, I have googled and although I get part of the answer I cannot figure out how to implement it.
Many Thanks In Advance.
I suspect that rather than a class, what you want is an instance of the class in question. One way to do that would be with a Map:
Map<String, Runner> runners = new HashMap<String, Runner>();
runners.put("P", new P());
runners.put("Ch", new Ch());
// etc.
(where Runner is an interface that all your classes implement). Then, inside your onListItemClick() method, where you have the toast:
runners.get(keyword).run();
(where run() is the method you want to launch).
Update (to address your comment)
It's hard to say exactly where to place which bits of code, but based on your question:
You could make runners a field in your Activity, and initialize it in your same onCreate function. So that part's handled.
The Runner interface could be as simple as this (in its own file):
public interface Runner {
public void run();
}
and each of your classes (P, Ch, Le, etc.) would have an implements bit in the constructor:
public class P implements Runner {
And would have to include a run() method (which could simply call whatever existing method you want called for the URL):
public void run() {
// do whatever you want done here
}