I want to fetch Longitude and Latitude separately from a particular address - java

I followed an example from Android Geocoding to Get Latitude Longitude for an Address tutorial, it worked but I want to fetch the longitude and latitude coordinates separately but could not.
Here is my code:
public class MainActivity extends AppCompatActivity {
Button addressButton;
TextView addressTV;
TextView latLongTV;
static TextView txtLatitude;
TextView txtLongitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addressTV = (TextView) findViewById(R.id.addressTV);
latLongTV = (TextView) findViewById(R.id.latLongTV);
txtLatitude = (TextView) findViewById(R.id.txtLatitude);
txtLatitude= (TextView) findViewById(R.id.txtLongitude);
addressButton = (Button) findViewById(R.id.addressButton);
addressButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
EditText editText = (EditText) findViewById(R.id.addressET);
String address = editText.getText().toString();
GeocodingLocation locationAddress = new GeocodingLocation();
locationAddress.getAddressFromLocation(address,
getApplicationContext(), new GeocoderHandler());
}
});
}
private class GeocoderHandler extends Handler {
#Override
public void handleMessage(Message message) {
String locationAddress,latitude ,longitude ;
switch (message.what) {
case 1:
Bundle bundle = message.getData();
locationAddress = bundle.getString("address");
latitude = bundle.getString("latitude");
longitude = bundle.getString("longitude");
break;
default:
locationAddress = null;
latitude = null;
longitude= null;
}
latLongTV.setText(locationAddress);
txtLatitude.setText(latitude);
// txtLongitude.setText(longitude);
}
}
private static class GeocodingLocation {
private static final String TAG = "GeocodingLocation";
public void getAddressFromLocation(final String locationAddress,
final Context context, final Handler handler) {
Thread thread = new Thread() {
#Override
public void run() {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
String result = null;
String strLatitude = null, strLongitude = null;
try {
List<Address> addressList = geocoder.getFromLocationName(locationAddress, 1);
if (addressList != null && addressList.size() > 0) {
Address address = addressList.get(0);
double latitude = address.getLatitude();
double longitude = address.getLongitude();
StringBuilder sb = new StringBuilder();
sb.append(address.getLatitude()).append("\n");
sb.append(address.getLongitude()).append("\n");
result = sb.toString();
strLatitude = String.valueOf(latitude);
strLongitude= String.valueOf(longitude);
}
} catch (IOException e) {
Log.e(TAG, "Unable to connect to Geocoder", e);
} finally {
Message message = Message.obtain();
message.setTarget(handler);
if (result != null) {
message.what = 1;
Bundle bundle = new Bundle();
result = "Address: " + locationAddress +
"\n\nLatitude and Longitude :\n" + result;
bundle.putString("address", result);
bundle.putString("Latitude", strLatitude);
bundle.putString("Longitude", strLongitude);
message.setData(bundle);
} else {
message.what = 1;
Bundle bundle = new Bundle();
result = "Address: " + locationAddress +
"\n Unable to get Latitude and Longitude for this address location.";
bundle.putString("address", result);
message.setData(bundle);
}
message.sendToTarget();
}
}
};
thread.start();
}
}

According to this answer, bundle keys are case-sensitive. You set the strings with:
bundle.putString("Latitude", strLatitude);
bundle.putString("Longitude", strLongitude);
But then get them with:
latitude = bundle.getString("latitude");
longitude = bundle.getString("longitude");
Notice you put with a capital L, but get with a lower-case l.

Related

Send the values of recycleview settext as intent

I have a recycleview in a card layout, the cards have 3 values set with a company array, I'm trying to send those values as an intent. But for some reason everything I try the intent ends up sending null
#Override
public void onBindViewHolder(#NonNull final ViewHolder viewHolder, final int i) {
//companyList= new ArrayList<Company>();
//heres where the textviews get there values set
final Company company = companies.get(i);
viewHolder.textViewHead.setText(company.getCompanyTitle());
viewHolder.textviewDesc.setText(company.getCompanyType());
viewHolder.textViewNumber.setText(company.getCompanyNumber());
viewHolder.linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
///send these to nodes them attach the officers, get both in nodes and send to myview
companylist = new ArrayList<Company>();
//here are my ateempts try and send the values as intents
Company company1 = companies.get(i);
// view.getContext().startActivity(new Intent(view.getContext(), Nodes.class));
Intent skipintent = new Intent(view.getContext(), Nodes.class);
skipintent.putExtra(KEY_NAME, company.getCompanyTitle());
skipintent.putExtra(KEY_NAME,viewHolder.textViewHead.getText().toString());
skipintent.putExtra(KEY_TYPE, company1.getCompanyType());
skipintent.putExtra(KEY_NUMBER, company1.getCompanyNumber());
// view.getContext().startActivity(skipintent);
Bundle bundle = new Bundle();
bundle.putString("Companyname", company.getCompanyTitle());
bundle.putString(KEY_TYPE, company1.getCompanyType());
bundle.putString(KEY_NUMBER, company1.getCompanyNumber());
// bundle.putParcelableArrayList("Companyselected", companylist);
skipintent.putExtras(bundle);
new RetrieveFeedTask().execute(company1.getCompanyNumber());
}
});
}
And here is my activity where I am trying to receive it
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_nodes);
//Toolbar toolbar = findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
//textViewNodes = (TextView) findViewById(R.id.textViewNodes);
// ArrayList<Company> recList = this.getIntent().getParcelableArrayListExtra("Company");
// companyList= new ArrayList <>();
ArrayList<Officer> officerArrayList = this.getIntent().getParcelableArrayListExtra("Officer");
// ArrayList<Company> companyArrayList = this.getIntent().getParcelableArrayListExtra("Companyselected");
Intent skipintent = getIntent();
Bundle bundle = getIntent().getExtras();
if (null != skipintent) { //Null Checking
Company company = new Company();
String companyTITLE = bundle.getString("Companyname");
String companyNUMBER = skipintent.getStringExtra(company.getCompanyNumber());
String companyTYPE = skipintent.getStringExtra(company.getCompanyType());
company.setCompanyNumber(companyNUMBER);
company.setCompanyTitle(companyTITLE);
company.setCompanyType(companyTYPE);
companyList.add(company);
Log.d("help", "onPostExecute: " + company.getCompanyTitle());
}
Log.d("meme", Arrays.toString(new ArrayList[]{companyList}));
here is the end of retrivefeed, I think I should send the values of the textviews here im not sure how
try {
JSONObject object = new JSONObject(response);
JSONArray itemsAraay = object.getJSONArray("items");
officerList = new ArrayList<Officer>();
Log.d("borkofficer", "onPostExecute: " + itemsAraay.length());
for (int i = 0; i < itemsAraay.length(); i++) {
Officer officer = new Officer();
JSONObject jsonObjectNew = itemsAraay.getJSONObject(i);
String name = jsonObjectNew.optString("name");
String role = jsonObjectNew.optString("officer_role");
String appointed_on = jsonObjectNew.optString("appointed_on");
//JSONArray.put(jsonObjectNew);
officer.setOfficerName(name);
officer.setOfficerRole(role);
officer.setOfficerAppointed(appointed_on);
officerList.add(officer);
Log.d("borkofficer", "onPostExecute: " + officer.getOfficerName());
Log.d("borkofficertitle", "onPostExecute: " + officer.getOfficerRole());
}
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("Officer", officerList);
//Intent skipintent = new Intent(view.getContext(), Nodes.class);
Intent intentofficer = new Intent(context.getApplicationContext(), Nodes.class);
intentofficer.putParcelableArrayListExtra("Officer", officerList);
Intent intentofficer1 = new Intent(context.getApplicationContext(), Nodes.class);
intentofficer1.putExtras(bundle);
// context.startActivity(intentofficer1);
intentofficer.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intentofficer1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.getApplicationContext().startActivity(intentofficer);
} catch (JSONException e) {
e.printStackTrace();
}
update im trying to bundle up the value and send in a intent but its still coming up null in the other activity is it because of the other intent im trying to send?
class RetrieveFeedTask extends AsyncTask {
private Exception exception;
protected String doInBackground(String... numbers) {
companylist = new ArrayList<Company>();
Company company = new Company();
String companynumber = numbers[0];
String companytitle = numbers[1];
String companytype = numbers[2];
company.setCompanyTitle(companytitle);
company.setCompanyType(companytype);
company.setCompanyNumber(companynumber);
companylist.add(company);
Bundle bundle1 = new Bundle();
Intent skipintent = new Intent(context.getApplicationContext(), Nodes.class);
skipintent.putExtra(KEY_NAME, companytitle);
skipintent.putExtra(KEY_NUMBER, companynumber);
skipintent.putExtra(KEY_TYPE, companytype);
skipintent.putParcelableArrayListExtra("Companylist", companylist);
skipintent.putExtras(bundle1);
Log.d("connect", "onPostExecute: " + companytitle.toString());
Log.d("connect", "onPostExecute: " + companytype.toString());
try {
URL url = new URL(API_URL + companynumber +"/officers");
Log.d("connect", "onPostExecute: " + companynumber.toString());
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("Authorization", "uG5RCz7yWRZNKaMlkQRzUPXY1NpN0SRrb8mKSZ-0");
urlConnection.setReadTimeout(15000);
urlConnection.setConnectTimeout(15000);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
} finally {
urlConnection.disconnect();
}
} catch (Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
protected void onPostExecute(String response) {
if (response == null) {
response = "THERE WAS AN ERROR";
}
Log.i("INFO", response);
//does this store?
try {
JSONObject object = new JSONObject(response);
JSONArray itemsAraay = object.getJSONArray("items");
officerList = new ArrayList<Officer>();
Log.d("borkofficer", "onPostExecute: " + itemsAraay.length());
for (int i = 0; i < itemsAraay.length(); i++) {
Officer officer = new Officer();
JSONObject jsonObjectNew = itemsAraay.getJSONObject(i);
String name = jsonObjectNew.optString("name");
String role = jsonObjectNew.optString("officer_role");
String appointed_on = jsonObjectNew.optString("appointed_on");
//JSONArray.put(jsonObjectNew);
officer.setOfficerName(name);
officer.setOfficerRole(role);
officer.setOfficerAppointed(appointed_on);
officerList.add(officer);
Log.d("borkofficer", "onPostExecute: " + officer.getOfficerName());
Log.d("borkofficertitle", "onPostExecute: " + officer.getOfficerRole());
}
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("Officer", officerList);
//skipintent.putExtra(KEY_NUMBER, company1.getCompanyNumber());
// view.getContext().startActivity(skipintent);
//Bundle bundle = new Bundle();
// bundle.putString(KEY_NAME,);
//bundle.putString(KEY_TYPE, companylist.get(1).getCompanyType());
//bundle.putString(KEY_NUMBER, companylist.get(1).getCompanyNumber());
//company1.setCompanyTitle(;
//company1.setCompanyNumber(KEY_NUMBER);
// company1.setCompanyType(KEY_TYPE);
// companylist.add(company1);
// bundle.putParcelableArrayList("Companyselected", companylist);
//skipintent.putExtras(bundle);
Intent intentofficer = new Intent(context.getApplicationContext(), Nodes.class);
intentofficer.putParcelableArrayListExtra("Officer", officerList);
Intent intentofficer1 = new Intent(context.getApplicationContext(), Nodes.class);
intentofficer1.putExtras(bundle);
// context.startActivity(intentofficer1);
intentofficer.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intentofficer1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.getApplicationContext().startActivity(intentofficer);
Inside the activity, try to extract values with same keys as were used in adapter. Use
String companyNUMBER = skipintent.getStringExtra(KEY_NUMBER);
String companyTYPE = skipintent.getStringExtra(KEY_TYPE);
instead of
String companyNUMBER = skipintent.getStringExtra(company.getCompanyNumber());
String companyTYPE = skipintent.getStringExtra(company.getCompanyType());
UPDATE
To start activity inside the AsyncTask, pass data as a constructor parameter: new RetrieveFeedTask(company.getCompanyName()).
private String mCompanyName;
RetrieveFeedTask(String companyName) {
this.mCompanyName = companyName;
}
and then use it as usually to put in the intent:
intent.putExtra(KEY_NAME, mCompanyName);
UPDATE 2
As an alternative, you can pass data in the new RetrieveFeedTask().execute(company1.getCompanyNumber(), company1.getCompanyTitle(), company1.getCompanyType()) method and use them in doInBackground:
String doInBackground(String... data) {
String companyNumber = data[0];
String companyTitle = data[1];
String companyType = data[2];
// ...
}

JVMTI_ERROR_THREAD_NOT_ALIVE error using multiple activites and OpenWeatherMap API

I am making an weather app, on the main screen app shows current weather for a city that is chosen and on the second activity screen you can find weather for next 3 days. I have WeatherInfoTask.java that is used to get JSON for MainActivity and MultipleWeatherTask.java that is used to get JSON for MultipleDays (activity)
so the MainActivity works fine and I get JSON and all of the info is shown on the screen just as it should be, but when I click on the button that should redirect me to the screen of the MultipleDays, I am redirected and just a plain screen is shown without data and this error is shown:
E/StudioProfiler: JVMTI error: 15(JVMTI_ERROR_THREAD_NOT_ALIVE)
These are my files:
public class MainActivity extends AppCompatActivity {
public static String cityName;
Handler handler;
TextView titleText;
TextView temperatureText;
TextView descriptionText;
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(!isNetworkAvailable()){
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Closing the App")
.setMessage("No Internet Connection, check your settings")
.setPositiveButton("Close", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.show();
}
handler = new Handler();
titleText = (TextView) findViewById(R.id.titleText);
temperatureText = (TextView) findViewById(R.id.temperatureText);
descriptionText = (TextView) findViewById(R.id.descriptionText);
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
autocompleteFragment.setHint("Find City");
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
cityName = place.getName().toString();
updateWeather(cityName);
/*Log.i(TAG, "Place: " + place.getName());*/
}
#Override
public void onError(Status status) {
// TODO: Handle the error.
Log.i("MainActivity", "An error occurred: " + status);
}
});
}
private void updateWeather(final String city){
new Thread(){
public void run(){
final JSONObject json = WeatherInfoTask.getJSON(MainActivity.this, city);
if(json == null){
Toast.makeText(MainActivity.this, "Error loading weather", Toast.LENGTH_LONG).show();
} else {
handler.post(new Runnable(){
public void run(){
SetWeather(json);
}
});
}
}
}.start();
}
private void SetWeather(JSONObject json){
try {
/*cityField.setText(json.getString("name").toUpperCase(Locale.US) +
", " +
json.getJSONObject("sys").getString("country"));*/
JSONObject details = json.getJSONArray("weather").getJSONObject(0);
JSONObject main = json.getJSONObject("main"); /*"main":{"temp":280.32,"pressure":1012,"humidity":81,"temp_min":279.15,"temp_max":281.15}*/
titleText.setText(R.string.title + cityName);
descriptionText.setText( /*"description":"light intensity drizzle"*/
details.getString("description") +
"\n" + "Humidity: " + main.getString("humidity") + "%" +
"\n" + "Pressure: " + main.getString("pressure") + " hPa");
temperatureText.setText(
String.format("%.2f", main.getDouble("temp"))+ " ℃");
}catch(Exception e){
Log.e("SimpleWeather", "One or more fields not found in the JSON data");
}
}
public void MultipleDays(View view){
Intent intent = new Intent(this, MultipleDays.class);
startActivity(intent);
}
}
Next one:
public class WeatherInfoTask {
private static final String OpenWeatherAPI =
"http://api.openweathermap.org/data/2.5/weather?q=%s&units=metric";
public static JSONObject getJSON(Context context, String city) {
try {
URL url = new URL(String.format(OpenWeatherAPI, city));
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.addRequestProperty("x-api-key", context.getString(R.string.apikey));
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuffer json = new StringBuffer(1024);
String tmp = ""; /*tmp = temporary*/
while ((tmp = reader.readLine()) != null)
json.append(tmp).append("\n");
reader.close();
JSONObject data = new JSONObject(json.toString());
/*This value will be 404 if the request was not successful*/
if (data.getInt("cod") != 200) {
/*greska*/
return null;
}
return data;
} catch (Exception e) {
return null;
}
Next one:
public class MultipleDays extends AppCompatActivity {
Handler handler;
TextView day1;
TextView day2;
TextView day3;
Integer dayCounter = 1;
Date comparisonDate;
Date currentDate;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Float dailyMin;
Float dailyMax;
Float currMin;
Float currMax;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_multiple_days);
handler = new Handler();
day1 = (TextView) findViewById(R.id.day1);
day2 = (TextView) findViewById(R.id.day2);
day3 = (TextView) findViewById(R.id.day3);
updateMultipleWeather(MainActivity.cityName);
}
private void updateMultipleWeather(final String city){
new Thread(){
public void run(){
final JSONObject json = MultipleWeatherTask.getJSON(MultipleDays.this, city);
if(json == null){
Toast.makeText(MultipleDays.this, "Error loading weather", Toast.LENGTH_LONG).show();
} else {
handler.post(new Runnable(){
public void run(){
setWeather(json);
}
});
}
}
}.start();
}
private void setWeather(JSONObject json){
try {
JSONArray list = json.getJSONArray("list");
for (int i=0; i < list.length() ; i++){
if(i == 0) {
String string = list.getJSONObject(i).getString("dt_txt");
string = convertDate(string);
comparisonDate = formatter.parse(string.replace("",""));
dailyMin = Float.parseFloat(list.getJSONObject(i).getString("temp_min"));
dailyMax = Float.parseFloat(list.getJSONObject(i).getString("temp_max"));
}
else if ( dayCounter <=3 ){
String string = list.getJSONObject(i).getString("dt_txt");
string = convertDate(string);
currentDate = formatter.parse(string.replace("","")); //datum u obliku "yy-MM-dd"
if ( comparisonDate == currentDate ){ //ako smo i dalje na istom danu
currMin = Float.parseFloat(list.getJSONObject(i).getString("temp_min"));
currMax = Float.parseFloat(list.getJSONObject(i).getString("temp_max"));
if( dailyMin > currMin ) dailyMin = currMin;
if( dailyMax < currMax ) dailyMax = currMax;
}
else {
switch (dayCounter){
case 1: day1.setText("Minimum temperature: " + String.format("%.2f", dailyMin) + "\n" +
"Maximum temperature: " + String.format("%.2f", dailyMax) + "\n" +
"Weather: " + list.getJSONObject(i-1).getString("description"));
dayCounter++;
break;
case 2: day2.setText("Minimum temperature: " + String.format("%.2f", dailyMin) + "\n" +
"Maximum temperature: " + String.format("%.2f", dailyMax) + "\n" +
"Weather: " + list.getJSONObject(i-1).getString("description"));
dayCounter++;
break;
case 3: day3.setText("Minimum temperature: " + String.format("%.2f", dailyMin) + "\n" +
"Maximum temperature: " + String.format("%.2f", dailyMax) + "\n" +
"Weather: " + list.getJSONObject(i-1).getString("description"));
dayCounter++;
break;
}
}
}
}
Next one:
public class MultipleWeatherTask {
private static final String OpenWeatherAPI =
"api.openweathermap.org/data/2.5/forecast?q=%s&units=metric";
public static JSONObject getJSON(Context context, String city) {
try {
URL url = new URL(String.format(OpenWeatherAPI, city));
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.addRequestProperty("x-api-key", context.getString(R.string.apikey));
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuffer json = new StringBuffer(1024);
String tmp = ""; /*tmp = temporary*/
while ((tmp = reader.readLine()) != null)
json.append(tmp).append("\n");
reader.close();
JSONObject data = new JSONObject(json.toString());
/*This value will be 404 if the request was not successful*/
if (data.getInt("cod") != 200) {
/*greska*/
return null;
}
return data;
} catch (Exception e) {
return null;
}
}
}
File ---> Invalidate Caches / Restart will help you.

using aSyncTask with variables

I am making a simple weather app and i have a problem with reading variables by aSyncTask. I am very beginner in programming for andorid, so I am asking for understanding. So, i want to put variables "latitude" and "longitude" choosen from place picker into asyncTask.execute("Latitude", "Longitude") and refresh a screen to show weather for new location. Now it dosent work, but i noticed, that when i put coordinates in code not by variables (for ex. asyncTask.execute("52.2296756", "38,3435546") then weather for this location appears after using Place Picker. I have also added outprint to check this varibles, and they looks okay.
public class MainActivity extends AppCompatActivity {
TextView cityField, detailsField, currentTemperatureField,
humidity_field, pressure_field, weatherIcon, updatedField;
ImageView mPlacePicker;
Typeface weatherFont;
int PLACE_PICKER_REQUEST = 1;
String latitude;
String longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_main);
mPlacePicker = (ImageView) findViewById(R.id.place_picker);
mPlacePicker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PlacePicker.IntentBuilder builder = new
PlacePicker.IntentBuilder();
Intent intent;
try {
intent = builder.build(MainActivity.this);
startActivityForResult(intent, PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent
data) {
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
Place place = PlacePicker.getPlace(this, data);
String address = String.format("Place %s", place.getAddress());
Toast.makeText(this, address, Toast.LENGTH_LONG).show();
LatLng latLng = place.getLatLng();
latitude = String.valueOf(latLng.latitude);
longitude = String.valueOf(latLng.longitude);
//System.out.println(latitude);
//System.out.println(longitude);
}
}
weatherFont = Typeface.createFromAsset(getApplicationContext().getAssets(), "fonts/weathericons-regular-webfont.ttf");
cityField = (TextView) findViewById(R.id.city_field);
updatedField = (TextView) findViewById(R.id.updated_field);
detailsField = (TextView) findViewById(R.id.details_field);
currentTemperatureField = (TextView) findViewById(R.id.current_temperature_field);
humidity_field = (TextView) findViewById(R.id.humidity_field);
pressure_field = (TextView) findViewById(R.id.pressure_field);
weatherIcon = (TextView) findViewById(R.id.weather_icon);
weatherIcon.setTypeface(weatherFont);
mPlacePicker = (ImageView) findViewById(place_picker);
Function.placeIdTask asyncTask = new Function.placeIdTask(new Function.AsyncResponse() {
public void processFinish(String weather_city, String weather_description, String weather_temperature, String weather_humidity, String weather_pressure, String weather_updatedOn, String weather_iconText, String sun_rise) {
cityField.setText(weather_city);
updatedField.setText(weather_updatedOn);
detailsField.setText(weather_description);
currentTemperatureField.setText(weather_temperature);
humidity_field.setText("Humidity: " + weather_humidity);
pressure_field.setText("Pressure: " + weather_pressure);
weatherIcon.setText(Html.fromHtml(weather_iconText));
}
});
System.out.println('"' + latitude + '"');
System.out.println('"' + longitude + '"');
asyncTask.execute('"' + latitude + '"', '"' + longitude + '"'); // asyncTask.execute("Latitude", "Longitude")
}
}
And this is second class with doInBackground
public class Function {
private static final String OPEN_WEATHER_MAP_URL =
"http://api.openweathermap.org/data/2.5/weather?lat=%s&lon=%s&units=metric";
private static final String OPEN_WEATHER_MAP_API = "3b30fbc239f6a1ed664220635330aa46";
public static String setWeatherIcon(int actualId, long sunrise, long sunset){
int id = actualId / 100;
String icon = "";
if(actualId == 800){
long currentTime = new Date().getTime();
if(currentTime>=sunrise && currentTime<sunset) {
icon = "";
} else {
icon = "";
}
} else {
switch(id) {
case 2 : icon = "";
break;
case 3 : icon = "";
break;
case 7 : icon = "";
break;
case 8 : icon = "";
break;
case 6 : icon = "";
break;
case 5 : icon = "";
break;
}
}
return icon;
}
public interface AsyncResponse {
void processFinish(String output1, String output2, String output3, String output4, String output5, String output6, String output7, String output8);
}
public static class placeIdTask extends AsyncTask<String, Void, JSONObject> {
public AsyncResponse delegate = null;//Call back interface
public placeIdTask(AsyncResponse asyncResponse) {
delegate = asyncResponse;//Assigning call back interfacethrough constructor
}
#Override
protected JSONObject doInBackground(String... params) {
JSONObject jsonWeather = null;
try {
jsonWeather = getWeatherJSON(params[0], params[1]);
} catch (Exception e) {
Log.d("Error", "Cannot process JSON results", e);
}
return jsonWeather;
}
#Override
protected void onPostExecute(JSONObject json) {
try {
if(json != null){
JSONObject details = json.getJSONArray("weather").getJSONObject(0);
JSONObject main = json.getJSONObject("main");
DateFormat df = DateFormat.getDateTimeInstance();
String city = json.getString("name").toUpperCase(Locale.US) + ", " + json.getJSONObject("sys").getString("country");
String description = details.getString("description").toUpperCase(Locale.US);
String temperature = String.format("%.2f", main.getDouble("temp"))+ "°";
String humidity = main.getString("humidity") + "%";
String pressure = main.getString("pressure") + " hPa";
String updatedOn = df.format(new Date(json.getLong("dt")*1000));
String iconText = setWeatherIcon(details.getInt("id"),
json.getJSONObject("sys").getLong("sunrise") * 1000,
json.getJSONObject("sys").getLong("sunset") * 1000);
delegate.processFinish(city, description, temperature, humidity, pressure, updatedOn, iconText, ""+ (json.getJSONObject("sys").getLong("sunrise") * 1000));
}
} catch (JSONException e) {
//Log.e(LOG_TAG, "Cannot process JSON results", e);
}
}
}
public static JSONObject getWeatherJSON(String lat, String lon){
try {
URL url = new URL(String.format(OPEN_WEATHER_MAP_URL, lat, lon));
HttpURLConnection connection =
(HttpURLConnection)url.openConnection();
connection.addRequestProperty("x-api-key", OPEN_WEATHER_MAP_API);
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
StringBuffer json = new StringBuffer(1024);
String tmp="";
while((tmp=reader.readLine())!=null)
json.append(tmp).append("\n");
reader.close();
JSONObject data = new JSONObject(json.toString());
// This value will be 404 if the request was not
// successful
if(data.getInt("cod") != 200){
return null;
}
return data;
}catch(Exception e){
return null;
}
}
}
Remove the extra "". You don't need those e.g.
asyncTask.execute(latitude,longitude);
you can use a constructor for your class AsyncTask
something like this :
class placeIdTask extends AsynckTask<Void,Void,Void>{
Double latitude;
Double longitude;
public placeIdTask(Double latitude, Double longitude){
this.latitude = latitude;
this.longitude=longitude;
}
...//implement doInbackground using latitude and longitude
}
or
just you change the type of generic CLass like this
class placeIdTask extends AsynckTask<Double,Void,Void>{
#Override
protected Void doInBackground(Double... arg0) {
Double latitude = arg0[0];
Double longitude = arg0[1];
... }
... }
and I suggest u to use Double instead of String
hope that help you
//Add async task
private class SampleAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// this might take a while ...
// Do your task over here
// Use parameterlike this
latitude=params[0];
longitude=params[1];
return "Success";
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
//Call asyc task
new SampleAsyncTask().execute(String.valueOf(latitude),String.valueOf(longitude));
Hope this help you. Happy coding

Get longitude and latitude values to post into url - Android

I am creating an Android app that pulls XML data. I want to be able to use the longitude and latitude values to post into the web link to get specific XML data for the users current location.
Here is my code so far, which does not work:
public class GeoSplashActivity extends Activity {
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
private String GEORSSFEEDURL = "http://www.socialalertme.com/mobilealerts.xml?lat="+latitude+"lng="+longitude+"&distance=20";
GeoRSSFeed feed3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash2);
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() == null
&& !conMgr.getActiveNetworkInfo().isConnected()
&& !conMgr.getActiveNetworkInfo().isAvailable()) {
// No connectivity - Show alert
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(
"Unable to reach server, \nPlease check your connectivity.")
.setTitle("TD RSS Reader")
.setCancelable(false)
.setPositiveButton("Exit",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int id) {
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
} else {
// Connected - Start parsing
new AsyncLoadXMLFeed().execute();
}
}
private class AsyncLoadXMLFeed extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// Obtain feed
GeoDOMParser myParser = new GeoDOMParser();
feed3 = myParser.parseXml(GEORSSFEEDURL);
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Bundle bundle = new Bundle();
bundle.putSerializable("feed", feed3);
// launch List activity
Intent intent = new Intent(GeoSplashActivity.this, GeoListActivity.class);
intent.putExtras(bundle);
startActivity(intent);
// kill this activity
finish();
}
}
}
I have never used the location stuff before, so I'm not entirely sure what I'm doing here. If anyone could give some pointers, I'd really appreciate it!
Hopefully you are not forgetting
<uses-permission android:name=“android.permission.ACCESS_FINE_LOCATION”></uses-permission>
in your manifest file. This tutorial can help you to get better understanding.
Edit
Google already have provided Training to get current Location.
//Get coordinates if available:
LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
Location loc;
double latitude=0,longitude=0;
if ( ( loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER) )!=null ){
latitude = loc.getLatitude();
longitude = loc.getLongitude();
}else if( ( loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER) )!=null ){
latitude = loc.getLatitude();
longitude = loc.getLongitude();
}
//If any coordinate value is recieved, use it.
if(latitude!=0 || longitude!=0){
String latitude = String.valueOf(latitude);
String longitude = String.valueOf(longitude);
//TODO post into url
}
You should move initialization of location variables to the onCreate method. Also you should also check if location != null:
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
longitude = location.getLongitude();
latitude = location.getLatitude();
GEORSSFEEDURL = "http://www.socialalertme.com/mobilealerts.xml?lat="+latitude+"lng="+longitude+"&distance=20";
} else {
...
}
I am doing the same thing, and this works for me!
But, the server I am requestiong is a node.js server, and the data is in JSON.
public class GetWeatherDataRest extends AsyncTask<Void, Void, String> {
private static final String TAG = "GetWeatherDataRest";
// get lat and long from main activity
double lat = MyActivity.lat;
double lng = MyActivity.lng;
// the url
String url = "http://ThisIsTheAddress/weather/5days?lat="+lat+"&lng="+lng;
public MyActivity context;
private List<Weather> posts;
public GetWeatherDataRest(MyActivity activity){
this.context = activity;
}
#Override
protected String doInBackground(Void... params) {
try {
//Create an HTTP client
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
//Perform the request and check the status code
HttpResponse response = client.execute(get);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
try {
//Read the server response and attempt to parse it as JSON
Reader reader = new InputStreamReader(content);
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("M/d/yy hh:mm a");
Gson gson = gsonBuilder.create();
posts = new ArrayList<Weather>();
posts = Arrays.asList(gson.fromJson(reader, Weather[].class));
content.close();
} catch (Exception ex) {
Log.e(TAG, "Failed to parse JSON due to: " + ex);
}
} else {
Log.e(TAG, "Server responded with status code: " + statusLine.getStatusCode());
}
} catch(Exception ex) {
Log.e(TAG, "Failed to send HTTP POST request due to: " + ex);
}
return null;
}
#Override
protected void onPostExecute(String result) {
context.updateFields(posts);
}
}
Okey! This is my GpsFragment, where I get the lng and lat!
I am not done with this yet, so It might not look like much, but it works, also it gives an address from the lng & lat using geocoder
You should implement the LocationListener.
public class GpsFragment extends Fragment implements LocationListener{
public Location location;
LocationManager locationManager;
String provider;
List<Address> mAddresses;
TextView mAddress1;
TextView mAddress2;
public static double lat;
public static double lng;
private static final String TAG = "MyGps";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View myInflatedView = inflater.inflate(R.layout.gps_fragment, container,false);
mAddress1 = (TextView) myInflatedView.findViewById(R.id.address_text);
mAddress2 = (TextView) myInflatedView.findViewById(R.id.address_text2);
locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(provider, 100, 1, this);
if(location != null){
onLocationChanged(location);
Log.v(TAG, "Location available!");
}
else{
mAddress1.setText("No location");
Log.e(TAG, "Location not available!");
}
return myInflatedView;
}
// So i think this is what you need! the 'onLocationChanged'
#Override
public void onLocationChanged(Location location) {
this.location = location;
lat = location.getLatitude();
lng = location.getLongitude();
Geocoder mLocation = new Geocoder(getActivity().getApplicationContext(), Locale.getDefault());
try {
mAddresses = mLocation.getFromLocation(lat, lng, 1);
if(mAddresses != null) {
Address returnedAddress = mAddresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("Address:\n");
for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}
// mAddress.setText(strReturnedAddress.toString());
//mAddress1.setText("lat"+lat);
//mAddress2.setText("lng"+lng);
mAddress1.setText("Address: "+returnedAddress.getAddressLine(0).toString());
mAddress2.setText("City: "+returnedAddress.getAddressLine(1).toString());
}
else{
// mAddress.setText("No Address returned!");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//mAddress.setText("Cannot get Address!");
}
((MyActivity)getActivity()).fetchData();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}

How to put JSON lOutput (latitude and longitude) on the map

I have a main activity which parses the JSON data from my mysql (table tracking:Lattitude and longitude) Now I want to pass this data in to my MapActivity and display on google maps. Any help is highly appreciated. Thanks!
this my JSONactivity
public class JSONActivity extends Activity{
private JSONObject jObject;
private String xResult ="";
//Seusuaikan url dengan nama domain
private String url = "http://10.0.2.2/labiltrack/daftartracking.php";
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.daftartrack);
TextView txtResult = (TextView)findViewById(R.id.TextViewResult);
//url += "?lattitude=" + UserData.getEmail();
xResult = getRequest(url);
try {
parse(txtResult);
} catch (Exception e) {
e.printStackTrace();
}
}
private void parse(TextView txtResult) throws Exception {
// TODO Auto-generated method stub
jObject = new JSONObject(xResult);
JSONArray menuitemArray = jObject.getJSONArray("joel");
String sret="";
//int j = 0;
for (int i = 0; i < menuitemArray.length(); i++) {
sret +=menuitemArray.getJSONObject(i).
getString("lattitude").toString()+" : ";
System.out.println(menuitemArray.getJSONObject(i)
.getString("lattitude").toString());
System.out.println(menuitemArray.getJSONObject(i).getString(
"longitude").toString());
sret +=menuitemArray.getJSONObject(i).getString(
"lattitude").toString()+"\n";
//j=i;
}txtResult.setText(sret);
}
/**
* Method untuk Mengirimkan data keserver
* event by button login diklik
*
* #param view
*/
private String getRequest(String url) {
// TODO Auto-generated method stub
String sret="";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
try{
HttpResponse response = client.execute(request);
sret =request(response);
}catch(Exception ex){
Toast.makeText(this,"jo "+sret, Toast.LENGTH_SHORT).show();
}
return sret;
}
/**
* Method untuk Menenrima data dari server
* #param response
* #return
*/
private String request(HttpResponse response) {
// TODO Auto-generated method stub
String result = "";
try{
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
str.append(line + "\n");
}
in.close();
result = str.toString();
}catch(Exception ex){
result = "Error";
}
return result;
}
}
and this my mapActivity
public class mapactivity extends MapActivity {
private MapView mapView;
MapController mc;
GeoPoint p;
//private MyLocationOverlay me = null;
class MapOverlays extends com.google.android.maps.Overlay
{
#Override
public boolean draw (Canvas canvas, MapView mapView, boolean shadow, long when)
{
super.draw(canvas, mapView, shadow);
//translate the geopoint to screen pixels
Point screenPts = new Point();
mapView.getProjection().toPixels(p, screenPts);
//tambah marker
Bitmap bmp = BitmapFactory.decodeResource(getResources (), R.drawable.pin_red);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y-50, null);
//mapView.setSatellite(true);
return true;
}
#Override
public boolean onTouchEvent(MotionEvent event, MapView mapView)
{
//---when user lifts his finger---
if (event.getAction() == 1) {
GeoPoint p = mapView.getProjection().fromPixels(
(int) event.getX(),
(int) event.getY());
Toast.makeText(getBaseContext(),
p.getLatitudeE6() / 1E6 + "," +
p.getLongitudeE6() /1E6 ,
Toast.LENGTH_SHORT).show();
mc.animateTo(p);
//geocoding
Geocoder geoCoder = new Geocoder(
getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(
p.getLatitudeE6() / 1E6,
p.getLongitudeE6() / 1E6, 1);
String add = "";
if (addresses.size() > 0)
{
for (int i=0; i<addresses.get(0).getMaxAddressLineIndex();
i++)
add += addresses.get(0).getAddressLine(i) + "\n";
}
Toast.makeText(getBaseContext(), add, Toast.LENGTH_SHORT).show();
}
catch (IOException e) {
e.printStackTrace();
}
return true;
}
else
return false;
} }
/** Called when the activity is first created. */
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mapview1);
//utk mnampilkan zoom
mapView = (MapView) findViewById(R.id.mapView);
LinearLayout zoomLayout = (LinearLayout)findViewById(R.id.zoom);
View zoomView = mapView.getZoomControls();
zoomLayout.addView(zoomView,
new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
mapView.displayZoomControls(true);
//menampilkan default peta banda aceh
mc = mapView.getController();
String coordinates[] = {"5.550381", "95.318699"};
double lat = Double.parseDouble(coordinates[0]);
double lng = Double.parseDouble(coordinates[1]);
p = new GeoPoint(
(int) (lat * 1E6),
(int) (lng * 1E6));
mc.animateTo(p);
mc.setZoom(14);
mapView.invalidate();
//tambah marker
MapOverlays mapOverlay = new MapOverlays();
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
mapView.invalidate();
}
public void btnSatelitClick(View v){
mapView.setSatellite(true);
mapView.setStreetView(false);
}
public void btnjalanClick (View v){
mapView.setSatellite(false);
mapView.setStreetView(true);
}
protected boolean isRouteDisplayed()
{
//auto generate method
return false;
}
}
my jsonactivity is get data from mysql (field "latitude" and "longitude") into listview, but now I want to display that data (latitude and longitude) on google map, How Could I do this ?
please help me, thanks in advance !
You need to get bundle from another class : this class will be for your mapActivity
Bundle b = getIntent().getExtras(); // Getting the Bundle object that pass from another activity
int SelectedPropertylat = b.getInt("SelectedLat");
int SelectedPropertylong = b.getInt("SelectedLong");
String lattitude = Integer.toString(SelectedPropertylat);
String longertude = Integer.toString(SelectedPropertylong);
Log.d(lattitude,longertude);
And taking datafrom mysql into your apps use this :
try{
JSONArray earthquakes = json.getJSONArray("PropertyDetails");
for(int i=0;i<earthquakes.length();i++){
JSONObject e = earthquakes.getJSONObject(i);
lat = e.getString("P_Lat");
lonng = e.getString("P_Long");
then convert lat and long into an string like :
lonnng = Integer.parseInt(lonng.toString());
latt =Integer.parseInt(lat.toString());
then pass the data into your mapview like this :
Intent moreDetailsIntent = new Intent(PropertiesDetails.this,mapActivity .class);
Bundle dataBundle = new Bundle();
dataBundle.putInt("SelectedLong",lonnng);
dataBundle.putInt("SelectedLat", latt);
moreDetailsIntent.putExtras(dataBundle);
startActivity(moreDetailsIntent);

Categories