Wrox Programmer Forums

Need to download code?

View our list of code downloads.

Register | FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read
BOOK: Professional Android Application Development ISBN: 978-0-470-34471-2
This is the forum to discuss the Wrox book Professional Android Application Development by Reto Meier; ISBN: 9780470344712
Welcome to the p2p.wrox.com Forums.

You are currently viewing the BOOK: Professional Android Application Development ISBN: 978-0-470-34471-2 section of the Wrox Programmer to Programmer discussions. This is a community of tens of thousands of software programmers and website developers including Wrox book authors and readers. As a guest, you can read any forum posting. By joining today you can post your own programming questions, respond to other developersí questions, and eliminate the ads that are displayed to guests. Registration is fast, simple and absolutely free .
DRM-free e-books 300x50
Reply
 
Thread Tools Display Modes
  #1 (permalink)  
Old January 15th, 2013, 01:02 AM
Registered User
Points: 13, Level: 1
Points: 13, Level: 1 Points: 13, Level: 1 Points: 13, Level: 1
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Jan 2013
Posts: 3
Thanks: 0
Thanked 0 Times in 0 Posts
Default error in example Earthquake ch 6

LOG CAT ERROR-->
01-15 11:18:53.970: D/dalvikvm(1439): GC_CONCURRENT freed 172K, 5% free 6271K/6535K, paused 71ms+93ms, total 251ms
01-15 11:18:54.290: W/dalvikvm(1439): threadid=11: thread exiting with uncaught exception (group=0x40a13300)
01-15 11:18:54.300: E/AndroidRuntime(1439): FATAL EXCEPTION: refresh_earthquake
01-15 11:18:54.300: E/AndroidRuntime(1439): java.lang.SecurityException: Requires VIBRATE permission
01-15 11:18:54.300: E/AndroidRuntime(1439): at android.os.Parcel.readException(Parcel.java:1425)
01-15 11:18:54.300: E/AndroidRuntime(1439): at android.os.Parcel.readException(Parcel.java:1379)
01-15 11:18:54.300: E/AndroidRuntime(1439): at android.app.INotificationManager$Stub$Proxy.enqueu eNotificationWithTag(INotificationManager.java:295 )
01-15 11:18:54.300: E/AndroidRuntime(1439): at android.app.NotificationManager.notify(Notificatio nManager.java:124)
01-15 11:18:54.300: E/AndroidRuntime(1439): at android.app.NotificationManager.notify(Notificatio nManager.java:103)
01-15 11:18:54.300: E/AndroidRuntime(1439): at com.paad.earthquake.EarthquakeService.announceNewQ uake(EarthquakeService.java:170)
01-15 11:18:54.300: E/AndroidRuntime(1439): at com.paad.earthquake.EarthquakeService.addNewQuake( EarthquakeService.java:126)
01-15 11:18:54.300: E/AndroidRuntime(1439): at com.paad.earthquake.EarthquakeService.doRefreshEar thquakes(EarthquakeService.java:255)
01-15 11:18:54.300: E/AndroidRuntime(1439): at com.paad.earthquake.EarthquakeService.access$1(Ear thquakeService.java:194)
01-15 11:18:54.300: E/AndroidRuntime(1439): at com.paad.earthquake.EarthquakeService$2.run(Earthq uakeService.java:189)
01-15 11:18:54.300: E/AndroidRuntime(1439): at java.lang.Thread.run(Thread.java:856)
01-15 11:18:55.530: I/Choreographer(1439): Skipped 71 frames! The application may be doing too much work on its main thread.

EARTHQUAKE.JAVA---------->
package com.paad.earthquake;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.database.Cursor;
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;

@SuppressLint("SimpleDateFormat")
public class Earthquake extends Activity {
private static final int QUAKE_DIALOG = 1;

private static final int MENU_UPDATE = Menu.FIRST;
private static final int MENU_PREFERENCES = Menu.FIRST+1;

private static final int SHOW_PREFERENCES = 1;

ListView earthquakeListView;

ArrayList<Quake> earthquakes = new ArrayList<Quake>();
ArrayAdapter<Quake> aa;

Quake selectedQuake;

EarthquakeReceiver receiver;
NotificationManager notificationManager;

// Preference values
int minimumMagnitude = 0;
boolean autoUpdate = false;
int updateFreq = 0;

@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);

earthquakeListView = (ListView)this.findViewById(R.id.earthquakeListVie w);
earthquakeListView.setOnItemClickListener(new OnItemClickListener() {
@SuppressWarnings("deprecation")
public void onItemClick(AdapterView<?> _av, View _v, int _index, long _id) {
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);

loadQuakesFromProvider();

updateFromPreferences();
refreshEarthquakes();

notificationManager = (NotificationManager)getSystemService(Context.NOTI FICATION_SERVICE);
}

/** Refresh data from the earthquake feed using the Service*/
private void refreshEarthquakes() {
startService(new Intent(this, EarthquakeService.class));
}

/** Add a new quake to the ArrayList */
private void addQuakeToArray(Quake _quake) {
if (_quake.getMagnitude() > minimumMagnitude) {
// Add the new quake to our list of earthquakes.
earthquakes.add(_quake);

// Notify the array adapter of a change.
aa.notifyDataSetChanged();
}
}

/** Retrieve the Quakes from provider and populate the ArrayList */
private void loadQuakesFromProvider() {
// Clear the existing earthquake array
earthquakes.clear();

ContentResolver cr = getContentResolver();

// Return all the saved earthquakes
Cursor c = cr.query(EarthquakeProvider.CONTENT_URI, null, null, null, null);

if (c.moveToFirst())
{
do {
// Extract the quake details.
Long datems = c.getLong(EarthquakeProvider.DATE_COLUMN);
String details = c.getString(EarthquakeProvider.DETAILS_COLUMN);
Float lat = c.getFloat(EarthquakeProvider.LATITUDE_COLUMN);
Float lng = c.getFloat(EarthquakeProvider.LONGITUDE_COLUMN);
Double mag = c.getDouble(EarthquakeProvider.MAGNITUDE_COLUMN);
String link = c.getString(EarthquakeProvider.LINK_COLUMN);

Location location = new Location("dummy");
location.setLongitude(lng);
location.setLatitude(lat);

Date date = new Date(datems);

Quake q = new Quake(date, details, location, mag, link);
addQuakeToArray(q);
} while(c.moveToNext());
}
c.close();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);

menu.add(0, MENU_UPDATE, Menu.NONE, R.string.menu_update);
menu.add(0, MENU_PREFERENCES, Menu.NONE, R.string.menu_preferences);


return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);

switch (item.getItemId()) {
case (MENU_UPDATE): {
refreshEarthquakes();
return true;
}
case (MENU_PREFERENCES): {
Intent i = new Intent(this, Preferences.class);
startActivityForResult(i, SHOW_PREFERENCES);
return true;
}
}
return false;
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (requestCode == SHOW_PREFERENCES)
if (resultCode == Activity.RESULT_OK) {
updateFromPreferences();
refreshEarthquakes();
}
}

/** Update preference variables based on saved preferences */
private void updateFromPreferences() {
SharedPreferences prefs = getSharedPreferences(Preferences.USER_PREFERENCE, Activity.MODE_PRIVATE);

int minMagIndex = prefs.getInt(Preferences.PREF_MIN_MAG, 0);
if (minMagIndex < 0)
minMagIndex = 0;

int freqIndex = prefs.getInt(Preferences.PREF_UPDATE_FREQ, 0);
if (freqIndex < 0)
freqIndex = 0;

autoUpdate = prefs.getBoolean(Preferences.PREF_AUTO_UPDATE, false);

Resources r = getResources();
// Get the option values from the arrays.
int[] minMagValues = r.getIntArray(R.array.magnitude);
int[] freqValues = r.getIntArray(R.array.update_freq_values);

// Convert the values to ints.
minimumMagnitude = minMagValues[minMagIndex];
updateFreq = freqValues[freqIndex];
}

@Override
public Dialog onCreateDialog(int id) {
switch(id) {
case (QUAKE_DIALOG) :
LayoutInflater li = LayoutInflater.from(getApplicationContext());
View quakeDetailsView = li.inflate(R.layout.quake_details, null);

AlertDialog.Builder quakeDialog = new AlertDialog.Builder(getApplicationContext());
quakeDialog.setTitle("Quake Time");
quakeDialog.setView(quakeDetailsView);
return quakeDialog.create();
}
return null;
}

@Override
public void onPrepareDialog(int id, Dialog dialog) {
switch(id) {
case (QUAKE_DIALOG) :
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
String dateString = sdf.format(selectedQuake.getDate());
String quakeText = "Mangitude " + selectedQuake.getMagnitude() + "\n"
+ selectedQuake.getDetails() + "\n" + selectedQuake.getLink();

AlertDialog quakeDialog = (AlertDialog)dialog;
quakeDialog.setTitle(dateString);

TextView tv = (TextView)quakeDialog.findViewById(R.id.quakeDetai lsTextView);
if (tv != null)
tv.setText(quakeText);

break;
}
}

@Override
public void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter(EarthquakeService.NEW_EARTHQUAKE_FOUN D);
receiver = new EarthquakeReceiver();
registerReceiver(receiver, filter);
notificationManager.cancel(EarthquakeService.NOTIF ICATION_ID);

loadQuakesFromProvider();
}

@Override
public void onPause() {
unregisterReceiver(receiver);
super.onPause();
}

public class EarthquakeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
notificationManager.cancel(EarthquakeService.NOTIF ICATION_ID);
loadQuakesFromProvider();
}
}
}

EARTHQUAKEPROVIDER.JAVA---------->
package com.paad.earthquake;

import android.content.*;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.database.sqlite.SQLiteDatabase.CursorFacto ry;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

public class EarthquakeProvider extends ContentProvider {

public static final Uri CONTENT_URI = Uri.parse("content://com.paad.provider.earthquake/earthquakes");

//Create the constants used to differentiate between the different URI requests.
private static final int QUAKES = 1;
private static final int QUAKE_ID = 2;

private static final UriMatcher uriMatcher;
//Allocate the UriMatcher object, where a URI ending in 'earthquakes' will
//correspond to a request for all earthquakes, and 'earthquakesí with a trailing '/[rowID]' will represent a single earthquake row.
static {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI("com.paad.provider.Earthquake", "earthquakes", QUAKES);
uriMatcher.addURI("com.paad.provider.Earthquake", "earthquakes/#", QUAKE_ID);
}

@Override
public boolean onCreate() {
Context context = getContext();

earthquakeDatabaseHelper dbHelper;
dbHelper = new earthquakeDatabaseHelper(context, DATABASE_NAME,
null, DATABASE_VERSION);
earthquakeDB = dbHelper.getWritableDatabase();
return (earthquakeDB == null) ? false : true;
}

@Override
public String getType(Uri uri) {
switch (uriMatcher.match(uri)) {
case QUAKES: return "vnd.android.cursor.dir/vnd.paad.earthquake";
case QUAKE_ID: return "vnd.android.cursor.item/vnd.paad.earthquake";
default: throw new IllegalArgumentException("Unsupported URI: " + uri);
}
}

@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sort) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(EARTHQUAKE_TABLE);

// If this is a row query, limit the result set to the passed in row.
switch (uriMatcher.match(uri)) {
case QUAKE_ID: qb.appendWhere(KEY_ID + "=" + uri.getPathSegments().get(1));
break;
default : break;
}

// If no sort order is specified sort by date / time
String orderBy;
if (TextUtils.isEmpty(sort)) {
orderBy = KEY_DATE;
} else {
orderBy = sort;
}

// Apply the query to the underlying database.
Cursor c = qb.query(earthquakeDB,
projection,
selection, selectionArgs,
null, null, orderBy);

// Register the contexts ContentResolver to be notified if
// the cursor result set changes.
c.setNotificationUri(getContext().getContentResolv er(), uri);

// Return a cursor to the query result.
return c;
}

@Override
public Uri insert(Uri _uri, ContentValues _initialValues) {
// Insert the new row, will return the row number if successful.
long rowID = earthquakeDB.insert(EARTHQUAKE_TABLE, "quake", _initialValues);

// Return a URI to the newly inserted row on success.
if (rowID > 0) {
Uri uri = ContentUris.withAppendedId(CONTENT_URI, rowID);
getContext().getContentResolver().notifyChange(uri , null);
return uri;
}
throw new SQLException("Failed to insert row into " + _uri);
}

@Override
public int delete(Uri uri, String where, String[] whereArgs) {
int count;

switch (uriMatcher.match(uri)) {
case QUAKES:
count = earthquakeDB.delete(EARTHQUAKE_TABLE, where, whereArgs);
break;

case QUAKE_ID:
String segment = uri.getPathSegments().get(1);
count = earthquakeDB.delete(EARTHQUAKE_TABLE, KEY_ID + "="
+ segment
+ (!TextUtils.isEmpty(where) ? " AND ("
+ where + ')' : ""), whereArgs);
break;

default: throw new IllegalArgumentException("Unsupported URI: " + uri);
}

getContext().getContentResolver().notifyChange(uri , null);
return count;
}

@Override
public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
int count;
switch (uriMatcher.match(uri)) {
case QUAKES: count = earthquakeDB.update(EARTHQUAKE_TABLE, values, where, whereArgs);
break;

case QUAKE_ID: String segment = uri.getPathSegments().get(1);
count = earthquakeDB.update(EARTHQUAKE_TABLE, values, KEY_ID
+ "=" + segment
+ (!TextUtils.isEmpty(where) ? " AND ("
+ where + ')' : ""), whereArgs);
break;

default: throw new IllegalArgumentException("Unknown URI " + uri);
}

getContext().getContentResolver().notifyChange(uri , null);
return count;
}

/** The underlying database */
private SQLiteDatabase earthquakeDB;

private static final String TAG = "EarthquakeProvider";
private static final String DATABASE_NAME = "earthquakes.db";
private static final int DATABASE_VERSION = 1;
private static final String EARTHQUAKE_TABLE = "earthquakes";

// Column Names
public static final String KEY_ID = "_id";
public static final String KEY_DATE = "date";
public static final String KEY_DETAILS = "details";
public static final String KEY_LOCATION_LAT = "latitude";
public static final String KEY_LOCATION_LNG = "longitude";
public static final String KEY_MAGNITUDE = "magnitude";
public static final String KEY_LINK = "link";

// Column indexes
public static final int DATE_COLUMN = 1;
public static final int DETAILS_COLUMN = 2;
public static final int LONGITUDE_COLUMN = 3;
public static final int LATITUDE_COLUMN = 4;
public static final int MAGNITUDE_COLUMN = 5;
public static final int LINK_COLUMN = 6;

// Helper class for opening, creating, and managing database version control
private static class earthquakeDatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_CREATE =
"create table " + EARTHQUAKE_TABLE + " ("
+ KEY_ID + " integer primary key autoincrement, "
+ KEY_DATE + " LONG, "
+ KEY_DETAILS + " TEXT, "
+ KEY_LOCATION_LAT + " FLOAT, "
+ KEY_LOCATION_LNG + " FLOAT, "
+ KEY_MAGNITUDE + " FLOAT, "
+ KEY_LINK + " TEXT);";

/** Helper class for managing the Earthquake database */
public earthquakeDatabaseHelper(Context context, String name, CursorFactory factory, int version) {
super(context, name, factory, version);
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");

db.execSQL("DROP TABLE IF EXISTS " + EARTHQUAKE_TABLE);
onCreate(db);
}
}
}
EARTHQUAKESERVICE.JAVA---------->
package com.paad.earthquake;

import java.io.File;
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.Date;
import java.util.GregorianCalendar;
import java.util.Timer;
import java.util.TimerTask;
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.annotation.SuppressLint;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Color;
import android.location.Location;
import android.net.Uri;
import android.os.IBinder;

public class EarthquakeService extends Service {

public static final String NEW_EARTHQUAKE_FOUND = "New_Earthquake_Found";
public static final int NOTIFICATION_ID = 1;

private Timer updateTimer;
private Notification newEarthquakeNotification;

@SuppressWarnings("deprecation")
@Override
public void onCreate() {
updateTimer = new Timer("earthquakeUpdates");

int icon = R.drawable.icon;
String tickerText = "New Earthquake Detected";
long when = System.currentTimeMillis();

newEarthquakeNotification = new Notification(icon, tickerText, when);
}

@Override
public void onStart(Intent intent, int startId) {
// Retrieve the shared preferences
SharedPreferences prefs = getSharedPreferences(Preferences.USER_PREFERENCE, Activity.MODE_PRIVATE);

int minMagIndex = prefs.getInt(Preferences.PREF_MIN_MAG, 0);
if (minMagIndex < 0)
minMagIndex = 0;

int freqIndex = prefs.getInt(Preferences.PREF_UPDATE_FREQ, 0);
if (freqIndex < 0)
freqIndex = 0;

boolean autoUpdate = prefs.getBoolean(Preferences.PREF_AUTO_UPDATE, false);

Resources r = getResources();
int[] freqValues = r.getIntArray(R.array.update_freq_values);

int updateFreq = freqValues[freqIndex];

updateTimer.cancel();
if (autoUpdate) {
updateTimer = new Timer("earthquakeUpdates");
updateTimer.scheduleAtFixedRate(doRefresh, 0, updateFreq*60*1000);
}
else
refreshEarthquakes();
};

private TimerTask doRefresh = new TimerTask() {
public void run() {
refreshEarthquakes();
}
};

@Override
public IBinder onBind(Intent intent) {
return null;
}

private void addNewQuake(Quake _quake) {
ContentResolver cr = getContentResolver();
// Construct a where clause to make sure we donít already have this
// earthquake in the provider.
String w = EarthquakeProvider.KEY_DATE + " = " + _quake.getDate().getTime();

// If the earthquake is new, insert it into the provider.
Cursor c = cr.query(EarthquakeProvider.CONTENT_URI, null, w, null, null);
int dbCount = c.getCount();
c.close();

if (dbCount == 0){
ContentValues values = new ContentValues();

values.put(EarthquakeProvider.KEY_DATE, _quake.getDate().getTime());
values.put(EarthquakeProvider.KEY_DETAILS, _quake.getDetails());

double lat = _quake.getLocation().getLatitude();
double lng = _quake.getLocation().getLongitude();
values.put(EarthquakeProvider.KEY_LOCATION_LAT, lat);
values.put(EarthquakeProvider.KEY_LOCATION_LNG, lng);
values.put(EarthquakeProvider.KEY_LINK, _quake.getLink());
values.put(EarthquakeProvider.KEY_MAGNITUDE, _quake.getMagnitude());

cr.insert(EarthquakeProvider.CONTENT_URI, values);
announceNewQuake(_quake);
}
}

@SuppressWarnings("deprecation")
private void announceNewQuake(Quake quake) {
String svcName = Context.NOTIFICATION_SERVICE;
NotificationManager notificationManager;
notificationManager = (NotificationManager)getSystemService(svcName);

Context context = getApplicationContext();
String expandedText = quake.getDetails();
String expandedTitle = "M:" + quake.getMagnitude() + " " + quake.getLocation();
Intent startActivityIntent = new Intent(this, Earthquake.class);
PendingIntent launchIntent = PendingIntent.getActivity(context, 0, startActivityIntent, 0);

newEarthquakeNotification.setLatestEventInfo(conte xt,
expandedTitle,
expandedText,
launchIntent);
newEarthquakeNotification.when = java.lang.System.currentTimeMillis();

if (quake.getMagnitude() > 6) {
Uri ringURI = Uri.fromFile(new File("/system/media/audio/ringtones/ringer.mp3"));
newEarthquakeNotification.sound = ringURI;
}

double vibrateLength = 100*Math.exp(0.53*quake.getMagnitude());
long[] vibrate = new long[] {100, 100, (long)vibrateLength };
newEarthquakeNotification.vibrate = vibrate;

int color;
if (quake.getMagnitude() < 5.4)
color = Color.GREEN;
else if (quake.getMagnitude() < 6)
color = Color.YELLOW;
else
color = Color.RED;

newEarthquakeNotification.ledARGB = color;
newEarthquakeNotification.ledOffMS = (int)vibrateLength;
newEarthquakeNotification.ledOnMS = (int)vibrateLength;
newEarthquakeNotification.flags = newEarthquakeNotification.flags | Notification.FLAG_SHOW_LIGHTS;

notificationManager.notify(NOTIFICATION_ID, newEarthquakeNotification);

Intent intent = new Intent(NEW_EARTHQUAKE_FOUND);
intent.putExtra("date", quake.getDate().getTime());
intent.putExtra("details", quake.getDetails());
intent.putExtra("longitude", quake.getLocation().getLongitude());
intent.putExtra("latitude", quake.getLocation().getLatitude());
intent.putExtra("magnitude", quake.getMagnitude());

sendBroadcast(intent);
}

private void refreshEarthquakes() {
Thread updateThread = new Thread(null, backgroundRefresh, "refresh_earthquake");
updateThread.start();
}

private Runnable backgroundRefresh = new Runnable() {
public void run() {
doRefreshEarthquakes();
}
};

@SuppressLint("SimpleDateFormat")
private void doRefreshEarthquakes() {
// 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.
Document dom = db.parse(in);
Element docEle = dom.getDocumentElement();

// 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").ite m(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();
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
addNewQuake(quake);
}
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
finally {
}
}
}
QUAKE.JAVA---------->
package com.paad.earthquake;

import java.util.Date;
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;
}

@Override
public String toString() {

SimpleDateFormat sdf = new SimpleDateFormat("HH.mm");
String dateString = sdf.format(date);
//return "(" + dateString + ") " + details;
return dateString + ": " + magnitude + " " + details;
}

}
Reply With Quote
  #2 (permalink)  
Old January 15th, 2013, 01:09 AM
Registered User
Points: 13, Level: 1
Points: 13, Level: 1 Points: 13, Level: 1 Points: 13, Level: 1
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Jan 2013
Posts: 3
Thanks: 0
Thanked 0 Times in 0 Posts
Unhappy new errors when clicking on a earthquake item in list view

01-15 11:37:21.619: E/AndroidRuntime(1479): FATAL EXCEPTION: main
01-15 11:37:21.619: E/AndroidRuntime(1479): android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
01-15 11:37:21.619: E/AndroidRuntime(1479): at android.view.ViewRootImpl.setView(ViewRootImpl.jav a:589)
01-15 11:37:21.619: E/AndroidRuntime(1479): at android.view.WindowManagerImpl.addView(WindowManag erImpl.java:326)
01-15 11:37:21.619: E/AndroidRuntime(1479): at android.view.WindowManagerImpl.addView(WindowManag erImpl.java:224)
01-15 11:37:21.619: E/AndroidRuntime(1479): at android.view.WindowManagerImpl$CompatModeWrapper.a ddView(WindowManagerImpl.java:149)
01-15 11:37:21.619: E/AndroidRuntime(1479): at android.app.Dialog.show(Dialog.java:277)
01-15 11:37:21.619: E/AndroidRuntime(1479): at android.app.Activity.showDialog(Activity.java:3052 )
01-15 11:37:21.619: E/AndroidRuntime(1479): at android.app.Activity.showDialog(Activity.java:3002 )
01-15 11:37:21.619: E/AndroidRuntime(1479): at com.paad.earthquake.Earthquake$1.onItemClick(Earth quake.java:65)
01-15 11:37:21.619: E/AndroidRuntime(1479): at android.widget.AdapterView.performItemClick(Adapte rView.java:298)
01-15 11:37:21.619: E/AndroidRuntime(1479): at android.widget.AbsListView.performItemClick(AbsLis tView.java:1086)
01-15 11:37:21.619: E/AndroidRuntime(1479): at android.widget.AbsListView$PerformClick.run(AbsLis tView.java:2859)
01-15 11:37:21.619: E/AndroidRuntime(1479): at android.widget.AbsListView$1.run(AbsListView.java: 3533)
01-15 11:37:21.619: E/AndroidRuntime(1479): at android.os.Handler.handleCallback(Handler.java:615 )
01-15 11:37:21.619: E/AndroidRuntime(1479): at android.os.Handler.dispatchMessage(Handler.java:92 )
01-15 11:37:21.619: E/AndroidRuntime(1479): at android.os.Looper.loop(Looper.java:137)
01-15 11:37:21.619: E/AndroidRuntime(1479): at android.app.ActivityThread.main(ActivityThread.jav a:4745)
01-15 11:37:21.619: E/AndroidRuntime(1479): at java.lang.reflect.Method.invokeNative(Native Method)
01-15 11:37:21.619: E/AndroidRuntime(1479): at java.lang.reflect.Method.invoke(Method.java:511)
01-15 11:37:21.619: E/AndroidRuntime(1479): at com.android.internal.os.ZygoteInit$MethodAndArgsCa ller.run(ZygoteInit.java:786)
01-15 11:37:21.619: E/AndroidRuntime(1479): at com.android.internal.os.ZygoteInit.main(ZygoteInit .java:553)
01-15 11:37:21.619: E/AndroidRuntime(1479): at dalvik.system.NativeStart.main(Native Method)
Reply With Quote
  #3 (permalink)  
Old September 14th, 2013, 05:30 AM
Registered User
Points: 3, Level: 1
Points: 3, Level: 1 Points: 3, Level: 1 Points: 3, Level: 1
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Sep 2013
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
Default Important: EarthQuake URL has changed

New URL to consider:
http://earthquake.usgs.gov/earthquak...tom?format=xml

Another error I faced in EarthquakeListFragment.java

Instead of just this line:
Code:
details = details.split(",")[1].trim();
Code:
if (details.split(",").length > 1) {
							details = details.split(",")[1].trim();
						}
						else if (details.split(",").length > 0){
							details = details.split(",")[0].trim();
						}
						else {
							details = "";
						}
One title was not having comma (,) in them. So, need to change.
Reply With Quote
Reply


Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are Off
Pingbacks are On
Refbacks are Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
Chapter 7 Earthquake 2, Earthquake.java, error onActivityResult dbomberg BOOK: Professional Android 2 Application Development 2 November 30th, 2012 04:52 AM
CH 9 - Earthquake 2 (Async Task exmample) does not work cinomen BOOK: Professional Android 2 Application Development 2 November 2nd, 2010 08:40 PM
Chapter 9 - Earthquake - TimerTask Error IAmCorbin BOOK: Professional Android 2 Application Development 2 November 2nd, 2010 04:50 PM
Chapter 10 Earthquake 2 - Live Folder error MellowFellow BOOK: Professional Android 2 Application Development 1 September 13th, 2010 02:41 PM
Ch 4: Parse error: syntax error, unexpected T_SL hanizar77 BOOK: Beginning PHP5, Apache, and MySQL Web Development ISBN: 978-0-7645-7966-0 0 June 23rd, 2008 09:17 PM



All times are GMT -4. The time now is 02:10 AM.


Powered by vBulletin®
Copyright ©2000 - 2017, Jelsoft Enterprises Ltd.
© 2013 John Wiley & Sons, Inc.