find nearby places using places api - android

I followed a tut regarding finding nearby places using places api and tried to integrate it in my app. The nearyplaceactivity is runninng but place results are not showing up. Dont know wat is wrong coz the code is almost same as what the tutorial mentioned. Below is my code. If anyone could help, i would be really grateful... The tut link is http://www.androidhive.info/2012/08/android-working-with-google-places-and-maps-tutorial/
NearbyPlacesActivity.java
package com.example.travelplanner;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class NearbyPlacesActivity extends Activity {
// flag for Internet connection status
Boolean isInternetPresent = false;
// Connection detector class
ConnectionDetector cd;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
// Google Places
GooglePlaces googlePlaces;
// Places List
PlacesList nearPlaces;
// GPS Location
GPSTracker gps;
// Button
Button btnShowOnMap;
// Places Listview
ListView lv;
// ListItems data
ArrayList<HashMap<String, String>> placesListItems = new ArrayList<HashMap<String,String>>();
// KEY Strings
public static String KEY_REFERENCE = "reference"; // id of the place
public static String KEY_NAME = "name"; // name of the place
public static String KEY_VICINITY = "vicinity"; // Place area name
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nearby_places);
cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
isInternetPresent = cd.isConnectingToInternet();
if (!isInternetPresent) {
// Internet Connection is not present
alert.showAlertDialog(NearbyPlacesActivity.this, "Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// creating GPS Class object
gps = new GPSTracker(this);
// check if GPS location can get
if (gps.canGetLocation()) {
Log.d("Your Location", "latitude:" + gps.getLatitude() + ", longitude: " + gps.getLongitude());
} else {
// Can't get user's current location
alert.showAlertDialog(NearbyPlacesActivity.this, "GPS Status",
"Couldn't get location information. Please enable GPS",
false);
// stop executing code by return
return;
}
// Getting listview
lv = (ListView) findViewById(R.id.list);
// button show on map
btnShowOnMap = (Button) findViewById(R.id.btn_show_map);
// calling background Async task to load Google Places
// After getting places from Google all the data is shown in listview
new LoadPlaces().execute();
/** Button click event for shown on map */
btnShowOnMap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(),
PlacesMapActivity.class);
// Sending user current geo location
i.putExtra("user_latitude", Double.toString(gps.getLatitude()));
i.putExtra("user_longitude", Double.toString(gps.getLongitude()));
// passing near places to map activity
i.putExtra("near_places", nearPlaces);
// staring activity
startActivity(i);
}
});
/**
* ListItem click event
* On selecting a listitem SinglePlaceActivity is launched
* */
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String reference = ((TextView) view.findViewById(R.id.reference)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
SinglePlaceActivity.class);
// Sending place refrence id to single place activity
// place refrence id used to get "Place full details"
in.putExtra(KEY_REFERENCE, reference);
startActivity(in);
}
});
}
/**
* Background Async Task to Load Google places
* */
class LoadPlaces extends AsyncTask<String, String, String> {
// Progress dialog
ProgressDialog pDialog;
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NearbyPlacesActivity.this);
pDialog.setMessage(Html.fromHtml("<b>Search</b><br/>Loading Places..."));
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Places JSON
* */
protected String doInBackground(String... args) {
// creating Places class object
googlePlaces = new GooglePlaces();
try {
// Separeate your place types by PIPE symbol "|"
// If you want all types places make it as null
// Check list of types supported by google
//
String types = "cafe|restaurant"; // Listing places only cafes, restaurants
// Radius in meters - increase this value if you don't find any places
double radius = 1000; // 1000 meters
// get nearest places
nearPlaces = googlePlaces.search(gps.getLatitude(),
gps.getLongitude(), radius, types);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* and show the data in UI
* Always use runOnUiThread(new Runnable()) to update UI from background
* thread, otherwise you will get error
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed Places into LISTVIEW
* */
// Get json response status
String status = nearPlaces.status;
// Check for all possible status
if(status.equals("OK")){
// Successfully got places details
if (nearPlaces.results != null) {
// loop through each place
for (Place p : nearPlaces.results) {
HashMap<String, String> map = new HashMap<String, String>();
// Place reference won't display in listview - it will be hidden
// Place reference is used to get "place full details"
map.put(KEY_REFERENCE, p.reference);
// Place name
map.put(KEY_NAME, p.name);
// adding HashMap to ArrayList
placesListItems.add(map);
}
// list adapter
ListAdapter adapter = new SimpleAdapter(NearbyPlacesActivity.this, placesListItems,
R.layout.list_item,
new String[] { KEY_REFERENCE, KEY_NAME}, new int[] {
R.id.reference, R.id.name });
// Adding data into listview
lv.setAdapter(adapter);
}
}
else if(status.equals("ZERO_RESULTS")){
// Zero results found
alert.showAlertDialog(NearbyPlacesActivity.this, "Near Places",
"Sorry no places found. Try to change the types of places",
false);
}
else if(status.equals("UNKNOWN_ERROR"))
{
alert.showAlertDialog(NearbyPlacesActivity.this, "Places Error",
"Sorry unknown error occured.",
false);
}
else if(status.equals("OVER_QUERY_LIMIT"))
{
alert.showAlertDialog(NearbyPlacesActivity.this, "Places Error",
"Sorry query limit to google places is reached",
false);
}
else if(status.equals("REQUEST_DENIED"))
{
alert.showAlertDialog(NearbyPlacesActivity.this, "Places Error",
"Sorry error occured. Request is denied",
false);
}
else if(status.equals("INVALID_REQUEST"))
{
alert.showAlertDialog(NearbyPlacesActivity.this, "Places Error",
"Sorry error occured. Invalid Request",
false);
}
else
{
alert.showAlertDialog(NearbyPlacesActivity.this, "Places Error",
"Sorry error occured.",
false);
}
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.nearby_places, menu);
return true;
}
}

Related

Android Studio: Bluetooth Low Energy BLE Advertisements

on line 370 i need a way to look for a string of 'f's' in the advertisement data from a TI CC2650. I found this template online but I'm looking for specific advertising data. Please let me know what string array I need to look at to find this.
package net.jmodwyer.beacon.beaconPoC;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.content.SharedPreferences;
import android.location.Location;
import android.os.Bundle;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.text.util.Linkify;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.location.LocationClient;
import net.jmodwyer.ibeacon.ibeaconPoC.R;
import org.altbeacon.beacon.Beacon;
import org.altbeacon.beacon.BeaconConsumer;
import org.altbeacon.beacon.BeaconManager;
import org.altbeacon.beacon.RangeNotifier;
import org.altbeacon.beacon.Region;
import org.altbeacon.beacon.utils.UrlBeaconUrlCompressor;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
/**
* Adapted from original code written by D Young of Radius Networks.
* #author dyoung, jodwyer
*
*/
public class ScanActivity extends Activity implements BeaconConsumer,
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener {
// Constant Declaration
private static final String PREFERENCE_SCANINTERVAL = "scanInterval";
private static final String PREFERENCE_TIMESTAMP = "timestamp";
private static final String PREFERENCE_POWER = "power";
private static final String PREFERENCE_PROXIMITY = "proximity";
private static final String PREFERENCE_RSSI = "rssi";
private static final String PREFERENCE_MAJORMINOR = "majorMinor";
private static final String PREFERENCE_UUID = "uuid";
private static final String PREFERENCE_INDEX = "index";
private static final String PREFERENCE_LOCATION = "location";
private static final String PREFERENCE_REALTIME = "realTimeLog";
private static final String MODE_SCANNING = "Stop Scanning";
private static final String MODE_STOPPED = "Start Scanning";
protected static final String TAG = "ScanActivity";
/*
* Define a request code to send to Google Play services
* This code is returned in Activity.onActivityResult
*/
private final static int
CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private FileHelper fileHelper;
private BeaconManager beaconManager;
private Region region;
private int eventNum = 1;
// This StringBuffer will hold the scan data for any given scan.
private StringBuffer logString;
// Preferences - will actually have a boolean value when loaded.
private Boolean index;
private Boolean location;
private Boolean uuid;
private Boolean majorMinor;
private Boolean rssi;
private Boolean proximity;
private Boolean power;
private Boolean timestamp;
private String scanInterval;
// Added following a feature request from D.Schmid.
private Boolean realTimeLog;
// LocationClient for Google Play Location Services
LocationClient locationClient;
private ScrollView scroller;
private EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
verifyBluetooth();
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
BeaconScannerApp app = (BeaconScannerApp)this.getApplication();
beaconManager = app.getBeaconManager();
//beaconManager.setForegroundScanPeriod(10);
region = app.getRegion();
beaconManager.bind(this);
locationClient = new LocationClient(this, this, this);
fileHelper = app.getFileHelper();
scroller = (ScrollView)ScanActivity.this.findViewById(R.id.scanScrollView);
editText = (EditText)ScanActivity.this.findViewById(R.id.scanText);
// Initialise scan button.
getScanButton().setText(MODE_STOPPED);
}
#Override
public void onResume() {
super.onResume();
beaconManager.bind(this);
}
#Override
public void onPause() {
super.onPause();
// Uncommenting the following leak prevents a ServiceConnection leak when using the back
// arrow in the Action Bar to come out of the file list screen. Unfortunately it also kills
// background scanning, and as I have no workaround right now I'm settling for the lesser of
// two evils.
// beaconManager.unbind(this);
}
public String getCurrentLocation() {
/** Default "error" value is set for location, will be overwritten with the correct lat and
* long values if we're ble to connect to location services and get a reading.
*/
String location = "Unavailable";
if (locationClient.isConnected()) {
Location currentLocation = locationClient.getLastLocation();
if (currentLocation != null) {
location = Double.toString(currentLocation.getLatitude()) + "," +
Double.toString(currentLocation.getLongitude());
}
}
return location;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_activity_actions, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public void onBeaconServiceConnect() {}
/**
*
* #param view
*/
public void onScanButtonClicked(View view) {
toggleScanState();
}
// Handle the user selecting "Settings" from the action bar.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.Settings:
// Show settings
Intent api = new Intent(this, AppPreferenceActivity.class);
startActivityForResult(api, 0);
return true;
case R.id.action_listfiles:
// Launch list files activity
Intent fhi = new Intent(this, FileHandlerActivity.class);
startActivity(fhi);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Start and stop scanning, and toggle button label appropriately.
*/
private void toggleScanState() {
Button scanButton = getScanButton();
String currentState = scanButton.getText().toString();
if (currentState.equals(MODE_SCANNING)) {
stopScanning(scanButton);
} else {
startScanning(scanButton);
}
}
/**
* start looking for beacons.
*/
private void startScanning(Button scanButton) {
// Set UI elements to the correct state.
scanButton.setText(MODE_SCANNING);
((EditText)findViewById(R.id.scanText)).setText("");
// Reset event counter
eventNum = 1;
// Get current values for logging preferences
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
HashMap <String, Object> prefs = new HashMap<String, Object>();
prefs.putAll(sharedPrefs.getAll());
index = (Boolean)prefs.get(PREFERENCE_INDEX);
location = (Boolean)prefs.get(PREFERENCE_LOCATION);
uuid = (Boolean)prefs.get(PREFERENCE_UUID);
majorMinor = (Boolean)prefs.get(PREFERENCE_MAJORMINOR);
rssi = (Boolean)prefs.get(PREFERENCE_RSSI);
proximity = (Boolean)prefs.get(PREFERENCE_PROXIMITY);
power = (Boolean)prefs.get(PREFERENCE_POWER);
timestamp = (Boolean)prefs.get(PREFERENCE_TIMESTAMP);
scanInterval = (String)prefs.get(PREFERENCE_SCANINTERVAL);
realTimeLog = (Boolean)prefs.get(PREFERENCE_REALTIME);
// Get current background scan interval (if specified)
if (prefs.get(PREFERENCE_SCANINTERVAL) != null) {
beaconManager.setBackgroundBetweenScanPeriod(Long.parseLong(scanInterval));
}
logToDisplay("Scanning...");
// Initialise scan log
logString = new StringBuffer();
//Start scanning again.
beaconManager.setRangeNotifier(new RangeNotifier() {
#Override
public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
if (beacons.size() > 0) {
Iterator <Beacon> beaconIterator = beacons.iterator();
while (beaconIterator.hasNext()) {
Beacon beacon = beaconIterator.next();
// Debug - logging a beacon - checking background logging is working.
System.out.println("Logging another beacon.");
logBeaconData(beacon);
}
}
}
});
try {
beaconManager.startRangingBeaconsInRegion(region);
} catch (RemoteException e) {
// TODO - OK, what now then?
}
}
/**
* Stop looking for beacons.
*/
private void stopScanning(Button scanButton) {
try {
beaconManager.stopRangingBeaconsInRegion(region);
} catch (RemoteException e) {
// TODO - OK, what now then?
}
String scanData = logString.toString();
if (scanData.length() > 0) {
// Write file
fileHelper.createFile(scanData);
// Display file created message.
Toast.makeText(getBaseContext(),
"File saved to:" + getFilesDir().getAbsolutePath(),
Toast.LENGTH_SHORT).show();
scanButton.setText(MODE_STOPPED);
} else {
// We didn't get any data, so there's no point writing an empty file.
Toast.makeText(getBaseContext(),
"No data captured during scan, output file will not be created.",
Toast.LENGTH_SHORT).show();
scanButton.setText(MODE_STOPPED);
}
}
/**
*
* #return reference to the start/stop scanning button
*/
private Button getScanButton() {
return (Button)findViewById(R.id.scanButton);
}
/**
*
* #param beacon The detected beacon
*/
private void logBeaconData(Beacon beacon) {
StringBuilder scanString = new StringBuilder();
if (index) {
scanString.append(eventNum++);
}
if (beacon.getServiceUuid() == 0xfeaa) {
if (beacon.getBeaconTypeCode() == 0x00) {
scanString.append(" Eddystone-UID -> ");
scanString.append(" Namespace : ").append(beacon.getId1());
scanString.append(" Identifier : ").append(beacon.getId2());
logEddystoneTelemetry(scanString, beacon);
} else if (beacon.getBeaconTypeCode() == 0x10) {
String url = UrlBeaconUrlCompressor.uncompress(beacon.getId1().toByteArray());
scanString.append(" Eddystone-URL -> " + url);
} else if (beacon.getBeaconTypeCode() == 0x20) {
scanString.append(" Eddystone-TLM -> ");
logEddystoneTelemetry(scanString, beacon);
}
} else {
// Just an old fashioned iBeacon or AltBeacon...
logGenericBeacon(scanString, beacon);
}
logToDisplay(scanString.toString());
scanString.append("\n");
// Code added following a feature request by D.Schmid - writes a single entry to a file
// every time a beacon is detected, the file will only ever have one entry as it will be
// recreated on each call to this method.
// Get current background scan interval (if specified)
if (realTimeLog) {
// We're in realtime logging mode, create a new log file containing only this entry.
fileHelper.createFile(scanString.toString(), "realtimelog.txt");
}
logString.append(scanString.toString());
}
/**
* Logs iBeacon & AltBeacon data.
*/
private void logGenericBeacon(StringBuilder scanString, Beacon beacon) {
// Comment stuff out for whatever reason
/*
if (location) {
scanString.append(" Location: ").append(getCurrentLocation()).append(" ");
}
`
*/
if (uuid) {
scanString.append(" UUID: ").append(beacon.getId1());
if (beacon.getId1().equals("ffffffff-ffff-ffff-ffff-ffffffffffff ")){
scanString.append("WE DID IT!!!!!!!!!!!");
}else{
scanString.append(" WE DID NOT DO IT =( ");
}
/*
if ((beacon.getId1()).equals ("f")){
scanString.append("WE DID IT!!!!!!!!!!!");
}else{
scanString.append(" WE DID NOT DO IT!!!!!!!!!!! ");
}
*/
}
// Making if statements to test for advertising data
/*
if (majorMinor) {
scanString.append(" Maj. Mnr.: ");
if (beacon.getId2() != null) {
scanString.append(beacon.getId2());
}
scanString.append("-");
if (beacon.getId3() != null) {
scanString.append(beacon.getId3());
}
}
if (rssi) {
scanString.append(" RSSI: ").append(beacon.getRssi());
}
if (proximity) {
scanString.append(" Proximity: ").append(BeaconHelper.getProximityString(beacon.getDistance()));
}
if (power) {
scanString.append(" Power: ").append(beacon.getTxPower());
}
if (timestamp) {
scanString.append(" Timestamp: ").append(BeaconHelper.getCurrentTimeStamp());
} */
}
private void logEddystoneTelemetry(StringBuilder scanString, Beacon beacon) {
// Do we have telemetry data?
if (beacon.getExtraDataFields().size() > 0) {
long telemetryVersion = beacon.getExtraDataFields().get(0);
long batteryMilliVolts = beacon.getExtraDataFields().get(1);
long pduCount = beacon.getExtraDataFields().get(3);
long uptime = beacon.getExtraDataFields().get(4);
scanString.append(" Telemetry version : " + telemetryVersion);
scanString.append(" Uptime (sec) : " + uptime);
scanString.append(" Battery level (mv) " + batteryMilliVolts);
scanString.append(" Tx count: " + pduCount);
}
}
/**
*
* #param line
*/
private void logToDisplay(final String line) {
runOnUiThread(new Runnable() {
public void run() {
editText.append(line + "\n");
// Temp code - don't really want to do this for every line logged, will look for a
// workaround.
Linkify.addLinks(editText, Linkify.WEB_URLS);
scroller.fullScroll(View.FOCUS_DOWN);
}
});
}
private void verifyBluetooth() {
try {
if (!BeaconManager.getInstanceForApplication(this).checkAvailability()) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Bluetooth not enabled");
builder.setMessage("Please enable bluetooth in settings and restart this application.");
builder.setPositiveButton(android.R.string.ok, null);
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
finish();
System.exit(0);
}
});
builder.show();
}
}
catch (RuntimeException e) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Bluetooth LE not available");
builder.setMessage("Sorry, this device does not support Bluetooth LE.");
builder.setPositiveButton(android.R.string.ok, null);
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
finish();
System.exit(0);
}
});
builder.show();
}
}
/* Location services code follows */
#Override
protected void onStart() {
super.onStart();
// Connect the client.
locationClient.connect();
}
#Override
protected void onStop() {
// Disconnect the client.
locationClient.disconnect();
super.onStop();
}
#Override
public void onConnected(Bundle dataBundle) {
// Uncomment the following line to display the connection status.
// Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
}
#Override
public void onDisconnected() {
// Display the connection status
Toast.makeText(this, "Disconnected. Please re-connect.",
Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
/* Google Play services can resolve some errors it detects.
* If the error has a resolution, try sending an Intent to
* start a Google Play services activity that can resolve
* error.
*/
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(
this,
CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
/*
* If no resolution is available, display a dialog to the
* user with the error.
*/
Toast.makeText(getBaseContext(),
"Location services not available, cannot track device location.",
Toast.LENGTH_SHORT).show();
}
}
// Define a DialogFragment that displays the error dialog
public static class ErrorDialogFragment extends DialogFragment {
// Global field to contain the error dialog
private Dialog mDialog;
// Default constructor. Sets the dialog field to null
public ErrorDialogFragment() {
super();
mDialog = null;
}
// Set the dialog to display
public void setDialog(Dialog dialog) {
mDialog = dialog;
}
// Return a Dialog to the DialogFragment.
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return mDialog;
}
}
/*
* Handle results returned to the FragmentActivity
* by Google Play services
*/
#Override
protected void onActivityResult(
int requestCode, int resultCode, Intent data) {
// Decide what to do based on the original request code
switch (requestCode) {
case CONNECTION_FAILURE_RESOLUTION_REQUEST :
/*
* If the result code is Activity.RESULT_OK, try
* to connect again
*/
switch (resultCode) {
case Activity.RESULT_OK :
/*
* TODO - Try the request again
*/
break;
}
}
}
}
Need to cast to string first .toString
if (uuid) {
scanString.append(" UUID: ").append(beacon.getId1());
// Making if statements to look for all f's in advertising data
if (beacon.getId1().toString().equals(Str1)){
scanString.append("\nAlarm ACTIVATED\n");
}else{
scanString.append("\n Alarm NOT active\n");
}
}

Why my hashmap is null Android?

i am trying to get the value from the hashmap (from ListViewRestaurants) So i can pass the latitude and longitude to the MapsActivity but for reason my hashmap always return null ... So can Anyone help me.
public class ListViewRestaurants extends Activity {
static ListView listView;
static ArrayList<HashMap<String, String>> arrList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
listView = (ListView) findViewById(R.id.listiew);
arrList = new ArrayList<HashMap<String, String>>();
String json_str = getJsonData();
try {
JSONArray jArray = new JSONArray(json_str);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json = null;
json = jArray.getJSONObject(i);
HashMap<String, String> map1 = new HashMap<String, String>();
// adding each child node to HashMap key => value
map1.put("id", json.getString("id"));
map1.put("BusinessName", json.getString("BusinessName"));
map1.put("AddressLine1", json.getString("AddressLine1"));
map1.put("AddressLine2", json.getString("AddressLine2"));
map1.put("AddressLine3", json.getString("AddressLine3"));
map1.put("PostCode", json.getString("PostCode"));
map1.put("RatingValue", json.getString("RatingValue"));
map1.put("RatingDate", json.getString("RatingDate"));
map1.put("DistanceKM", json.getString("DistanceKM"));
map1.put("Latitude", json.getString("Latitude"));
map1.put("Longitude", json.getString("Longitude"));
int name = json.getInt("RatingValue");
if(name == 5){
map1.put("Image", String.valueOf(R.drawable.ic_launcher_web));
}
else if(name==4){
//map1.put("Image", String.valueOf(R.drawable.ic_launcher_web));
}
else if(name==3){
// map1.put("Image", String.valueOf(R.drawable.ic_launcher_web));
}
else if(name==2){
// map1.put("Image", String.valueOf(R.drawable.ic_launcher_web));
}
else if(name==1){
// map1.put("Image", String.valueOf(R.drawable.ic_launcher_web));
}
else if(name==0){
// map1.put("Image", String.valueOf(R.drawable.ic_launcher_web));
}
else if(name==-1){
map1.put("RatingValue", "Exempt");
}
// adding HashList to ArrayList
arrList.add(map1); // Intent intent = new Intent(this,MapsActivity.class); // intent.putExtra("map", map1);
}
} catch (JSONException e) {
e.printStackTrace();
}
if (!arrList.isEmpty()) {
ListAdapter adapter = new SimpleAdapter(this, arrList,
R.layout.list_item, new String[]{"id", "BusinessName",
"AddressLine1", "AddressLine2", "AddressLine3", "PostCode",
"RatingValue", "RatingDate", "DistanceKM", "Image"},
new int[]{R.id.restaurantId, R.id.BusinessName,
R.id.adr1, R.id.adr2, R.id.adr3, R.id.postCode,
R.id.rating, R.id.ratingDate, R.id.distance, R.id.image});
listView.setAdapter(adapter);
}
}
private String getJsonData() {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork() // or .detectAll() for all detectable problems
.penaltyLog()
.build());
String str = "";
Intent intent = getIntent();
String latitude = intent.getStringExtra("Lat");
String longtitude = intent.getStringExtra("Lon");
HttpResponse response;
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost("http://sandbox.kriswelsh.com/hygieneapi/hygiene.php?op=s_loc&lat="+latitude+"&long="+longtitude);
try {
response = myClient.execute(myConnection);
str = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
Here i am trying to retrieve details from the hashamp (latitude and longitude) from the ListViewRestuarants but i always get null values.
import android.content.Intent; import android.support.v4.app.FragmentActivity; import android.os.Bundle; import android.util.Log;
import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions;
import java.util.HashMap;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
static String x;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
//get the value from the array class
Intent intent = getIntent();
HashMap<String, String> hashMap = (HashMap<String, String>)intent.getSerializableExtra("map"); System.out.println(hashmap)
// Log.v("HashMapTest", hashMap.get("Longtitude"));
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title(x));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
} }
This is a main class which display tab view (for more information)
import android.app.TabActivity; import android.content.Intent; import android.os.Bundle; import android.widget.TabHost;
public class MainActivity extends TabActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// create the TabHost that will contain the Tabs
TabHost tabHost = (TabHost)findViewById(android.R.id.tabhost);
TabHost.TabSpec tab1 = tabHost.newTabSpec("First Tab");
TabHost.TabSpec tab2 = tabHost.newTabSpec("Second Tab");
// Set the Tab name and Activity
// that will be opened when particular Tab will be selected
tab1.setIndicator("Restaurant");
tab1.setContent(new Intent(this, ListViewRestaurants.class));
tab2.setIndicator("Map");
tab2.setContent(new Intent(this, RestaurantMap.class));
/** Add the tabs to the TabHost to display. */
tabHost.addTab(tab1);
tabHost.addTab(tab2);
} }
The issue is you are setting a different key in the map but trying to fetch the value corresponding to a different key -
map1.put("Longitude", json.getString("Longitude")); //Setting "Longitude"
Log.v("HashMapTest", hashMap.get("Longtitude")); //Getting "Longtitude"
Apparently, there is no key "Longtitude" in your map.
Best practice is to have constants for keys and use it for insertion and retrieval and this will avoid such issues and will not waste your time debugging in also.

Global Variable Magically Getting Set To Null??

I am using a SMSReceiver class which receives an sms and then sends the sms as an extra to my main activity to use in the map application. In my onReceive method I toast the extra and I get the value perfectly fine, but when I try use the variable later down my code to reverse geoCode to get the coordinates from the address then suddenly the global variable is null again :(
The method is called showOnMapClicked on line 324 where the variable is null again.
The sms is being sent from the DDMS.
Somebody please help, I just cant figure it out!
OnReceive Class:
package com.example.maps;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;
import android.content.Intent;
public class SMSReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
//Adding bundle extras to be used by the main class
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "SMS from ";
//Adding the sms to the array to be stored
if (bundle != null)
{
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i = 0; i < msgs.length; i++) {
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
if (i == 0)
{
//Appending the information to the string to be displayed
str += msgs[i].getOriginatingAddress();
str += ": \n";
}
str += msgs[i].getMessageBody().toString();
}
Toast.makeText(context, str, Toast.LENGTH_LONG).show();
//Creating the new intent
Intent mainActivityIntent = new Intent(context, MainActivity.class);
mainActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(mainActivityIntent);
//Making the intent broadcast to the main class and putting the extra in to be displayed
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("SMS_RECEIVED_ACTION");
//Setting the name of the string to "sms"
broadcastIntent.putExtra("sms", str);
context.sendBroadcast(broadcastIntent);
//Stops the sms from going directly into the inbox
this.abortBroadcast();
}
}
}
Main Activity Class:
package com.example.maps;
//Daniel Tromp - Assignment 2 - 12002076
//Imports for DAYS!
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import com.example.maps.R;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.text.InputFilter;
import android.text.InputType;
import android.text.method.DigitsKeyListener;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
//Implementing all the needed services
public class MainActivity extends Activity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener, LocationListener {
// Initializing the needed globals
Location mLocation;
String addressSms;
String addressText;
public GoogleMap mMap;
private TextView mAddress;
private ProgressBar mActivityIndicator;
private LocationClient mLocationClient;
BroadcastReceiver smsSentReceiver, smsDeliveredReceiver;
IntentFilter intentFilter;
// Milliseconds per second
private static final int MILLISECONDS_PER_SECOND = 1000;
// Update frequency in seconds
public static final int UPDATE_INTERVAL_IN_SECONDS = 5;
// Update frequency in milliseconds
private static final long UPDATE_INTERVAL = MILLISECONDS_PER_SECOND
* UPDATE_INTERVAL_IN_SECONDS;
// The fastest update frequency, in seconds
private static final int FASTEST_INTERVAL_IN_SECONDS = 1;
// A fast frequency ceiling in milliseconds
private static final long FASTEST_INTERVAL = MILLISECONDS_PER_SECOND
* FASTEST_INTERVAL_IN_SECONDS;
// Define an object that holds accuracy and frequency parameters
private LocationRequest mLocationRequest;
private BroadcastReceiver intentReceiver = new BroadcastReceiver() {
#Override
//On receiving a message, the textview is set to the sms message
public void onReceive(Context context, Intent intent) {
addressSms = intent.getStringExtra("sms");
//Toasting the variable where it displays my sms message
Toast.makeText(getBaseContext(), addressSms, Toast.LENGTH_LONG).show();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpMapIfNeeded();
mAddress = (TextView) findViewById(R.id.address);
// As the app loads, the address bar will be displayed
mActivityIndicator = (ProgressBar) findViewById(R.id.address_progress);
// Setting the map type to be Hybrid
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// Create the LocationRequest object
mLocationRequest = LocationRequest.create();
// Use high accuracy
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the update interval to 5 seconds
mLocationRequest.setInterval(UPDATE_INTERVAL);
// Set the fastest update interval to 1 second
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
/*
* Create a new location client, using the enclosing class to handle
* callbacks.
*/
mLocationClient = new LocationClient(this, this, this);
//Creating the new intent
intentFilter = new IntentFilter();
intentFilter.addAction("SMS_RECEIVED_ACTION");
registerReceiver(intentReceiver, intentFilter);
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the
// map.
if (mMap == null) {
mMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
// The Map is verified. It is now safe to manipulate the map.
}
}
}
// When the application is started
#Override
protected void onStart() {
super.onStart();
// Connect the client.
mLocationClient.connect();
}
private class GetAddressTask extends AsyncTask<Location, Void, String> {
Context mContext;
public GetAddressTask(Context context) {
super();
mContext = context;
}
protected String doInBackground(Location... params) {
Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());
// Get the current location from the input parameter list
Location loc = params[0];
// Create a list to contain the result address
List<Address> addresses = null;
try {
/*
* Return 1 address.
*/
addresses = geocoder.getFromLocation(loc.getLatitude(),
loc.getLongitude(), 1);
} catch (IOException e1) {
Log.e("LocationSampleActivity",
"IO Exception in getFromLocation()");
e1.printStackTrace();
return ("IO Exception trying to get address");
} catch (IllegalArgumentException e2) {
// Error message to post in the log
String errorString = "Illegal arguments "
+ Double.toString(loc.getLatitude()) + " , "
+ Double.toString(loc.getLongitude())
+ " passed to address service";
Log.e("LocationSampleActivity", errorString);
e2.printStackTrace();
return errorString;
}
// If the reverse geocode returned an address
if (addresses != null && addresses.size() > 0) {
// Get the first address
Address address = addresses.get(0);
/*
* Format the first line of address (if available), city, and
* country name.
*/
addressText = String.format(
"%s, %s, %s",
// If there's a street address, add it
address.getMaxAddressLineIndex() > 0 ? address
.getAddressLine(0) : "",
// Locality is usually a city
address.getLocality(),
// The country of the address
address.getCountryName());
// Return the text
return addressText;
} else {
return "No address found";
}
}
protected void onPostExecute(String address) {
// Set activity indicator visibility to "gone"
mActivityIndicator.setVisibility(View.GONE);
// Display the results of the lookup.
mAddress.setText(address);
}
}
// When the connection is made to get live updates
public void onConnected(Bundle dataBundle) {
// Display the connection status
Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
// Start periodic updates
mLocationClient.requestLocationUpdates(mLocationRequest, this);
}
// When the new coordinates are put into the DDMS, the map will change to
// that location and get the new address
public void onLocationChanged(Location location) {
// Report to the UI that the location was updated
LatLng latlng = new LatLng(location.getLatitude(),
location.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLng(latlng));
mActivityIndicator.setVisibility(View.VISIBLE);
/*
* Reverse geocoding is long-running and synchronous. Run it on a
* background thread. Pass the current location to the background task.
* When the task finishes, onPostExecute() displays the address.
*/
(new GetAddressTask(this)).execute(location);
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
}
#Override
public void onDisconnected() {
}
// Click on button to get the read me file to know how to use the
// application
public void readMeClicked(View v) {
// Create a dialog to pop up and explain the application to the user
AlertDialog alertDialog = new AlertDialog.Builder(this).create(); // Read
// Update
alertDialog.setTitle("Read Me");
alertDialog
.setMessage("My app was created to be able to quickly send out an emergency SMS to a certain individual which will contain the emergency message as well as their current location. By using the DDMS, the coordinates can be input and then my app will go to that specific location and pull the most correct address of that location");
// Making the dialog show
alertDialog.show();
}
public void getFromLocationClicked(View v) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
MainActivity.this);
// Setting Dialog Title
alertDialog.setTitle("Emergency SMS");
// Setting Dialog Message
alertDialog.setMessage("Enter Emergency Contact Number");
final EditText input = new EditText(MainActivity.this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
alertDialog.setView(input);
// Setting Positive "Continue" Button
alertDialog.setPositiveButton("Continue",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String testing = input.getText().toString();
getFromLocation(testing);
}
});
// Setting Negative "Cancel" Button
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
};
public void getFromLocation(String strAddress) {
Geocoder coder = new Geocoder(this);
List<Address> address;
try {
address = coder.getFromLocationName(strAddress, 5);
if (address != null) {
Address location = address.get(0);
double recLat = location.getLatitude();
double recLng = location.getLongitude();
LatLng p = new LatLng(recLat, recLng);
Toast.makeText(getBaseContext(), p + "", Toast.LENGTH_LONG)
.show();
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(p, 16));
}
} catch (IOException ie) {
ie.printStackTrace();
}
}
//Showing the value when the show button is clicked
public void showOnMapClicked(View v)
{
//When it toasts, the addressSms value is now null!??
Toast.makeText(getBaseContext(), addressSms, Toast.LENGTH_LONG).show();
//getFromLocation(addressSms);
}
public void showToast(String message)
{
String test = message;
Toast.makeText(getBaseContext(), test, Toast.LENGTH_LONG).show();
}
// Click the button to start to generate the emergency SMS
public void sendAddressClicked(final View v) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
MainActivity.this);
// Setting Dialog Title
alertDialog.setTitle("Emergency SMS");
// Setting Dialog Message
alertDialog.setMessage("Enter Emergency Contact Number");
final EditText input = new EditText(MainActivity.this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
alertDialog.setView(input);
input.setFilters(new InputFilter[] {
// Maximum 2 characters.
new InputFilter.LengthFilter(10),
// Digits only.
DigitsKeyListener.getInstance(), // Not strictly needed, IMHO.
});
// Setting Positive "Continue" Button
alertDialog.setPositiveButton("Continue",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Setting the SMS message and adding the current
// location which is gathered by the map.
String textMessage = input.getText().toString();
// Checking if the phone number is not blank
if (textMessage.isEmpty()) {
// If the phone number is not entered
Toast.makeText(getBaseContext(),
"Cannot be blank. Enter phone number.",
Toast.LENGTH_LONG).show();
sendAddressClicked(v);
}
else {
enterMessage(textMessage);
}
}
});
// Setting Negative "Cancel" Button
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
};
// Method to send the emergency method and the current location
private void sendSMS(String phoneNumber, String message) {
// Sending the sms to the emulator number input
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, null, null);
}
// Once the user has input the number, the message now will be asked for
public void enterMessage(final String number) {
// Creating the dialog to input the emergency message
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
MainActivity.this);
// Setting Dialog Title
alertDialog.setTitle("Emergency SMS");
// Setting Dialog Message
alertDialog.setMessage("Enter Emergency SMS");
final EditText input = new EditText(MainActivity.this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
alertDialog.setView(input);
input.setInputType(InputType.TYPE_CLASS_TEXT);
// Setting Positive "SEND SMS" Button
alertDialog.setPositiveButton("SEND SMS",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog
// Setting the SMS message and adding the current
// location which is gathered by the map.
String textMessage = input.getText().toString();
String SMS = textMessage + "\n\n"
+ "My Current Address Is: " + addressText;
String phoneNumber = number;
// Checking to see if the SMS is blank
if (textMessage.isEmpty()) {
Toast.makeText(getBaseContext(),
"Cannot be blank. Enter emergency SMS.",
Toast.LENGTH_LONG).show();
enterMessage(phoneNumber);
}
else {
// Sending the variables through to the sendSMS
// method to be sent
sendSMS(phoneNumber, SMS);
}
}
});
// Setting Negative "Cancel" Button
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
};
}
Try overriding the onSaveInstanceState(Bundle bundle) method in your MainActivity and use logs to see if it is getting called before your data is getting wiped out. I suspect that you'll see it is getting called. If so, just save your 'globals' in the bundle and retrieve them by overriding the onRestoreInstanceState(Bundle bundle)
The DOC should help you with how to save and restore. Whenever the activity needs to be killed for memory or orientation change, onCreate will be called and the 'globals' can be lost that way.
This might help with more details.

Using Intent receiving null data in second activity using putExtra and getExtra methods

I have singlePlaceActivity class from which I want to pass string data like name ,address which I got in OnpostExecute to another Email activity. My singlePlace activity succesfully starts the email activity but I didn't receive putExtra string data in Email activity using getextra method and my string data name,address,phone don't have null values as I verified from logcat.
SinglePlaceActivity:
package info.androidhive.slidingmenu;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.widget.TextView;
public class SinglePlaceActivity extends Activity {
// flag for Internet connection status
Boolean isInternetPresent = false;
// Connection detector class
ConnectionDetector cd;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
// Google Places
GooglePlaces googlePlaces;
// Place Details
PlaceDetails placeDetails;
// Progress dialog
ProgressDialog pDialog;
// KEY Strings
// public static String KEY_REFERENCE = "reference"; // id of the place
public static String reference_value = "reference";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.single_place);
Intent i = getIntent();
// Place referece id
String reference = i.getStringExtra(reference_value);
// Calling a Async Background thread
new LoadSinglePlaceDetails().execute(reference);
}
/**
* Background Async Task to Load Google places
* */
class LoadSinglePlaceDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SinglePlaceActivity.this);
pDialog.setMessage("Passing Restaurent details to Email ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Profile JSON
* */
protected String doInBackground(String... args) {
String reference = args[0];
// creating Places class object
googlePlaces = new GooglePlaces();
// Check if used is connected to Internet
try {
placeDetails = googlePlaces.getPlaceDetails(reference);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed Places into LISTVIEW
* */
if(placeDetails != null){
String status = placeDetails.status;
// check place deatils status
// Check for all possible status
if(status.equals("OK")){
if (placeDetails.result != null) {
String name = placeDetails.result.name;
String address = placeDetails.result.formatted_address;
String phone = placeDetails.result.formatted_phone_number;
String latitude = Double.toString(placeDetails.result.geometry.location.lat);
String longitude = Double.toString(placeDetails.result.geometry.location.lng);
Intent in = new Intent(getApplicationContext(),Email.class);
in.putExtra("nameValue",name );
in.putExtra("addValue",address );
in.putExtra("urlValue",phone );
startActivity(in);
Log.d("Place ", name + address + phone + latitude + longitude);
}
}
else if(status.equals("ZERO_RESULTS")){
alert.showAlertDialog(SinglePlaceActivity.this, "Near Places",
"Sorry no place found.",
false);
}
else if(status.equals("UNKNOWN_ERROR"))
{
alert.showAlertDialog(SinglePlaceActivity.this, "Places Error",
"Sorry unknown error occured.",
false);
}
else if(status.equals("OVER_QUERY_LIMIT"))
{
alert.showAlertDialog(SinglePlaceActivity.this, "Places Error",
"Sorry query limit to google places is reached",
false);
}
else if(status.equals("REQUEST_DENIED"))
{
alert.showAlertDialog(SinglePlaceActivity.this, "Places Error",
"Sorry error occured. Request is denied",
false);
}
else if(status.equals("INVALID_REQUEST"))
{
alert.showAlertDialog(SinglePlaceActivity.this, "Places Error",
"Sorry error occured. Invalid Request",
false);
}
else
{
alert.showAlertDialog(SinglePlaceActivity.this, "Places Error",
"Sorry error occured.",
false);
}
}else{
alert.showAlertDialog(SinglePlaceActivity.this, "Places Error",
"Sorry error occured.",
false);
}
}
});
}
}
}
And this is my second receiving activity that is Email activity
Email.java
package info.androidhive.slidingmenu;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class Email extends Activity implements View.OnClickListener {
EditText personsEmail, rname, radd, rurl, yourmsg;
String emailAdd, beginning, stupidAction, hatefulAct, address;
Button sendEmail;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.email);
//String beginning = getIntent().getStringExtra("extraname") ;//returns null if nothing
// String address = getIntent().getStringExtra("extraname2");
//String stupidAction = getIntent().getStringExtra("extraname2");
beginning = getIntent().getStringExtra("nameValue");
address = getIntent().getStringExtra("addValue");
stupidAction= getIntent().getStringExtra("urlValue");
// beginning = intent.getStringExtra("nameValue");
//address = intent.getStringExtra("addValue");
// stupidAction = intent.getStringExtra("urlValue");
initializeVars();
sendEmail.setOnClickListener(this);
}
private void initializeVars() {
// TODO Auto-generated method stub
personsEmail = (EditText) findViewById(R.id.etEmails);
rname = (EditText) findViewById(R.id.etIntro);
radd = (EditText) findViewById(R.id.etName);
rurl = (EditText) findViewById(R.id.etThings);
yourmsg = (EditText) findViewById(R.id.etAction);
sendEmail = (Button) findViewById(R.id.bSentEmail);
}
public void onClick(View v) {
// TODO Auto-generated method stub
convertEditTextVarsIntoStringsAndYesThisIsAMethodWeCreated();
String emailaddress[] = { emailAdd };
String message = "Restaurent Name:"+ beginning
+ " Restaurent Address:"+ address
+ "Click for more details:" + stupidAction
+ "Message:" + hatefulAct;
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, emailaddress);
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT," Restaurent Recommendation");
emailIntent.setType("plain/text");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, message);
startActivity(emailIntent);
}
private void convertEditTextVarsIntoStringsAndYesThisIsAMethodWeCreated() {
// TODO Auto-generated method stub
emailAdd = personsEmail.getText().toString();
beginning = rname.getText().toString();
address = radd.getText().toString();
stupidAction = rurl.getText().toString();
hatefulAct = yourmsg.getText().toString();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
Try bundle to pass and receive data,
Intent intent = new Intent(first.this, second.class);
Bundle bundle = new Bundle();
bundle.putInt("index", index);
intent.putExtras(bundle);
startActivity(intent);
Receive data:
Bundle b = getIntent().getExtras();
int index = b.getInt("index");
If you use AsyncTask there is no need of any background thread inside onPostExecute(...). So, remove the thread inside onPostExecute(...) your problem will be solved if those values you are sending not null in onPostExecute(..).
AsyncTask enables proper and easy use of the UI thread. This class
allows to perform background operations and publish results on the UI
thread without having to manipulate threads and/or handlers.
Try this code for onPostExecute(String response) instead of yours
protected void onPostExecute(String response) {
// dismiss the dialog after getting all products
pDialog.dismiss();
/**
* Updating parsed Places into LISTVIEW
* */
if (placeDetails != null) {
String status = placeDetails.status;
// check place deatils status
// Check for all possible status
if (status.equals("OK")) {
if (placeDetails.result != null) {
String name = placeDetails.result.name;
String address = placeDetails.result.formatted_address;
String phone = placeDetails.result.formatted_phone_number;
String latitude = Double
.toString(placeDetails.result.geometry.location.lat);
String longitude = Double
.toString(placeDetails.result.geometry.location.lng);
Intent in = new Intent(getApplicationContext(), Email.class);
in.putExtra("nameValue", name);
in.putExtra("addValue", address);
in.putExtra("urlValue", phone);
startActivity(in);
Log.d("Place ", name + address + phone + latitude
+ longitude);
}
} else if (status.equals("ZERO_RESULTS")) {
alert.showAlertDialog(SinglePlaceActivity.this, "Near Places",
"Sorry no place found.", false);
} else if (status.equals("UNKNOWN_ERROR")) {
alert.showAlertDialog(SinglePlaceActivity.this, "Places Error",
"Sorry unknown error occured.", false);
} else if (status.equals("OVER_QUERY_LIMIT")) {
alert.showAlertDialog(SinglePlaceActivity.this, "Places Error",
"Sorry query limit to google places is reached", false);
} else if (status.equals("REQUEST_DENIED")) {
alert.showAlertDialog(SinglePlaceActivity.this, "Places Error",
"Sorry error occured. Request is denied", false);
} else if (status.equals("INVALID_REQUEST")) {
alert.showAlertDialog(SinglePlaceActivity.this, "Places Error",
"Sorry error occured. Invalid Request", false);
} else {
alert.showAlertDialog(SinglePlaceActivity.this, "Places Error",
"Sorry error occured.", false);
}
} else {
alert.showAlertDialog(SinglePlaceActivity.this, "Places Error",
"Sorry error occured.", false);
}
}
I spent weeks on this problem. It seems that you should take note of what data type the value is stored as in the "sender" activity. As I have different activities which starts my "receiver" activity, I added this if statement to handle both data types (considering someId is a Long Data Type).
someId = getIntent().getLongExtra(EXTRA_ID,0);
if (someId < 1){
someId = Long.parseLong(getIntent().getStringExtra(EXTRA_ID));
}
Unfortunately I can not explain why, maybe some Guru can enlighten us common folk...

How to parse and plot gpx file has an android MapView

I'm working to implement MapView for the given gpx file to show way points and tracks,please any one guide me to implement it with sample code.
Thanks in advance.
It is working correctly
package com.lightcone.mapoverlaydemo;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
public class ShowTheMap extends MapActivity {
private static double lat;
private static double lon;
private int latE6;
private int lonE6;
private MapController mapControl;
private GeoPoint gp;
private MapView mapView;
private Button overlayButton, accessButton;
private Button routeButton;
private List<Overlay> mapOverlays;
private Drawable drawable1, drawable2;
private MyItemizedOverlay itemizedOverlay1, itemizedOverlay2;
private boolean foodIsDisplayed = false;
// Define an array containing the food overlay items
private OverlayItem[] foodItem = {
new OverlayItem(new GeoPoint(35952967, -83929158), "Food Title 1",
"Food snippet 1"),
new OverlayItem(new GeoPoint(35953000, -83928000), "Food Title 2",
"Food snippet 2"),
new OverlayItem(new GeoPoint(35955000, -83929158), "Food Title 3",
"Food snippet 3") };
// Define an array containing the access overlay items
private OverlayItem[] accessItem = {
new OverlayItem(new GeoPoint(35953700, -83926158),
"Access Title 1", "Access snippet 1"),
new OverlayItem(new GeoPoint(35954000, -83928200),
"Access Title 2", "Access snippet 2"),
new OverlayItem(new GeoPoint(35955000, -83927558),
"Access Title 3", "Access snippet 3"),
new OverlayItem(new GeoPoint(35954000, -83927158),
"Access Title 4", "Access snippet 4") };
String TAG = "GPStest";
// Set up the array of GeoPoints defining the route
int numberRoutePoints;
GeoPoint routePoints[]; // Dimension will be set in class RouteLoader below
int routeGrade[]; // Index for slope of route from point i to point i+1
RouteSegmentOverlay route; // This will hold the route segments
boolean routeIsDisplayed = false;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); // Suppress title bar for
// more space
setContentView(R.layout.showthemap);
// Add map controller with zoom controls
mapView = (MapView) findViewById(R.id.mv);
mapView.setSatellite(false);
mapView.setTraffic(false);
mapView.setBuiltInZoomControls(true); // Set android:clickable=true in
// main.xml
int maxZoom = mapView.getMaxZoomLevel();
int initZoom = maxZoom - 2;
mapControl = mapView.getController();
mapControl.setZoom(initZoom);
// Convert lat/long in degrees into integers in microdegrees
latE6 = (int) (35.955 * 1e6);
lonE6 = (int) (-83.9265 * 1e6);
gp = new GeoPoint(latE6, lonE6);
mapControl.animateTo(gp);
// // Button to control food overlay
// overlayButton = (Button)findViewById(R.id.doOverlay);
// overlayButton.setOnClickListener(new OnClickListener(){
// public void onClick(View v) {
// setOverlay1();
// }
// });
//
// // Button to control access overlay
// accessButton = (Button)findViewById(R.id.doAccess);
// accessButton.setOnClickListener(new OnClickListener(){
// public void onClick(View v) {
// setOverlay2();
// }
// });
// Button to control route overlay
routeButton = (Button) findViewById(R.id.doRoute);
routeButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (!routeIsDisplayed) {
routeIsDisplayed = true;
loadRouteData();
} else {
if (route != null)
route.setRouteView(false);
route = null; // To prevent multiple route instances if key
// toggled rapidly (see line 235)
routeIsDisplayed = false;
mapView.postInvalidate();
}
}
});
}
/*
* Methods to set map overlays. In this case we will place a small overlay
* image at a specified location. Place the marker image as a png file in
* res > drawable-* . For example, the reference to
* R.drawable.knifefork_small below is to an image file called
* knifefork_small.png in the project folder res > drawable-hdpi. Can only
* use lower case letters a-z, numbers 0-9, ., and _ in these image file
* names. In this example the single overlay item is specified by drawable
* and the location of the overlay item is specified by overlayitem.
*/
// Display food location overlay. If not already displayed, clicking button
// displays all
// food overlays. If already displayed successive clicks remove items one by
// one. This
// illustrates ability to change individual overlay items dynamically at
// runtime.
public void setOverlay1() {
int foodLength = foodItem.length;
// Create itemizedOverlay2 if it doesn't exist and display all three
// items
if (!foodIsDisplayed) {
mapOverlays = mapView.getOverlays();
drawable1 = this.getResources().getDrawable(
R.drawable.knifefork_small);
itemizedOverlay1 = new MyItemizedOverlay(drawable1);
// Display all three items at once
for (int i = 0; i < foodLength; i++) {
itemizedOverlay1.addOverlay(foodItem[i]);
}
mapOverlays.add(itemizedOverlay1);
foodIsDisplayed = !foodIsDisplayed;
// Remove each item successively with button clicks
} else {
itemizedOverlay1.removeItem(itemizedOverlay1.size() - 1);
if ((itemizedOverlay1.size() < 1))
foodIsDisplayed = false;
}
// Added symbols will be displayed when map is redrawn so force redraw
// now
mapView.postInvalidate();
}
// Display accessibility overlay. If not already displayed, successive
// button clicks display each of
// the three icons successively, then the next removes them all. This
// illustrates the ability to
// change individual overlay items dynamically at runtime.
public void setOverlay2() {
int accessLength = accessItem.length;
// Create itemizedOverlay2 if it doesn't exist
if (itemizedOverlay2 == null) {
mapOverlays = mapView.getOverlays();
drawable2 = this.getResources().getDrawable(
R.drawable.accessibility);
itemizedOverlay2 = new MyItemizedOverlay(drawable2);
}
// Add items with each click
if (itemizedOverlay2.size() < accessLength) {
itemizedOverlay2.addOverlay(accessItem[itemizedOverlay2.size()]);
mapOverlays.add(itemizedOverlay2);
// Remove all items with one click
} else {
for (int i = 0; i < accessLength; i++) {
itemizedOverlay2.removeItem(accessLength - 1 - i);
}
}
// Added symbols will be displayed when map is redrawn so force redraw
// now
mapView.postInvalidate();
}
// Method to insert latitude and longitude in degrees
public static void putLatLong(double latitude, double longitude) {
lat = latitude;
lon = longitude;
}
// This sets the s key on the phone to toggle between satellite and map view
// and the t key to toggle between traffic and no traffic view (traffic view
// relevant only in urban areas where it is reported).
public boolean onKeyDown(int keyCode, KeyEvent e) {
if (keyCode == KeyEvent.KEYCODE_S) {
mapView.setSatellite(!mapView.isSatellite());
return true;
} else if (keyCode == KeyEvent.KEYCODE_T) {
mapView.setTraffic(!mapView.isTraffic());
mapControl.animateTo(gp); // To ensure change displays immediately
}
return (super.onKeyDown(keyCode, e));
}
// Required method since class extends MapActivity
#Override
protected boolean isRouteDisplayed() {
return false; // Don't display a route
}
// Method to read route data from server as XML
public void loadRouteData() {
try {
String url = "http://eagle.phys.utk.edu/reubendb/UTRoute.php";
String data = "?lat1=35952967&lon1=-83929158&lat2=35956567&lon2=-83925450";
// RouteLoader RL = new RouteLoader();
// RL.execute(new URL(url+data));
new RouteLoader().execute(new URL(url + data));
} catch (MalformedURLException e) {
Log.i("NETWORK", "Failed to generate valid URL");
}
}
// Overlay a route. This method is only executed after loadRouteData()
// completes
// on background thread.
public void overlayRoute() {
if (route != null)
return; // To prevent multiple route instances if key toggled
// rapidly (see also line 116)
// Set up the overlay controller
route = new RouteSegmentOverlay(routePoints, routeGrade); // My class
// defining
// route
// overlay
mapOverlays = mapView.getOverlays();
mapOverlays.add(route);
// Added symbols will be displayed when map is redrawn so force redraw
// now
mapView.postInvalidate();
}
/*
* Class to implement single task on background thread without having to
* manage the threads directly. Launch with
* "new RouteLoader().execute(new URL(urlString)". Must be launched from the
* UI thread and may only be invoked once. Adapted from example in Ch. 10 of
* Android Wireless Application Development. Use this to do data load from
* network on separate thread from main user interface to prevent locking
* main UI if there is network delay.
*/
private class RouteLoader extends AsyncTask<URL, String, String> {
#Override
protected String doInBackground(URL... params) {
// This pattern takes more than one param but we'll just use the
// first
try {
URL text = params[0];
XmlPullParserFactory parserCreator;
parserCreator = XmlPullParserFactory.newInstance();
XmlPullParser parser = parserCreator.newPullParser();
// parser.setInput(text.openStream(), null);
parser.setInput(getResources()
.openRawResource(R.raw.fells_loop), null);
publishProgress("Parsing XML...");
int parserEvent = parser.getEventType();
int pointCounter = -1;
int wptCounter = -1;
int totalWaypoints = -1;
int lat = -1;
int lon = -1;
String wptDescription = "";
int grade = -1;
// Parse the XML returned on the network
while (parserEvent != XmlPullParser.END_DOCUMENT) {
switch (parserEvent) {
case XmlPullParser.START_TAG:
String tag = parser.getName();
if (tag.compareTo("number") == 0) {
numberRoutePoints = Integer.parseInt(parser
.getAttributeValue(null, "numpoints"));
totalWaypoints = Integer.parseInt(parser
.getAttributeValue(null, "numwpts"));
routePoints = new GeoPoint[numberRoutePoints];
routeGrade = new int[numberRoutePoints];
Log.i(TAG, " Total points = " + numberRoutePoints
+ " Total waypoints = " + totalWaypoints);
}
if (tag.compareTo("trkpt") == 0) {
pointCounter++;
lat = Integer.parseInt(parser.getAttributeValue(
null, "lat"));
lon = Integer.parseInt(parser.getAttributeValue(
null, "lon"));
grade = Integer.parseInt(parser.getAttributeValue(
null, "grade"));
routePoints[pointCounter] = new GeoPoint(lat, lon);
routeGrade[pointCounter] = grade;
Log.i(TAG, " trackpoint=" + pointCounter
+ " latitude=" + lat + " longitude=" + lon
+ " grade=" + grade);
} else if (tag.compareTo("wpt") == 0) {
wptCounter++;
lat = Integer.parseInt(parser.getAttributeValue(
null, "lat"));
lon = Integer.parseInt(parser.getAttributeValue(
null, "lon"));
wptDescription = parser.getAttributeValue(null,
"description");
Log.i(TAG, " waypoint=" + wptCounter
+ " latitude=" + lat + " longitude=" + lon
+ " " + wptDescription);
}
break;
}
parserEvent = parser.next();
}
} catch (Exception e) {
Log.i("RouteLoader", "Failed in parsing XML", e);
return "Finished with failure.";
}
return "Done...";
}
protected void onCancelled() {
Log.i("RouteLoader", "GetRoute task Cancelled");
}
// Now that route data are loaded, execute the method to overlay the
// route on the map
protected void onPostExecute(String result) {
Log.i(TAG, "Route data transfer complete");
overlayRoute();
}
protected void onPreExecute() {
Log.i(TAG, "Ready to load URL");
}
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
}
}
}
feel_loop.xml file content from raw folder
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<gpx
version="1.0"
creator="ExpertGPS 1.1.1 - http://www.topografix.com"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.topografix.com/GPX/1/0"
xmlns:topografix="http://www.topografix.com/GPX/Private/TopoGrafix/0/1"
xsi:schemaLocation="http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd http://www.topografix.com/GPX/Private/TopoGrafix/0/1 http://www.topografix.com/GPX/Private/TopoGrafix/0/1/topografix.xsd">
<number numpoints="23" numwpts="2"></number>
<wpt lat="35952967" lon="-83929158" description="Construction"></wpt>
<wpt lat="35955038" lon="-83929126" description="Heavy traffic"></wpt>
<trk>
<trkseg>
<trkpt lat="35952967" lon="-83929158" grade="1"></trkpt>
<trkpt lat="35954021" lon="-83930341" grade="1"></trkpt>
<trkpt lat="35954951" lon="-83929075" grade="1"></trkpt>
<trkpt lat="35955038" lon="-83929126" grade="4"></trkpt>
<trkpt lat="35955203" lon="-83928973" grade="1"></trkpt>
<trkpt lat="35955212" lon="-83928855" grade="1"></trkpt>
<trkpt lat="35955603" lon="-83928273" grade="2"></trkpt>
<trkpt lat="35955807" lon="-83928369" grade="1"></trkpt>
<trkpt lat="35955974" lon="-83927943" grade="1"></trkpt>
<trkpt lat="35956063" lon="-83927720" grade="1"></trkpt>
<trkpt lat="35956291" lon="-83927358" grade="1"></trkpt>
<trkpt lat="35956471" lon="-83927229" grade="1"></trkpt>
<trkpt lat="35956541" lon="-83927176" grade="2"></trkpt>
<trkpt lat="35956397" lon="-83927044" grade="3"></trkpt>
<trkpt lat="35956274" lon="-83926685" grade="1"></trkpt>
<trkpt lat="35956213" lon="-83926642" grade="1"></trkpt>
<trkpt lat="35956239" lon="-83926261" grade="1"></trkpt>
<trkpt lat="35956202" lon="-83925722" grade="1"></trkpt>
<trkpt lat="35956226" lon="-83925467" grade="1"></trkpt>
<trkpt lat="35956343" lon="-83925502" grade="1"></trkpt>
<trkpt lat="35956324" lon="-83925617" grade="1"></trkpt>
<trkpt lat="35956445" lon="-83925379" grade="1"></trkpt>
<trkpt lat="35956567" lon="-83925450" grade="1"></trkpt>
</trkseg>
</trk>
</gpx>
Building on Kandha's answer, for the actual GPX parsing you can easily use one of the existing libraries to do it. See this other StackOverflow question.

Categories

Resources