- Windows (I happen to be using Windows 7, but any flavor of windows will do)
- Eclipse IDE for Java Developers (v3.5 Galileo)
- Java Platform (JDK 6 Update 18)
- Android SDK Tools, Revision 4
- Create a new Android project (File > New > Android Application)
- Set your project properties
- Project Name: Hello World
- Build Target: Select Android 2.1
- Application Name: Hello World
- Package Name: com.android.test
- Create Activity: HelloWorld
- Press "Finish"
Now you have your project created let's write some code! Your code is located in a file called HelloWorld.java in the src folder. Your screen layout file is main.xml in the layout directory.
Let's take a look at the main.xml (layout) file. Open main.xml. You should now see it in "Layout" mode like this...
and if you select "main.xml" you can view/edit the xml markup
Let's remove the default textview to cleanup our display
- Return to "Layout" mode
- Right click on "Hellow World, HelloWorld!" TextView and select "Remove"
View/edit the XML by clicking on "main.xml"
- Change android:text="@+id/Button01" to android:text="Click Me"
- Save your changes
<?xml version="1.0" encoding="utf-8"?> <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <button android:text="Click Me" android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button> </LinearLayout>Now we have a button let's make something happen when the button is pressed.
- Open "HelloWorld.java" file. There is already code for when the class is created that set's the content view.
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); }
- Add the highlighted code on line #5. Create a button object and reference the button we placed on our layout. After you add the following line of code you will get an error. This is because you need to import "android.widget.Button". The fastest way to import is the hotkey Ctrl-SHIFT-O. This will add all missing imports.
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button button = (Button) findViewById(R.id.Button01); }
- Register a callback to be invoked when this button is clicked. Add the highlighted code in lines #6-#10.
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button button = (Button) findViewById(R.id.Button01); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { } }); }
- Now let's add some code in the method "OnClick" to pop up a message when the button is clicked. Add the highlighted code on line #9.
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button button = (Button) findViewById(R.id.Button01); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Toast.makeText(HelloWorld.this, "Hello World", Toast.LENGTH_SHORT).show(); } }); }
Now let's run our new application.
- Select "Run > Run"
- You will get a dialog "Run As". Select "Android Application"
You may receive "Android AVD Error" if you have not setup an android emulator device.
- Select yes to setup a new Android Virtual Device
- Select "New"
- Create the following new Android Virtual Device
- Name: Android2.1
- Target: Android 2.1 API Level 7
- SD card Size: 4000 MiB
- Leave the rest at the default settings
- Press "Create AVD". Be patient it will take a minute to create your new AVD.
- Select your new AVD and run your application.
NOTE: If you receive an error try the following:
- Try removing "@Override" on line 18.
- change line 15 from "setContentView(R.layout.main);" to "this.setContentView(R.layout.main);"
Complete source for project
HelloWorld.java
package com.android.test; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class HelloWorld extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button button = (Button) findViewById(R.id.Button01); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Toast.makeText(HelloWorld.this, "Hello World", Toast.LENGTH_SHORT).show(); } }); } }
main.xml
<?xml version="1.0" encoding="utf-8"?> <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <button android:text="Click Me" android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button> </LinearLayout>
Download the complete project
If you import the project and receive a Must Override a Superclass Method Error, your targeting the wrong JDK version. Go to my blog post to resolve this error. http://androidcodemonkey.blogspot.com/2011/10/how-to-solve-must-override-superclass.html
Please feel free to post comments or questions. I will do my best to answer your questions.
113 comments:
Eclipse Classic 3.5.1 - http://www.eclipse.org/downloads/download.php?file=/eclipse/downloads/drops/R-3.5.1-200909170800/eclipse-SDK-3.5.1-win32.zip
wow greg ! way to go....!
what is the difference between eclipse 3.5.1 and galileo SR1?
Galileo SR1 is one of many "flavors" of Eclipse 3.5.1.
hey please help me.I done this same tutorial but i am not getting the output.
The output which i got is just the screen like phone and in the black screen it written as ANDROID instead of buttons.Can you suggest me whats the wrong
@Anu I would be happy to try and help. Post your class file and xml layout file. Also, try and copy/paste my code and see if that helps.
Apparently, in the version im using, the second @override makes the program not work, and if its omited, it works! idk why because im just starting, but thats just a tip to others who cant get it to work
On line 17, onClickListener becomes an error. :/
If you are experiencing an error with an @override for onClick (line 18), check your JAVA JDK version. You probably are running JDK 5 versus my JDK 6.
Hey Greg, even Im getting the same problem as of Anu's. Were you able to resolve her problem??
After a long wait it says...Process android.process.media is not responding... HELP!!!
Please mail me on rishabmathur@gmail.com
I would be glad to assist. Please post the relevant code and I will look it over.
Try removing "@Override" on line 18.
Cheers, just figured that out and its all good now, thanks.
Its running fine now except I am having the same issue as anu. It loads the homescreen fine but there is no button to click and there is no way to access the application. Any ideas what might be going wrong.
I get a warning 'This application, or a library it uses, is using NSQuickDrawView, which has been deprecated. Apps should cease use of QuickDraw and move to Quartz.'
But googling that seems to suggest that it can be ignored and does not affect the application.
I think that I may have just solved this problem and this might work for the other people suffering the same problems as me.
change the line:
setContentView(R.layout.main);
to:
this.setContentView(R.layout.main);
That got it all working for me.
@Sam, thanks for sharing your fix to this issue.
I've enjoyed your tutorials to this point, it seemed like everything was going to smooth. I've followed both tutorials
1)How to set up ... and also
2)Hello World
Everything looks identical but when I run HelloWorld I get "Conversion to Dalvik format failed"
Location is unknown
Type is Android Packaging Problem.
Any help available?
if you see ANDROID in the middle of your screen you need to wait until your virtual Device starts up.. took about 1 minute
Thanks !!!!!
It was exactly what i need
I am having issue : OnClickListener cannot be resolved to a type
Am using JDK 6 update 20.
@Dan
Removing the @Override will clear your error.
Description Resource Path Location Type
R.id cannot be resolved HelloWorld.java /Hello World/src/com/android/test line 16 Java Problem
The method onClick(View) of type new View.OnClickListener(){} must override a superclass method HelloWorld.java /Hello World/src/com/android/test line 19 Java Problem
Unparsed aapt error(s)! Check the console for output. Hello World line 1 Android ADT Problem
Please help me, I have tried reinstalling everything three times.
I keep getting these errors
http://img153.imageshack.us/i/helpi.png/
@Curtis
For the first error make sure you have a button Named "Button01" on your view.
For the second error remove the @Override just above the error.
If that doesn't solve your issue email me your zipped up project.
Please email me at Rfah614M1BbM@meltmail.com so I can get your email address, I really appreciate all the help you are giving me and other users :).
Here is a screenshot if you'd prefer to help me through comments :)
http://img199.imageshack.us/f/thankyouy.png/
To solve this "OnClickListener" error, cross verify the import items in your code, with the source code that is posted here.
Hi Greg,
I'm trying your Hello World example but just get the 'Android' text on the screen. I've also tried another sample (flashlight) from the internet, nothing goes on the screen.
My code is:
package com.android.text;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class HelloWorld extends Activity {
/** Called when the activity is first created. */
/*@Override*/
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main);
Button button = (Button)findViewById(R.id.Button01);
button.setOnClickListener(new OnClickListener()
{
public void onClick(View v) {
Toast.makeText(HelloWorld.this, "Hello World", Toast.LENGTH_SHORT).show();
}
});
}
}
My main.xml:
android:text="Click Me" android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content"
Thanks for looking at this.
I'm using Eclipse 3.5 on windows xp.
Anne
Greg,
I got it working, turns out I need to wait about 5 minutes, then the button and text appear.
Anne
@Anne,
Glad you got it working.
Had a similar issue with incorect Arguments for OnClickListener. Needed to more fully specify this as View.OnClickListener.
Changed line 17 from:
button.setOnClickListener(new OnClickListener() {
to
button.setOnClickListener(new View. OnClickListener() {
Hey, I've did all the steps. But in File->New
No new android project menu found. Please help..
hi,
i am new in android developers,
i had done my own programme, in which i include 1 button, 1 text, 1 edit box, but i got 1 error
"OnClickListner cannot be resolve to a type".
i also post my code
package com.msi.manning.unlockingandroid;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.view.View.OnClickListener;
public class MyFirst extends Activity {
private EditText name;
private Button ok;
private TextView Name;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = new TextView(this);
tv.setText("Hello This is My First Programe");
setContentView(tv);
this.name = (EditText)findViewById(R.id.name);
// final Button button = (Button)findViewById(R.id.Ok);
this.ok = (Button)findViewById(R.id.Ok);
this.ok.setOnClickListener(new OnClickListner(){
public void onClick(View v){
try{
Log.i(tag, "onClick invoke.");
String Name = name.getText().toString();
Log.i(tag, "My name is == ");
Name.setText(name);
}catch(Exception e){
e.printStackTrace();
Name.setText(e.getMessage());
}
}
});
}
}
if any one know ans. please help me
I have different prob. AVD is running , I can see emulator window and able to do operation on GUI.
But when I run command "adb devices" I get no device listed.
C:\download\android-sdk-windows\tools>adb devices
List of devices attached
C:\download\android-sdk-windows\tools>
any experts comments please
guys i need some help....
I'm a newbie in this programming. I'm trying to learn about Android SDK and i'm learning through tutorials in the SDK website. The problem is, i'm having trouble opening xml files in Eclipse. When i double click the xml, the software will either crash or stopped responding.
Anyways I'm running Eclipse Helios on Win7 64bit. Any help?
Hey. Nice guide :D
I've just got one question: How can i transform the JAVA and XML files into a .apk file?
Your compiled .apk file is contained in the bin folder of your project. You can also deploy directly to your phone over a USB cable.
Thanks for your reply.
Have you made some other guides that will make a little more sophisticated app?
I'm afraid mine might be a bonehead problem. I have created your Hello World app in Eclipse Galileo, and have run it successfully on the Android emulator in Eclipse. I am trying to deploy .apk to my Nexus 1. In your response to Michno, you said "...deploy directly to your phone over a USB cable." Sounds good but is not working for me. I have connected my Nexus 1 with a USB, and am using the webshare app to move the .apk file from my PC (Win 7 x86 OS) to the nexus. Though WebShare tells me the .apk transferred successfully, I can't find it on the Nexus. Also, I'm getting an error message on the PC saying that there is no disk where the nexus is supposed to be. What am I doing wrong? Any help or links or suggestions are welcome.
Hello. I cannot see my 'Click me' Button. I can only see an "ANDROID_" wriiten on it. Have any suggestion? Please email me at:sunny_ashi1@hotmail.com
Thank you very much.
Great tutorial, thanks. I'm struggling with getting the Android SDK to create AVDs. Each time I try, the SDK locks up with a "not responding" message. Once I get that to clear, I can see the following details on the AVD that I tried to create:
Name: Android2.1
Path: C:\Users\Bob\.android\avd\Android2.1
Error: Failed to parse properties from c:\Users\Bob\.android\avd\Android2.1
Any idea what I might have screwed up? Thanks.
Well, I figured out why I was having problems with the Android SDK. I have a 4 year old laptop that doesn't have a very fast processor - its an AMD Turion 64 X2. So I was waiting for 10-15 minutes for this thing to finish - would get the "not responding" message. I thought the thing had failed - but yesterday I looked at the Task Manager and could see that the SDK process was still cranking away. So 25 minutes later, it finished and I got my Android2.1 Virtual Device. Had similar issues today with running HelloWorld - took a really long time to set up, and I got error messages along the way, but once it finished, the app was loaded and it worked. So I'll be springing for something like an i7 Intel laptop in the fairly near future. Thanks again for the great tutorial - would have been difficult to get set up without it.
I need some help and I need it file. I need a app that would read a text file from the SDCARD which has phone numbers and text everyone in the file the same message as a click on the button .. can someone please help
worked for me. had to change the 'Button01' to 'button1' and remove that line 18 @override, but given the speed of releases of both android and eclipse, i was very impressed that I got it up and running in under twenty minutes. Thanks Greg
is there any minimum size of SD card ?
i am getting error tools folder not found plz help?
Hi,
Thanks for the awesome tutorial.
First I got the screen with "android" on it > then with the android screen lock and sound icon.
I see the foll. in the console screen
[2011-03-09 17:16:17 - Hello world] ActivityManager: [1] Killed
Any help is appreciated.
Thanks again
missed the last pasrt of sentence
[2011-03-09 17:16:17 - Hello world] ActivityManager: [1] Killed am start -n com....
@rana, I added a download link for the complete source code. See if you can run my code or update yours to match mine.
Thanks much Greg. Hitting the same with your code. Appreciate your help.
googled it and someone solved it by modifying AndroidManifest.xml - did not mention how.
Thanks for the example!
I had problems similar to the ones reported here and here's the solution:
1) Add
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
to import list.
2) Change Button01 to button1.
3) Comment out "@Override" on line 18.
4) WAIT for the device emulator (5 to 25 min depending on your system).
Why does the emulator load so slowly? Is there a different version than 2.1 that is actually usable?
Hi Greg,
Im having trouble with the new project creation part. Everytime i go on to click the Finish button i get an error saying: "E:\\android-sdk-windows\tools\lib\proguard.cfg (The system cannot find the file specified)." Plz help as im new to the environment. Im using Win7 + eclipse IDE(v3.6 helios).
-Harshdeep
3) Comment out "@Override" on line 18.
4) WAIT for the device emulator (5 to 25 min depending on your system).
April 11, 2011 6:01 AM
ouch!! 5-25 min for emulator to fire up.. eash.. I was soo happen when I imported a boat load of androids from hong hong... i7 emulator startup.. 35sec... whoo hoo comon 2011...
check out my androids a http://8cupsaday.com
I added "" right before the ending menifest tag to avoid warning.
Hi all,
In the following code "setContentView(R.layout.main);"
I am getting an error "R cannot be resolved to a variable"
When i import the class android.R this is resolved but it is giving a error "main cannot be resolved or it is not a field " i am very new to this android dev, kindly advice me in this
Thanks... This is very helpful for everyone who wants to be an android developer :D
thanks its very good...
i got an error
[2011-07-14 11:49:31 - Emulator] PANIC: Could not open:C:\Users\pcname\.android/avd/MonoDroid2.2.ini
my android emulator path is D:\Users\pcname\.android/avd/MonoDroid2.2.ini...
how can i fixed it..
thanks
I have the exactly same problem
mine says
Could not find HelloAndroid.apk!
Download my complete example and run it. Then compare it to your project.
Michael Yap,
To solve it, copy your folder ".android" from D:\... into C:\Users\pcname\.
Is there a way to change the emulator path from C: to D: instead of copying the folder? It would help a LOT.
The 10 first hits on google for "Emulator Panic: Could not open" have no idea how to do this. :(
when I am building my code it gives me an error, " Dalvik Format failed with error 1"
Can anyone tell me what does this mean..???
when i am running the AVD following error appears
[2011-09-04 07:46:42 - Hello World] Launching a new emulator with Virtual Device 'Andriod2.1'
[2011-09-04 07:46:42 - Emulator] invalid command-line parameter: Files.
[2011-09-04 07:46:42 - Emulator] Hint: use '@foo' to launch a virtual device named 'foo'.
[2011-09-04 07:46:42 - Emulator] please use -help for more information
Could you please help me out
This @foo problem is because of the SDK location. I had a long path for program files which caused this issue. Some suggested to use ~ for the directory having space. That seems to work. I installed SDK in a direction "Android" and it worked perfect.
Good work Greg. Really enjoyed my First Android App!!
Great! Thanks for sharing the code. I had missed a show() method call and I was tearing my hair out!
i am new to android, plz suggest me some tutorials for learning it..
If you are experiencing an error with an @override for onClick (line 18) you can correct this by right clicking on your project and select "Java Compiler" and setting it 1.6. You probably are on 1.5. That should correct your override errors.
Wow..Thanks Greg :)
It saved a lot of time..Selecting 1.6 really solved it..
The Words "Hello World" appear in my application.
Where is this text coming from, it isn't in the main.xml, it isn't in the java source file. Is it something I can edit ? or do all android applications have to say "Hello World", I have only been programming for 20 years, so perhaps modifying the "Hello World" text is beyond me... maybe I shouldn't be tinkering with the hidden "Hello World" string that is embedded deep in a secret file that is part of every project, but can't be found or edited.
If you ran my sample Hello World is on line 9 of HelloWorld.java. I have never seen hello world just appear in an app.
I am getting an error."R cannot be resolved to a variable" how do I solve it?
how about Android?
how to install eclipse to run Android application
package our.age.name;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class RT extends Activity {
Button Calculate;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Calculate = (Button) findViewById(R.id.button1);
Calculate.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(RT.this, "Hello World", Toast.LENGTH_SHORT).show();
}
});
}
}
my code is performing no action on onClick()Please help me why my code is not working
I ran your code and it worked, I received a popup message hello world. Your issue must be somewhere else. If you email me the entire project folder zipped I can take a look. Also you can download my complete example and run it and see if it works for you, then compare the two projects.
hi Greg where i can mail you my zipped folder
n i am using eclipse indigo jdk1.5 sdk r15 and API 10 version 2.3 it this combination works
You can send it to [greg][@][androidcodemonkey].[com]
hii greg i hv mailed you please chk and tell what can be done
thanx a lot!
Great
thanx!
Thanks bro.
Works.
I would always start the Emulator first before doing any coding in future. So slow to start. I think shutting down anti-virus can help speed it up but not ideal obv.
Upwards and onwards now.
First off a very big Thank You for your pages here! They are a great confidence builder for new Android developers.
I ran into one problem that prevented me from getting the app to run on Eclipse 3.72 with the latest Android SDK and Java JDK on Win7. I nearly posted asking for help and I was able to fix it myself.
Your main.xml example at the top has linearlayout and button markers. That caused Eclipse to crash just starting the app. When I changed them to LinearLayout and Button (both mixed case, not lower case) the problem went away.
I found that when I used lower case for both the sample app would not even run. It died with:
04-02 19:39:55.915: E/AndroidRuntime(481): FATAL EXCEPTION: main
04-02 19:39:55.915: E/AndroidRuntime(481): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.android.test/com.android.test.HelloWorld}: android.view.InflateException: Binary XML file line #2: Error inflating class linearlayout
and gives a nice big callstack. You may want to add that case check to the eratta notes for those who just copy/paste and have not yet absorbed all of the Android subtlties.
Bruce
Hello, just wanna ask why do this line get an error?
Button button = (Button)findViewById(R.id.Button01);
thanks!
I am unable to get the option Android project in Eclipse Indigo. I downloaded 752 mb android sdk folder, it has android 1.5 to 3.0. I even downloaded Android plugin in Eclipse. But still it is not showing Android project. What should I do?
" Dual screen APIs" not installing,any reason for that
Greg really nice of u to reply to so many posts :)
M just getting screen written 'android' on it. Code had no error. What could be the problem?
My first droid Hello World! After a couple tweaks : remove @Override and rename button1 it worked! Cool!!!!
HI Greg,
I get the following error when I run the code you have listed at the beginning:
emulator-5554 disconnected! Cancelling 'com.example.helloanroid.HelloAnroidActivity activity launch'!
Could you please help me here!
it says...failed to instal 001HelloWorld.apk on device emulator...will you tell me why...?
coz right now i must make a medic application that running on android...
please...
Well if anyone is ultranoob at this like me and wanna not lose a couple hours of your life like i did, watch your capitalization. I had the superclass prob, changed from 1.5/1.6 several times, hit clean, etc and perused several websites finally i found and fixed ityped OnCreate and changed it to onCreate, life was good after that....im doing the tut on android website btw but may switch to this site, this sites better it has more descriptive steps and user feedback
Nice thanks.....
hi every one am new in android development and i get an error which says unreachable code on button1 underlined red Button clear=(Button)findViewById(R.id.button1); and the following lines it doesn't say anything.
help me what is the problem.
Excellent tutorials for beginners....Really good work!!!!!!
heyyy hi All
can you guys help me regarding source codde of 'android web browser' that can be run as an application using monkey talk,, i a am done with the hello world project and its recording the script..
please provide me a zip file similar to the hello world. I shall be very thankful to you. i have tried few from internet, but there are so many errors during the run , so the smulator is not opening.
Please help.
Regards
Pawan
i think it is easier to use etrus insead of eclips it works nice
We are a leading software company dwarka,India which works as per the client requirements and give provide software.
Did you ever think is it possible to edit an APK file or change the way it works?
http://goo.gl/rv6JRT
Good work, thank you so much for sharing this, it's really excellent.
open source of barcode generator for java
Android change the world of smartphone. Now days most of peoples are just taking Android OS mobile phones but few peoples are using iOS operating system. Waiting for ios 9 release date.
Great post,Thanks for providing us this great knowledge,Keep it up.
A good blog.
Signature:
download descargar facebook messenger and download free descargar facebook para android , descargar facebook gratis , descarga facebook
The article you have shared here very awesome. I really like and appreciated your work. I read deeply your article, the points you have mentioned in this article are useful
Signature:
download free descargar whatsapp gratis and download baixar whatsapp gratis online and descargar whatsapp , baixar whatsapp
your blog Provides things are helps me to find my detail. your blog is very good for me
please keep it up.
Visit :- App builder Android
We understand that businesses are on the outlook for android app development company that can help fulfill their comprehensive android app needs. This is why Webnet offers a broad range of android app services to businesses.
Custom Android App Development is said to have a showing position in the Smartphone market as Android is a mind energizing stage to make Smartphone applications.
Do you know which the top smartphone platform in the US is? It is undoubtedly Android. Android has achieved the trust of more than 52% of total Smartphone users in the U.S. Android Development California
oh thank you for the post! it is very great!
لعبه توم القط المتكلم
This article is very much helpful and i hope this will be an useful information for the needed one. Keep on updating these kinds of informative things...
Mobile App Development Company in Chennai
Android app Development Company in Chennai
ios app development Company in Chennai
Post a Comment
Note: Only a member of this blog may post a comment.