Android: Step by Step Hello World! [includes basic xmlparse and little gps]
Hi; after a while i m back! with a post including some android experiences. Before start I want to mention that I have been developing on csharp for a long time so I want to mention that these Java tools made me sick
for a while to get use to and work with but now I am a good hello world programmer at android. As a system I use 64 bit Windows 7 (i hear you say what a shame for a developer
).
My Android development tools are Eclipse and Android SDK ofcourse.
Step 1: Make Environment Ready To Code:
First of all as s programmer who get used to code csharp on sharpdevelop I have alittle bit pain on preparing my development environment
about eclipse but thanks to some web resources I start to get on well with it but still think eclipse can cause some pain in your stomach
especially while you work with emulator.
The things you need:
- Eclipse Juno (in my case 64 bit http://www.eclipse.org/downloads/download.php?file=/technology/epp/downloads/release/juno/SR1/eclipse-mobile-juno-SR1-win32-x86_64.zip)
- Android Sdk (from Eclipse http://developer.android.com/sdk/installing/installing-adt.html)
- Also some AVD to emulate your code.
These things can seen really silly to you to explain but I writedown incase some folks need.
So as a recap to install android sdk from eclipse you should choose Android sdk manager and make sure that you installed
all necessary stuff:
In my case I install some things I need in this example with Android 4.2:
Yes after these painfull steps you have to arrenge your emulator again from Eclipse>Window>Android Device Manager you have
to create an emulator in my case it is ARM Android 4.2 device:
Now our development environment is ready for coding which is a little bit painfull for the first timers
but also choosing the right
developmet target is also important, from porject>properties choose your build target as your emulator.
In my case: Emulator: Android 4.2 Build Target: Android 4.2
Step 2: Ready To Say Hello World!:
My application will be very very basic it will parse some xml,get our gps and show us these information on gui.
ManinActivity.js
</pre>
package com.example.h;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.Menu;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TextView;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final Runnable Timer_Tick = null;
private static final ImageView ImageView = null;
private TextView textViewr=null;
int i=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//****gps
/* Use the LocationManager class to obtain GPS locations */
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
//***gps
final Runnable updateTask = new Runnable() {
public void run() {
TextView textView = (TextView) findViewById(R.id.textView1);
android.text.format.DateFormat df = new android.text.format.DateFormat();
textView.setText(df.format("dd/MM/yyyy hh:mm", new java.util.Date()));
textViewr = (TextView) findViewById(R.id.textView2);
//******************************************WEATHER***********************************
String imageUri=null;
InputStream content = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet("http://rss.accuweather.com/rss/liveweather_rss.asp?metric=1&locCode=MEA%7CTR%7CTU039%7CIZMIR%7C"));
XPath xpath = XPathFactory.newInstance().newXPath();
content = response.getEntity().getContent();
String expression = "//channel/item/description";
InputSource inputSource = new InputSource(content);
String id = null;
try {
id = (String) xpath.evaluate(expression, inputSource, XPathConstants.STRING);
} catch (XPathExpressionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.i("Test", id);
textViewr.setText(id.split("<img")[0]);
imageUri=id.split("<img src=\"")[1].split(".gif")[0];
imageUri=imageUri+".gif";
// TextView textViewr23 = (TextView) findViewById(R.id.textView3);
//textViewr23.setText(imageUri);
} catch (Exception e) {
Log.i("[GET REQUEST]", "Network exception", e);
}
//******************************************WEATHER***********************************
ImageView imgView =(ImageView)findViewById(R.id.imageView1);
Drawable drawable = LoadImageFromWebOperations(imageUri);
imgView.setImageDrawable(drawable);
}
private Drawable LoadImageFromWebOperations(String url) {
try{
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
}catch (Exception e) {
System.out.println("Exc="+e);
return null;
}
}
};
//******************************************TIMER FOR CLOCK***********************************
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
runOnUiThread(updateTask);
}
}, 1, 50000);
//******************************************TIMER FOR CLOCK***********************************
}
/* Class My Location Listener */
public class MyLocationListener implements LocationListener
{
@Override
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
String Text = "My current location is: " +
"Latitud = " + loc.getLatitude() +
"Longitud = " + loc.getLongitude();
TextView textViewr23 = (TextView) findViewById(R.id.textView3);
textViewr23.setText(Text);
Toast.makeText( getApplicationContext(), Text, Toast.LENGTH_SHORT).show();
ImageView imgView =(ImageView)findViewById(R.id.imageView2);
//http://maps.googleapis.com/maps/api/staticmap?&zoom=13&size=600x300&maptype=roadmap&markers=color:blue%7Clabel:S%7C40.702147,-74.015794&sensor=false
//http://maps.googleapis.com/maps/api/staticmap?&zoom=13&size=600x300&maptype=roadmap&markers=color:blue%257Clabel:S%257C40.702147,-74.015794&sensor=false
Drawable drawable = LoadImageFromWebOperations("http://maps.googleapis.com/maps/api/staticmap?&zoom=13&size=300x300&maptype=roadmap&markers=color:blue%7Clabel:S%7C"+loc.getLatitude()+","+loc.getLongitude()+"&sensor=false");
imgView.setImageDrawable(drawable);
}
private Drawable LoadImageFromWebOperations(String url) {
try{
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
}catch (Exception e) {
System.out.println("Exc="+e);
return null;
}
}
@Override
public void onProviderDisabled(String provider)
{
Toast.makeText( getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT ).show();
}
@Override
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
<pre>
AndroidManifest.xml
</pre> <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.h" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="8" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.h.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> <pre>
Output:
As you see at output we get our location with Google Static Maps Api and also parse weather condition from a xml service. To emulate
GPS you have yo use “Emulator Control” as below.
Download Source:
http://www.sendspace.com/file/nxhl0m
Pls dont hesitate to ask questions about this post…









lista de emails 8:02 pm on January 23, 2013 Permalink |
thanks for the post buddy. lista de emails lista de emails lista de emails lista de emails lista de emails
Hostpapa Ratings 5:58 am on January 24, 2013 Permalink |
Way cool! Some extremely valid points! I appreciate you writing this write-up and also the rest of the website is also very good.
christian music 6:01 am on January 24, 2013 Permalink |
i ponder factors i must do