Lập trình Android: EarthQuake ppt

16 207 0
Lập trình Android: EarthQuake ppt

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Trung tâm Tin học – ĐH KHTN Cảnh báo động đất Trong bài viết này mình sẽ xây dựng 1 bài viết lấy các thông tin về động đất trên thế giới (dựa và website của chính phủ Mỹ : www.earthquake.usgs.gov ). Và thông qua đó giới thiệu 1 số kỹ thuật lập trình Android với các bạn (kiểu như tự học lập trình thông qua Project thực tế). 1/ Đầu tiên các bạn tạo 1 Project như sau: Project name: Earthquake Build Target: Android 2.3.3 Application name: Earthquake Package name: com.paad.earthquake 2/ Tạo các resources cho Project như sau: + Trong file strings.xml : <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">Earthquake</string> <string name="quake_feed"> http://earthquake.usgs.gov/eqcenter/catalogs/1day-M2.5.xml </string> <string name="menu_update">Refresh Earthquakes</string> </resources> + Tạo thêm 1 file quake_details.xml trong folder layout như sau: <?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" android:padding="10dp"> <TextView android:id="@+id/quakeDetailsTextView" android:layout_width="fill_parent" android:layout_height="fill_parent" android:textSize="14sp" android:autoLink="all" /> </LinearLayout> Lập trình Android – http://laptrinhdidong.vn Page 1 Trung tâm Tin học – ĐH KHTN + Trong file main.xml như sau: <?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"> <ListView android:id="@+id/earthquakeListView" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </LinearLayout> Vậy ta đã tao 1 ListView để hiển thị list các trận động đất xảy ra gần đây. Để ứng dụng có thể truy cập vào Internet lấy thông tin ta thêm vào file AndroidManifest.xml như sau (chú ý phần màu vàng): <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.paad.earthquake" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".Earthquake" 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> <uses-sdk android:minSdkVersion="7" /> <uses-permission android:name="android.permission.INTERNET"/> </manifest> 3/ Ta tiến đến lập trình xử lý cho ứng dụng. Đầu tiên ta tạo 1 class Quake.java để làm đối tượng 1 bản tin (từng Item của ListItem). Sau khi tạo xong ta thêm code như sau: package com.paad.earthquake; import java.util.Date; Lập trình Android – http://laptrinhdidong.vn Page 2 Trung tâm Tin học – ĐH KHTN import java.text.SimpleDateFormat; import android.location.Location; public class Quake { private Date date; private String details; private Location location; private double magnitude; private String link; public Date getDate() { return date; } public String getDetails() { return details; } public Location getLocation() { return location; } public double getMagnitude() { return magnitude; } public String getLink() { return link; } public Quake(Date _d, String _det, Location _loc, double _mag, String _link) { date = _d; details = _det; location = _loc; magnitude = _mag; link = _link; } Lập trình Android – http://laptrinhdidong.vn Page 3 Trung tâm Tin học – ĐH KHTN @Override public String toString() { SimpleDateFormat sdf = new SimpleDateFormat("HH.mm"); String dateString = sdf.format(date); return dateString + ": " + magnitude + " " + details; } } Trong class này mình tạo các thuộc tính cho từng dòng thông báo như ngày tháng,địa điểm… và 2 số phương thức: Thiết lập và định dạng cho ngày tháng. Sau đó ta tạo code cho file Earthquake.java như sau: package com.paad.earthquake; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.GregorianCalendar; Lập trình Android – http://laptrinhdidong.vn Page 4 Trung tâm Tin học – ĐH KHTN import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.location.Location; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.MenuItem; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.AdapterView.OnItemClickListener; public class Earthquake extends Activity { Lập trình Android – http://laptrinhdidong.vn Page 5 Trung tâm Tin học – ĐH KHTN ListView earthquakeListView; ArrayAdapter<Quake> aa; ArrayList<Quake> earthquakes = new ArrayList<Quake>(); static final private int QUAKE_DIALOG = 1; Quake selectedQuake; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); earthquakeListView = (ListView)this.findViewById(R.id.earthquakeListView); earthquakeListView.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView _av, View _v, int _index, long arg3) { selectedQuake = earthquakes.get(_index); showDialog(QUAKE_DIALOG); } }); int layoutID = android.R.layout.simple_list_item_1; aa = new ArrayAdapter<Quake>(this, layoutID , earthquakes); earthquakeListView.setAdapter(aa); Lập trình Android – http://laptrinhdidong.vn Page 6 Trung tâm Tin học – ĐH KHTN refreshEarthquakes(); } private void refreshEarthquakes() { // Get the XML URL url; try { String quakeFeed = getString(R.string.quake_feed); url = new URL(quakeFeed); URLConnection connection; connection = url.openConnection(); HttpURLConnection httpConnection = (HttpURLConnection)connection; int responseCode = httpConnection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream in = httpConnection.getInputStream(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); // Parse the earthquake feed. Lập trình Android – http://laptrinhdidong.vn Page 7 Trung tâm Tin học – ĐH KHTN Document dom = db.parse(in); Element docEle = dom.getDocumentElement(); // Clear the old earthquakes earthquakes.clear(); // Get a list of each earthquake entry. NodeList nl = docEle.getElementsByTagName("entry"); if (nl != null && nl.getLength() > 0) { for (int i = 0 ; i < nl.getLength(); i++) { Element entry = (Element)nl.item(i); Element title = (Element)entry.getElementsByTagName("title").item(0); Element g = (Element)entry.getElementsByTagName("georss:point").item(0); Element when = (Element)entry.getElementsByTagName("updated").item(0); Element link = (Element)entry.getElementsByTagName("link").item(0); String details = title.getFirstChild().getNodeValue(); String hostname = "http://earthquake.usgs.gov"; String linkString = hostname + link.getAttribute("href"); String point = g.getFirstChild().getNodeValue(); String dt = when.getFirstChild().getNodeValue(); Lập trình Android – http://laptrinhdidong.vn Page 8 Trung tâm Tin học – ĐH KHTN SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM- dd'T'hh:mm:ss'Z'"); Date qdate = new GregorianCalendar(0,0,0).getTime(); try { qdate = sdf.parse(dt); } catch (ParseException e) { e.printStackTrace(); } String[] location = point.split(" "); Location l = new Location("dummyGPS"); l.setLatitude(Double.parseDouble(location[0])); l.setLongitude(Double.parseDouble(location[1])); String magnitudeString = details.split(" ")[1]; int end = magnitudeString.length()-1; double magnitude = Double.parseDouble(magnitudeString.substring(0, end)); details = details.split(",")[1].trim(); Quake quake = new Quake(qdate, details, l, magnitude, linkString); // Process a newly found earthquake Lập trình Android – http://laptrinhdidong.vn Page 9 Trung tâm Tin học – ĐH KHTN addNewQuake(quake); } } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } finally { } } private void addNewQuake(Quake _quake) { // Add the new quake to our list of earthquakes. earthquakes.add(_quake); // Notify the array adapter of a change. aa.notifyDataSetChanged(); } Lập trình Android – http://laptrinhdidong.vn Page 10 [...]... hiển thị list, tạo Menu và tạo thông báo Kết quả của Project khi debug: Ban đầu: Lập trình Android – http://laptrinhdidong.vn Page 13 Trung tâm Tin học – ĐH KHTN Khi bấm vào 1 Item: Lập trình Android – http://laptrinhdidong.vn Page 14 Trung tâm Tin học – ĐH KHTN Khi bấm vào đường link ta đc chi tiết của trang web: Lập trình Android – http://laptrinhdidong.vn Page 15 Trung tâm Tin học – ĐH KHTN Vậy... R.string.menu_update); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); switch (item.getItemId()) { case (MENU_UPDATE): { refreshEarthquakes(); return true; } } return false; } Lập trình Android – http://laptrinhdidong.vn Page 11 Trung tâm Tin học – ĐH KHTN @Override public Dialog onCreateDialog(int id) { switch(id) { case (QUAKE_DIALOG) : LayoutInflater... SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); String dateString = sdf.format(selectedQuake.getDate()); String quakeText = "Magnitude " + selectedQuake.getMagnitude() + "\n" + selectedQuake.getDetails() + "\n" + Lập trình Android – http://laptrinhdidong.vn Page 12 Trung tâm Tin học – ĐH KHTN selectedQuake.getLink(); AlertDialog quakeDialog = (AlertDialog)dialog; quakeDialog.setTitle(dateString); TextView tv = (TextView)quakeDialog.findViewById(R.id.quakeDetailsTextView);... cho các bạn 1 Project đơn giản nhưng khá hay và có thể ứng dụng thật tế Mọi ý kiến đóng góp các bạn gữi bài viết về forum trang web www.laptrinhdidong.vn Rất mong nhận được sự phản hồi của các bạn Lập trình Android – http://laptrinhdidong.vn Page 16 . (dựa và website của chính phủ Mỹ : www .earthquake. usgs.gov ). Và thông qua đó giới thiệu 1 số kỹ thuật lập trình Android với các bạn (kiểu như tự học lập trình thông qua Project thực tế). 1/. xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="10dp"> <TextView android:id="@+id/quakeDetailsTextView" . xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ListView android:id="@+id/earthquakeListView"

Ngày đăng: 08/08/2014, 04:21

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan