Get the lat and lang from the Geo coding API? - android

I want to get the latitude and longitude positions from the Geo Coding API. I wrote the following code for that.
package com.appulento.mapsexample.pack;
import android.graphics.Point;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
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.Projection;
import com.mapsinfo.pack.DBAdapter;
public class MapsMianClass extends MapActivity {
private MapController mapController;
private LocationManager locationManager;
private MapView mapView;
List<Overlay> listOfOverlays ;
private List mapOverlays;
private Projection projection;
private Geocoder geoCoder;
private MapController mc;
private GeoPoint gP;
private DBAdapter db;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//here i am giving the Maps Geo coding API URL
Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true_or_false"));
startActivity(intent);
//starting the Intent
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
//default method of maps Activity.
}
}
Is it correct? How can I incorporate JSON in the above code for getting latitude and longitude values from the URL?

Try this Code
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
public class MyActivity extends Activity {
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
AsyncTask<String, Void, Void> stringVoidVoidAsyncTask = new AsyncTask<String, Void, Void>() {
BufferedReader in;
#Override
protected Void doInBackground(String... strings) {
String url = "";
if (strings.length > 0) {
url = strings[0];
} else {
return null;
}
try {
HttpClient httpClient = new DefaultHttpClient();// Client
HttpGet getRequest = new HttpGet();
getRequest.setURI(new URI(url));
HttpResponse response = httpClient.execute(getRequest);
in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String page = sb.toString();
JSONObject jsonObject = new JSONObject(page);
JSONArray jsonArray = (JSONArray) jsonObject.get("results");
if (jsonArray.length() > 0) {
jsonObject = (JSONObject) jsonArray.get(0);
jsonObject = (JSONObject) jsonObject.get("geometry");
JSONObject location = (JSONObject) jsonObject.get("location");
Double lat = (Double) location.get("lat");
Double lng = (Double) location.get("lng");
System.out.println("lat - " + lat + " , lon - " + lng);
}
System.out.println(page);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
};
stringVoidVoidAsyncTask.execute("http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true");
}
}
And do add permission in AndroidManifest for Internet
<uses-permission android:name="android.permission.INTERNET"/>
And for next time do homework before asking question do googleing first. Hope this help you.

What are you want to start in StartActivity() method in Activity's onCreate()?
You should go for http request using HttpClient
and parse the response from it

Related

Sending GPS latitude and longitude to database from Android

I am working on an android app that is supposed to send gps locations to mysql database using php.
I have the Set_Location class which gets the gps location of a user upon the click of a button and the BackgroundLocation class which is supposed to send these coordinates to the mysql database. I have a problem passing these values. I am using context on the BackgroundLocation class and passing the values as parameters. Here is my Set_Location class:
package com.example.bensonkorir.m_ulinzi;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.provider.Settings;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Set_Location extends AppCompatActivity implements LocationListener {
private Button button;
private TextView textView,latitude,longitude;
private LocationListener locationListener;
private LocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set__location);
button = (Button) findViewById(R.id.button);
textView = (TextView) findViewById(R.id.textView);
latitude = (TextView) findViewById(R.id.lat);
longitude = (TextView) findViewById(R.id.lon);
locationManager=(LocationManager)getSystemService(LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
double lat= location.getLatitude();
double lon= location.getLongitude();
String type="location";
latitude.setText(Double.toString(lat));
longitude.setText(Double.toString(lon));
String lat2 = String.valueOf(location.getLatitude());
String lon2= String.valueOf(location.getLongitude());
BackgroundLocation backgroundLocation = new BackgroundLocation(this);
backgroundLocation.execute(type, lat2,lon2);
textView.append("\n"+location.getLatitude()+","+location.getLongitude());
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
};
ConfigureButton();
}
private void ConfigureButton() {
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
locationManager.requestLocationUpdates("gps",5000,0,locationListener);
}
});
}
}
and this is my BackgroundLocation Class:
package com.example.bensonkorir.m_ulinzi;
import android.app.AlertDialog;
import android.content.Context;
import android.location.LocationListener;
import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
public class BackgroundLocation extends AsyncTask<String, Void, String> {
LocationListener locationListener;
AlertDialog alertDialog;
BackgroundLocation (LocationListener locationListener){ this.locationListener= locationListener;}
#Override
protected String doInBackground(String... params) {
String Register_Url= "http://192.168.43.254/register2.php";
String type = params[0];
if(type.equals("location")){
try {
String langitude=params[1];
String longitude=params[2];
URL url= new URL(Register_Url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data= URLEncoder.encode("username", "UTF-8")+"="+URLEncoder.encode(String.valueOf(langitude),"UTF-8")+"&"
+URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(String.valueOf(longitude),"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result="";
String line;
while ((line=bufferedReader.readLine())!=null){
result += line;
}
bufferedReader.close();;
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
alertDialog= new AlertDialog.Builder((Context) locationListener).create();
alertDialog.setTitle(" Status");
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
alertDialog.setMessage(result);
alertDialog.show();
}
}
Kindly assist me with this or point me in the right direction, thanks.

Get current location using json

Hi i a m writing an application whih gets the current latitude and longitude and convert it to corrsponding address.i can get the lattitude and longitutde but how to convert it to the corresponding address using json. i am new to json. i tried some sample codes butnot getting the address
This is my code
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.maps.GeoPoint;
public class GMapActivity extends FragmentActivity {
private GoogleMap map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
LocationManager locManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener locListener = new GpsActivity(getBaseContext());
locManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, locListener);
if (map == null) {
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
map.setMyLocationEnabled(true);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.map, menu);
return true;
}
private class GpsActivity implements LocationListener{
Marker marker;
Context mcontext;
public GpsActivity(Context context){
super();
mcontext=context;
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if (location != null) {
double latitude=location.getLatitude();
double longitude=location.getLongitude();
LatLng gpslocation=new LatLng(latitude,longitude);
Toast.makeText(getApplicationContext(),"" +gpslocation,
Toast.LENGTH_LONG).show();
pls help me
thanks in advance
To change back human readable format, you can also use Geocoder but that is not working sometimes because google play service problem. I used this json geocodeing as second option for in case.
Please refer Google Geocoding API
Workflow is pass your latitude and longitude and get current location. Request url gonna be like this.
String reqURL = "http://maps.googleapis.com/maps/api/geocode/json?latlng="+ lat+","+lng +"&sensor=true";
Hopefully, this answer will help you.
public static JSONObject getLocationInfo(double lat, double lng) {
HttpGet httpGet = new HttpGet("http://maps.googleapis.com/maps/api/geocode/json?latlng="+ lat+","+lng +"&sensor=true");
HttpClient client = new DefaultHttpClient();
HttpResponse response;
StringBuilder stringBuilder = new StringBuilder();
try {
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
JSONObject jsonObject = new JSONObject();
try {
jsonObject = new JSONObject(stringBuilder.toString());
} catch (JSONException e) {
e.printStackTrace();
}
return jsonObject;
}
public static String getCurrentLocationViaJSON(double lat, double lng) {
JSONObject jsonObj = getLocationInfo(lat, lng);
Log.i("JSON string =>", jsonObj.toString());
String currentLocation = "testing";
String street_address = null;
String postal_code = null;
try {
String status = jsonObj.getString("status").toString();
Log.i("status", status);
if(status.equalsIgnoreCase("OK")){
JSONArray results = jsonObj.getJSONArray("results");
int i = 0;
Log.i("i", i+ "," + results.length() ); //TODO delete this
do{
JSONObject r = results.getJSONObject(i);
JSONArray typesArray = r.getJSONArray("types");
String types = typesArray.getString(0);
if(types.equalsIgnoreCase("street_address")){
street_address = r.getString("formatted_address").split(",")[0];
Log.i("street_address", street_address);
}else if(types.equalsIgnoreCase("postal_code")){
postal_code = r.getString("formatted_address");
Log.i("postal_code", postal_code);
}
if(street_address!=null && postal_code!=null){
currentLocation = street_address + "," + postal_code;
Log.i("Current Location =>", currentLocation); //Delete this
i = results.length();
}
i++;
}while(i<results.length());
Log.i("JSON Geo Locatoin =>", currentLocation);
return currentLocation;
}
} catch (JSONException e) {
Log.e("testing","Failed to load JSON");
e.printStackTrace();
}
return null;
}
As my experience, only device generated latitude and longitude will work.
Then call
String currentLocation = getCurrentLocationViaJSON(lat, lng);

user bug in my app I can not reproduce

I have a feature in my app that gets a users gps coordinates then returns nearby breweries. When I use the feature it has never forced closed, and others have tested it to and it worked. One user reported this error when they opened the activity that gets the user location and tries to get the location of breweries:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.beerportfolio.beerportfoliopro/com.example.beerportfoliopro.FindBrewery}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2355)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2391)
at android.app.ActivityThread.access$600(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1335)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5511)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1029)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:796)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.beerportfoliopro.FindBrewery.onCreate(FindBrewery.java:42)
at android.app.Activity.performCreate(Activity.java:5066)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1101)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2311)
... 11 more
My activity that is launched is:
package com.example.beerportfoliopro;
import android.content.Context;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;
import com.beerportfolio.beerportfoliopro.R;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
/**
* Created by mike on 7/3/13.
*/
public class FindBrewery extends ActionbarMenu {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.beer_location_list);
String title = "Nearby Breweries";
TextView topTitle = (TextView) findViewById(R.id.beerLocationTitle);
topTitle.setText(title);
//get user location
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
//construct url
String url = myURLandKey;
Log.d("urlTest",url);
//async task goes here
new GetNearbyBreweries(this).execute(url);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main2, menu);
return true;
}
}
Lastly my asynctask is:
package com.example.beerportfoliopro;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import com.beerportfolio.beerportfoliopro.R;
public class GetNearbyBreweries extends AsyncTask
<String, Void, String> {
Context c;
private ProgressDialog Dialog;
public GetNearbyBreweries (Context context)
{
c = context;
Dialog = new ProgressDialog(c);
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return readJSONFeed(arg0[0]);
}
protected void onPreExecute() {
Dialog.setMessage("Locating Breweries");
Dialog.setTitle("Loading");
Dialog.setCancelable(false);
Dialog.show();
}
protected void onPostExecute(String result){
//decode json here
try{
JSONObject json = new JSONObject(result);
//acces listview
ListView lv = (ListView) ((Activity) c).findViewById(R.id.locationList);
//make array list for beer
final List<BreweryLocationData> tasteList = new ArrayList<BreweryLocationData>();
for(int i = 0; i < json.getJSONArray("data").length(); i++) {
String brewery = json.getJSONArray("data").getJSONObject(i).getJSONObject("brewery").getString("name");
String id = json.getJSONArray("data").getJSONObject(i).getJSONObject("brewery").getString("id");
String latitude = json.getJSONArray("data").getJSONObject(i).getString("latitude");
String longitude = json.getJSONArray("data").getJSONObject(i).getString("longitude");
String distance = json.getJSONArray("data").getJSONObject(i).getString("distance");
int count = i + 1;
//create object
BreweryLocationData tempLocation = new BreweryLocationData(brewery, id, longitude , latitude,distance);
//add to arraylist
tasteList.add(tempLocation);
//add items to listview
BreweryLocationInfoAdapter adapter1 = new BreweryLocationInfoAdapter(c ,R.layout.listview_item_row, tasteList);
lv.setAdapter(adapter1);
//set up clicks
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
BreweryLocationData o=(BreweryLocationData)arg0.getItemAtPosition(arg2);
String tempID = o.id;
Toast toast = Toast.makeText(c, tempID, Toast.LENGTH_SHORT);
toast.show();
//get beer details from id
Intent myIntent = new Intent(c, BreweryPage2.class);
myIntent.putExtra("id", tempID);
c.startActivity(myIntent);
}
});
}
}
catch(Exception e){
}
Dialog.dismiss();
}
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} else {
Log.d("JSON", "Failed to download file");
}
} catch (Exception e) {
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
}
You are getting a force close when attempting to get the users location. I would add validation that the use has GPS enabled and if not then give them an alert dialog asking them to enable, you may also send them directly to GPS settings.
Can the user reproduce the error?
From your code listing it seems line 42 is(maybe you edited it though):
39 LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
40 Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
41 double longitude = location.getLongitude();
42 double latitude = location.getLatitude();
Cant see why getLatitude() would break and not getLongitude()
You should validate location, to make sure you have it.
As a couple of others have pointed out, it is telling you that the error is on line 42. Unfortunately you have slightly affected the line numbers pasting it here. On your line 42 you are assuming something is not null, and it actually is null.
Given that LocationManager#getLastKnownLocation can return null, and you're not checking for that, I'd say that was your issue, and that your line 42 is where you call location.getLongitude().
getLastKnownLocation will only return a Location if the provider you specify has been used recently. If nothing has forced it to find a location yet, or for a long time (Android considers the last location too old to be correct), then you will get null.

Cant get Geopoints to add to google map due to; Couldn't get connection factory client

I am getting this error while try to plot multiple Geopoint locations onto a google map. I am reading the latitude and longitude from a MySQL database through PHP and JSON. I have looked at the main examples, such as Couldn't get connection factory client, Couldn't get connection factory client - fighting with Google Maps, Android MapActivity : Couldn't get connection factory client.I can confirm it is not an invalid API key as I have generated 2 different keys and returned the same error. It is also not an API level problem either, I tried to run the application on API level 17 and on level 8 and still no joy. When I run the code it displays the map no problem and then gets to my exception toast message of "Error displaying contents" Here is my mapview.java code:
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.graphics.drawable.Drawable;
import android.net.ParseException;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
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 mapview extends MapActivity
{
//protected MapView mapview;
JSONArray jarray;
String result=null;
InputStream is=null;
StringBuilder sb=null;
double LAT;
double LNG;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.mapview);
MapView mapview = (MapView) findViewById(R.id.mapview);
mapview.setBuiltInZoomControls(true);
//ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/displaymarkers.php");
//httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection"+e.toString());
}
try{
jarray = new JSONArray("$json_output[]");
JSONObject json_data = null;
for(int i = 0; i < jarray.length(); i++)
{
json_data = jarray.getJSONObject(i);
LAT=json_data.getDouble("lat");
LNG=json_data.getDouble("lng");
GeoPoint point = new GeoPoint((int)(LAT * 1E6), (int)(LNG * 1E6));
OverlayItem overlayitem = new OverlayItem(point, "TEXT", null);
List<Overlay> mapOverlays = mapview.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.marker);
myItemizedOverlay itemizedoverlay = new myItemizedOverlay(drawable, this);
MapController mapController = mapview.getController();
//mapController.animateTo(point);
mapController.setZoom(8);
itemizedoverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedoverlay);
}
}
catch(JSONException e1)
{
Toast.makeText(getBaseContext(), "Error displaying contents" ,Toast.LENGTH_LONG).show();
}
catch (ParseException e1)
{
e1.printStackTrace();
}
}
#Override
protected boolean isRouteDisplayed()
{
return false;
}
}
This is my ItemizedOverlay.java code:
import java.util.ArrayList;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.drawable.Drawable;
import com.google.android.maps.OverlayItem;
import com.google.android.maps.ItemizedOverlay;
public class myItemizedOverlay extends ItemizedOverlay
{
private ArrayList<OverlayItem> mapOverlays = new ArrayList<OverlayItem>();
private Context mContext;
public myItemizedOverlay(Drawable marker, Context context)
{
super(boundCenterBottom(marker));
mContext = context;
}
public void addOverlay(OverlayItem overlay)
{
mapOverlays.add(overlay);
this.populate();
}
#Override
protected OverlayItem createItem(int i)
{
return mapOverlays.get(i);
}
#Override
public int size()
{
return mapOverlays.size();
}
#Override
protected boolean onTap(int index)
{
OverlayItem item = mapOverlays.get(index);
AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
dialog.setTitle(item.getTitle());
dialog.setMessage(item.getSnippet());
dialog.show();
return true;
}
}
I would appreciate any help I get, thanks in advance.
If you have generated these keys recently, you will not get your results, because API v1 is deprecated and won't work.
You may want to switch to Maps API v2: https://developers.google.com/maps/documentation/android/
Don't try to use your old code, because new API doesn't share any code with API v1.

How to handle - Application has stopped working in Android

So I am trying to create an Android app which basically reads out the twitter feed according to the search query inside a UI. The feed that I need to display form the parsed JSON is the user name, handle, profile picture and the tweet.
Now I have created the whole thing and my code compiles but as soon as I run it the app opens and I write something in the search feed and hit enter - " Unfortunately, AppName has stopped working " I am attaching my logcat and my source code for reference.
*Solved the issue by removing set text from DoInBackground and then giving adequate permission for Android to access internet. The issue now is that as I try and display the profile picture, the URL gets displayed, not the image.
Source code :
package com.example.twittersearchactivity;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class TwitterSearchActivity extends Activity {
private TextView tweetDisplay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_twitter_search);
tweetDisplay = (TextView)findViewById(R.id.tweet_txt);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.twitter_search, menu);
return true;
}
public void searchTwitter(View view){
EditText searchTxt = (EditText)findViewById(R.id.search_edit);
String searchTerm = searchTxt.getText().toString();
if(searchTerm.length()>0){
try{
String encodedSearch = URLEncoder.encode(searchTerm, "UTF-8");
String searchURL = "http://search.twitter.com/search.json?q="+encodedSearch;
new GetTweets().execute(searchURL);
Log.i("1", "entered the searchterm");
}
catch(Exception e){
tweetDisplay.setText("Whoops - something went wrong!");
e.printStackTrace();
}
}
else
tweetDisplay.setText("Enter a search query!");
}
private class GetTweets extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... twitterURL) {
StringBuilder tweetFeedBuilder = new StringBuilder();
for (String searchURL : twitterURL) {
HttpClient tweetClient = new DefaultHttpClient();
try {
HttpGet tweetGet = new HttpGet(searchURL);
HttpResponse tweetResponse = tweetClient.execute(tweetGet);
StatusLine searchStatus = tweetResponse.getStatusLine();
if (searchStatus.getStatusCode() == 200) {
HttpEntity tweetEntity = tweetResponse.getEntity();
Log.i("2", "entered gettweets");
InputStream tweetContent = tweetEntity.getContent();
InputStreamReader tweetInput = new InputStreamReader(tweetContent);
BufferedReader tweetReader = new BufferedReader(tweetInput);
String lineIn;
while ((lineIn = tweetReader.readLine()) != null) {
tweetFeedBuilder.append(lineIn);
Log.i("3", "entered while in dobackground");
}
}
else {Log.i("error", "error");}
//tweetDisplay.setText("Whoops - something went wrong!");
}
catch(Exception e) {
Log.e("DEBUGTAG", "Remote Image Exception", e);
//tweetDisplay.setText("Whoops - something went wrong!");
e.printStackTrace();
}}
return tweetFeedBuilder.toString();
}
protected void onPostExecute(String result) {
StringBuilder y;
StringBuilder tweetResultBuilder = new StringBuilder();
try {
Log.i("tag", "entered try block");
JSONObject resultObject = new JSONObject(result);
JSONArray tweetArray = resultObject.getJSONArray("results");
for (int t=0; t<tweetArray.length(); t++) {
Log.i("tag", "entered the json stream");
JSONObject tweetObject = tweetArray.getJSONObject(t);
tweetResultBuilder.append(tweetObject.getString("from_user")+": ");
tweetResultBuilder.append(tweetObject.getString("from_user_name")+": ");
tweetResultBuilder.append(tweetObject.get("text")+"\n\n");
String imageURL = (String) tweetObject.get(("profile_image_url")+": ");
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageURL).getContent());
#SuppressWarnings("deprecation")
Drawable d =new BitmapDrawable(bitmap);
d.setAlpha(255);
TextView.setCompoundDrawablesWithIntrinsicBounds(0,0,1,0);
}
}
catch (Exception e) {
tweetDisplay.setText("Whoops - something went wrong!");
e.printStackTrace();}
if(tweetResultBuilder.length()>0)
tweetDisplay.setText(tweetResultBuilder.toString());
else
tweetDisplay.setText("Sorry - no tweets found for your search!");
}
}}
You can't call view functions like setText on another thread like an AsyncTask doInBackground function. You need to do it in onPostExecute.

Categories

Resources