How to save multiple location coordinates in your project? - java

I'm fetching some of the locations from the server and need to point them as markers in the google map, so what i did was i created a model of the locations and used the volley library to fetch the details from the server and saved them in a variable and post it in the map. But I'm getting an error as java.lang.NumberFormatException: multiple points.
So need some assistance.
This is my model
public class LocationModel
private String pdLatitude;
private String pdLongitude;
public LocationModel(String pdLatitude, String pdLongitude){
this.pdLatitude = pdLatitude;
this.pdLongitude = pdLongitude; }
public String getPdLatitude() {
return pdLatitude;
}
public String getPdLongitude() {
return pdLongitude;
}
This is my Activity where i'm retreiving the information from the server
private void findRoute(){
StringRequest request = new StringRequest(Request.Method.GET,
Constant.Route_URL + "/" + driverschoolname + "/" + driverid,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
String pdlatitude = "";
String pdlongitude = "";
try{
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("res");
for (int i=0; i<array.length(); i++){
JSONObject object = array.getJSONObject(i);
StudentsPickDropModel pickDropModel = new StudentsPickDropModel(
object.getString("pdloc_latitude"),
object.getString("pdloc_longitude")
);
pdlatitude += pickDropModel.getPdLatitude();
pdlongitude += pickDropModel.getPdLongitude();
Toast.makeText(StudentsPickDropActivity.this, pickDropModel.getPdName(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Activity.this, GetRoute.class);
intent.putExtra("pd_latitude", pdlatitude);
intent.putExtra("pd_longitude", pdlongitude);
startActivity(intent);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Activity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(request);
}
And this is how i'm posting my coordiantes in Google maps
Bundle bundle = getIntent().getExtras();
schoollat = bundle.getString("school_lat");
schoollng = bundle.getString("school_lng");
pdlat = bundle.getString("pd_latitude");
pdlng = bundle.getString("pd_longitude");
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
mFusedLocationClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
#Override
public void onComplete(#NonNull Task<Location> task) {
Location location = task.getResult();
if (location == null){
requestNewLocationData();
} else {
currentLat = location.getLatitude();
currentLng = location.getLongitude();
System.out.println("Current Latitude: "+location.getLatitude());
System.out.println("Current Longitude: "+location.getLongitude());
}
}
});
Double clat = currentLat;
System.out.println("Current Latitude : "+clat);
Double schoollatitude = new Double(schoollat);
Double schoollongitude = new Double(schoollng);
System.out.println("School latitude : "+schoollatitude + ", School Longitude : "+schoollongitude);
Double pdlatitude = new Double(pdlat);
Double pdlongitude = new Double(pdlng);
getDirections = findViewById(R.id.getdirection);
getDirections.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new FetchURL(GetRoute.this).execute(getUrl(placeOne.getPosition(), placeTwo.getPosition(), "driving"), "driving");
}
});
MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map_fragment);
mapFragment.getMapAsync(this);
places = new MarkerOptions().position(new LatLng(pdlatitude, pdlongitude)).title("Office");
And this is my JSON
"res": [
{
"pdloc_latitude": "12.3111356",
"pdloc_longitude": "76.6075989",
},
{
"pdloc_latitude": "88.568645787",
"pdloc_longitude": "75.54544454887",
}

Use Double.parseDouble() for better efficiency
The core method is parseDouble() which is specially designed to parse
a String containing floating point value into the Double object. Rest
of the methods e.g. valueOf() and constructor uses parseDouble()
internally.
and be sure that the pdlat value you are passing is a valid double number and not just plain characters
This( Double.parseDouble()) method will throw NullPointerException if the string you are passing is null and NumberFormatException if String is not containing a valid double value e.g. containing alphabetic characters.
Just debug Double pdlatitude = new Double(pdlat); line to be sure.

Your PDlat have 2 points. That is invalid for Double since Double have 1 point.
Your value:
12.311135688.568645787
What it should has 1 point like this:
12.311135688568645787
PS. You can catch an exception If the value parsing is fail, and what to do is up to what exception occurs.

Related

Why is my public variable being shown as " 'this' is not available"?

I am trying to populate a listview with data from a database but it won't allow me to assign a string variable.
i have read some other articles on this but i cannot for the life of me figure out why my variable is shown as " 'this' is not available " When i use the debugger.
public class InventoryActivity extends AppCompatActivity
{
private RecyclerView varRecyclerView;
private RecyclerView.Adapter varAdapter;
private RecyclerView.LayoutManager varLayoutManager;
private static String URL_FindInventory = "MyPHPFile";
//IM TRYING TO SET THESE TWO VARIABLES
public String itemOneName, itemOneEffect;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inventory);
String characterID = getIntent().getStringExtra("characterID");
ArrayList<LayoutItem> inventoryList = new ArrayList<>();
FindInventory(characterID);
inventoryList.add(new LayoutItem(R.drawable.ic_add_circle, itemOneName, itemOneEffect));
inventoryList.add(new LayoutItem(R.drawable.ic_add_circle, "Item Two Name", "Item Two's Effect"));
varRecyclerView = findViewById(R.id.recyclerView);
varRecyclerView.setHasFixedSize(true);
varLayoutManager = new LinearLayoutManager(this);
varAdapter = new LayoutAdapter(inventoryList);
varRecyclerView.setLayoutManager(varLayoutManager);
varRecyclerView.setAdapter(varAdapter);
}
private void FindInventory(final String characterID)
{
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_FindInventory,
new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
try
{
JSONObject jsonObject = new JSONObject(response);
String result = jsonObject.getString("result");
if (result != null)
{
JSONArray jsonArray = jsonObject.getJSONArray("result");
for(int i = 0; i < jsonArray.length(); i++)
{
JSONObject object = jsonArray.getJSONObject(i);
//IM TRYING TO USE THESE TWO VARIABLES TO SET THE PUBLIC ONES.
String itemName = object.getString("Name").trim(); // this has a value of "Cap of Thinking"
String itemEffect = object.getString("Effect").trim(); // this has a value of "Helps the user to think +2 Intelligence"
itemOneName = itemName; // THIS IS SHOWN AS "ItemOneName = 'this' is not available "
itemOneEffect = itemEffect; // THIS IS SHOWN AS "ItemOneEffect = 'this' is not available "
}
}
else if ((result.equals("error")))
{
Toast.makeText(InventoryActivity.this, "Cannot find Inventory", Toast.LENGTH_LONG).show();
}
} catch (JSONException e)
{
e.printStackTrace();
Toast.makeText(InventoryActivity.this, "Exception Error " + e.toString(), Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(InventoryActivity.this, "Error " + error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("characterid", characterID);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
When I'm trying to set the value of the 2 public strings they are being set as null, I can't for the life of me figure out why it won't allow me to set there value to the variables I read from the JSON object.
They are null because your web request happens after you added the items to the lists.
Make inventoryList a field and remove the two string fields you're trying to set
Move the two inventoryList.add methods into the onResponse, then you need to notify the RecyclerView adapter that new data needs to be displayed
The reason they are null is because when the compiler executes below two lines(let's call it line 1 and line 2):
FindInventory(characterID);//line 1
inventoryList.add(new LayoutItem(R.drawable.ic_add_circle, itemOneName, itemOneEffect));//line 2
-At line 1, the method gets executed asynchronously(means that it will not block the execution of line 2, line 2 will be executed either after or before line 1). This causes the variables itemOneName and itemOneEffect to be null, since line 2 was executed before line 1, remember line 1 and line 2 are being executed in parallel or same time.
To fix this:
-You have to do below:
inventoryList.add(new LayoutItem(R.drawable.ic_add_circle, itemOneName, itemOneEffect));
inventoryList.add(new LayoutItem(R.drawable.ic_add_circle, "Item Two Name", "Item Two's Effect"));
...and other dependencies
After you invoke these lines within onResponse():
String itemName = object.getString("Name").trim(); // this has a value of "Cap of Thinking"
String itemEffect = object.getString("Effect").trim();

Android : Show MapMarker info when user is in 20m way

I am new in Android developing, and took a hard one for first project. :D
So the back story :
I have MapActivity what gets MapMarkers from MySql DB (php -> Json)
Now I have a map where are some Marks and user location is known.
And what I want to do?
Simple.. when user gets near to marker (lets say 20m) then he will get
popup where he can submit that he is there..
Problem is that I have no idea how to do it..
My Code is bad, but it works :D.
For rights I have fast workaround (Lenovo tab is with bit old Android, but other way works on Android 7.1.. I hope someone can help me out here. :).
public class kaart extends FragmentActivity implements OnMapReadyCallback {
MapFragment mapFragment;
GoogleMap gMap;
MarkerOptions markerOptions = new MarkerOptions();
CameraPosition cameraPosition;
LatLng center, latLng;
String title;
String kirjeldus;
String vahend;
public static final String ID = "id"; //god to use for marker detection
public static final String TITLE = "nimi";
public static final String KIRJELDUS = "kirjeldus";
public static final String LAT = "lat";
public static final String LNG = "lng";
public static final String VAHEND = "vahend";
private String url = "https://lammerdis.ee/orient/";
String tag_json_obj = "json_obj_req";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.kaart);
mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.kaart);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
gMap = googleMap;
gMap.getUiSettings().setMapToolbarEnabled(false);
gMap.setMapType(GoogleMap.MAP_TYPE_HYBRID); //Võimalikud valikud MAP_TYPE_SATELLITE, MAP_TYPE_TERRAIN, MAP_TYPE_HYBRID, MAP_TYPE_NORMAL
gMap.getUiSettings().setZoomControlsEnabled(true);
gMap.getUiSettings().setCompassEnabled(true);
gMap.getUiSettings().setMyLocationButtonEnabled(true);
gMap.getUiSettings().setZoomGesturesEnabled(true);
// Kaardi alguse asukoha Zoomime Aida juurde
center = new LatLng(59.175597, 25.022103);
cameraPosition = new CameraPosition.Builder().target(center).zoom(10).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
getMarkers();
}
private void addMarker(LatLng latlng, final String title, final String kirjeldus, final String vahend) {
markerOptions.position(latlng);
markerOptions.title(title);
markerOptions.snippet(kirjeldus);
if (vahend.equalsIgnoreCase("auto")) {
markerOptions.icon(BitmapDescriptorFactory.fromResource(R.mipmap.auto));
} else {
markerOptions.icon(BitmapDescriptorFactory.fromResource(R.mipmap.jala)); }
gMap.addMarker(markerOptions);
}
// Korjame JSON-ist punktid kokku
private void getMarkers() {
StringRequest strReq = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("Response: ", response.toString());
try {
JSONObject jObj = new JSONObject(response);
String getObject = jObj.getString("punktid");
JSONArray jsonArray = new JSONArray(getObject);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
title = jsonObject.getString(TITLE);
kirjeldus = jsonObject.getString(KIRJELDUS);
vahend = jsonObject.getString(VAHEND);
latLng = new LatLng(Double.parseDouble(jsonObject.getString(LAT)), Double.parseDouble(jsonObject.getString(LNG)));
// Kuvame andmed kaardile
addMarker(latLng, title, kirjeldus, vahend);
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error: ", error.getMessage());
Toast.makeText(kaart.this, error.getMessage(), Toast.LENGTH_LONG).show();
}
});
AppController.getInstance().addToRequestQueue(strReq, tag_json_obj);
//kui punktid kaardil ja seadmes on lubatud asukohta otsida, siis kuvame kasutaja asukoha ka
//Kui on vanem android siis saame Manifestis kirjeldatud õigustega hakkama ja saaba sukoha kuvatud
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
gMap.setMyLocationEnabled(true); //Kuvab asukoha punktina kaardil
gMap.getUiSettings().setMyLocationButtonEnabled(true); // Kuvab asukoha nupu (viskab ilusti oma asukohale)
} else {
//Kui on android 6.0 või uuem siis tuleb õiguseid küsida rakenduse käivitamisel
ActivityCompat.requestPermissions(this, new String[] {
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION },
PackageManager.PERMISSION_GRANTED);
//Kui õigused on lubatud siis tuleb neid rakendada, kõige lihtsam on kasutajale pasundada, et rakenduse restardiks
final Toast tag = Toast.makeText(this, R.string.OIGUSE_INFO, Toast.LENGTH_LONG);
tag.show();
new CountDownTimer(50000, 1000)
{
public void onTick(long millisUntilFinished) {tag.show();}
public void onFinish() {tag.show();}
}.start();
}
}
}
You can set up GeoFences ( https://developer.android.com/training/location/geofencing.html ) with these you can create an area where when the user enters it or it you will get an intent in your intent service then it's just a matter of use that info wherever you like.

How to make app recognize that location is enabled after startup

I solved the issue for "checking if location is enabled", but now I'm stuck. I want the app to show a toast if location is disabled, and once it's enabled by the user, I want the app to proceed as normal, like location was enabled at the first place. My code looks correct to me, I don't know where the problem is. Note that I don't have any issues with accessing the location, network and stuff. It's just that I always need to restart the app after enabling location, otherwise it won't proceed and keep giving me the warning toast. Thanks in advance.
Edit: So I just added an alert dialog method instead of Toast messages. Users can now go to settings and turn location and network on using that dialog. I'd like you to take a look at the Network check if-else statement inside getForecast() method. else contains the alert dialog that leads user to Settings-Data Roaming. And when user activated mobile data and returns to the app, everything's fine and app can get info. I did the same for location if-else statement, yet when user turns location on and returns to the app, no matter what I do (wait several minutes, refresh several times), I'm not getting the location info. I need to close and reopen the app every time. That's the exact issue I'm facing.
Code:
public class MainActivity extends AppCompatActivity {
public static final String TAG = MainActivity.class.getSimpleName();
public static final String DAILY_FORECAST = "DAILY_FORECAST";
private Forecast mForecast;
#Bind(R.id.timeLabel) TextView mTimeLabel;
#Bind(R.id.tempLabel) TextView mTempLabel;
#Bind(R.id.humidityValue) TextView mHumidityValue;
#Bind(R.id.precipValue) TextView mPrecipValue;
#Bind(R.id.summaryLabel) TextView mSummaryLabel;
#Bind(R.id.windSpeedValue) TextView mWindSpeedValue;
#Bind(R.id.relativeLayout) RelativeLayout mRelativeLayout;
#Bind(R.id.container) SwipeRefreshLayout mSwipeRefreshLayout;
#Bind(R.id.locationLabel) TextView mLocationLabel;
double latitude;
double longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
final GPSTracker gpsTracker = new GPSTracker(this);
mSwipeRefreshLayout.setColorSchemeColors(Color.RED, Color.GREEN, Color.BLUE, Color.CYAN);
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
mSwipeRefreshLayout.setRefreshing(false);
}
}, 1500);
if (gpsTracker.getIsGPSTrackingEnabled()){
getForecast(gpsTracker);
updateDisplay(gpsTracker);
} else {
Toast.makeText(MainActivity.this, "Please enable location services.!!", Toast.LENGTH_LONG).show();
gpsTracker.showSettingsAlert();
}
}
});
getForecast(gpsTracker);
}
private void getForecast(final GPSTracker gpsTracker) {
latitude = gpsTracker.getLatitude();
longitude = gpsTracker.getLongitude();
String apiKey = "7d22cdb138cd70f2e9e8d2006cd0461c";
String forecastUrl = "https://api.forecast.io/forecast/" + apiKey
+ "/" + latitude + "," + longitude;
if (isNetworkAvailable()) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(forecastUrl).build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
alertUserAboutError();
}
#Override
public void onResponse(Response response) throws IOException {
try {
String jsonData = response.body().string();
Log.v(TAG, jsonData);
if (response.isSuccessful()) {
mForecast = parseForecastDetails(jsonData);
runOnUiThread(new Runnable() {
#Override
public void run() {
if (gpsTracker.getIsGPSTrackingEnabled()) {
updateDisplay(gpsTracker);
} else {
Toast.makeText(MainActivity.this, "Please enable location services.", Toast.LENGTH_LONG).show();
}
}
});
} else {
alertUserAboutError();
}
} catch (IOException | JSONException e) {
Log.e(TAG, "Exception caught: ", e);
}
}
});
} else {
gpsTracker.showSettingsAlert2();
}
}
private void updateDisplay(GPSTracker gpsTracker) {
Currently currently = mForecast.getCurrently();
String area = gpsTracker.getSubLocality(this);
String city = gpsTracker.getAdminArea(this);
String country = gpsTracker.getCountryName(this);
mLocationLabel.setText(area + "\n" + city + ", " + country);
mTempLabel.setText(currently.getTemperature() + "");
mTimeLabel.setText(currently.getFormattedTime());
mHumidityValue.setText(currently.getHumidity() + "%");
mPrecipValue.setText(currently.getPrecipChance() + "%");
mSummaryLabel.setText(currently.getSummary());
mWindSpeedValue.setText(currently.getWindSpeed() + "");
Drawable drawable = getResources().getDrawable(currently.getBackgroundId());
mRelativeLayout.setBackground(drawable);
}
// irrelevant after this point. (I guess)
private Forecast parseForecastDetails(String jsonData) throws JSONException {
Forecast forecast = new Forecast();
forecast.setCurrently(getCurrentlyDetails(jsonData));
forecast.setHourlyForecast(getHourlyForecast(jsonData));
forecast.setDailyForecast(getDailyForecast(jsonData));
return forecast;
}
private Daily[] getDailyForecast(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
String timezone = forecast.getString("timezone");
JSONObject jsonDaily = forecast.getJSONObject("daily");
JSONArray data = jsonDaily.getJSONArray("data");
Daily[] days = new Daily[data.length()];
for (int i = 0; i < data.length(); i++) {
JSONObject daily = data.getJSONObject(i);
Daily day = new Daily();
day.setSummary(daily.getString("summary"));
day.setTempMax(daily.getDouble("temperatureMax"));
day.setTempMin(daily.getDouble("temperatureMin"));
day.setIcon(daily.getString("icon"));
day.setTime(daily.getLong("time"));
day.setTimezone(timezone);
days[i] = day;
}
return days;
}
private Hourly[] getHourlyForecast(String jsonData) throws JSONException{
JSONObject forecast = new JSONObject(jsonData);
String timezone = forecast.getString("timezone");
JSONObject jsonHourly = forecast.getJSONObject("hourly");
JSONArray data = jsonHourly.getJSONArray("data");
Hourly[] hours = new Hourly[data.length()];
for(int i=0; i < data.length(); i++) {
JSONObject hourly = data.getJSONObject(i);
Hourly hour = new Hourly();
hour.setSummary(hourly.getString("summary"));
hour.setTemp(hourly.getDouble("temperature"));
hour.setIcon(hourly.getString("icon"));
hour.setTime(hourly.getLong("time"));
hour.setTimezone(timezone);
hours[i] = hour;
}
return hours;
}
private Currently getCurrentlyDetails(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
String timezone = forecast.getString("timezone");
JSONObject currently = forecast.getJSONObject("currently");
Currently currentWeather = new Currently();
currentWeather.setHumidity(currently.getDouble("humidity"));
currentWeather.setTime(currently.getLong("time"));
currentWeather.setPrecipChance(currently.getDouble("precipProbability"));
currentWeather.setSummary(currently.getString("summary"));
currentWeather.setTemperature(currently.getDouble("temperature"));
currentWeather.setWindSpeed(currently.getDouble("windSpeed"));
currentWeather.setTimeZone(timezone);
currentWeather.setBackgroundId(currently.getString("icon"));
Log.d(TAG, currentWeather.getFormattedTime());
return currentWeather;
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()){
isAvailable = true;
}
return isAvailable;
}
private void alertUserAboutError() {
AlertDialogFragment dialog = new AlertDialogFragment();
dialog.show(getFragmentManager(), "error_dialog");
}
#OnClick (R.id.dailyButton)
public void startDailyActivity(View view){
Intent intent = new Intent(this, DailyForecastActivity.class);
intent.putExtra(DAILY_FORECAST, mForecast.getDailyForecast());
startActivity(intent);
}
}

Retrieve data from a List

Sorry if the heading is misleading, i couldn't quite put it in words.
Rotten Tomatoes
The list runs fine and looks fine for what i am doing. What i am planning on doing is have a details page now with the synopsis etc. I thought about passing the ID of the movie that is passed on.
If i click on a movie, how can i, in the next page set the image of that movie, the text etc. Basically get all the data i need from the selected movie?
The source code can be found here - Github
Screenshot (Terrible looking but its just messing around):
Thanks
I was having the same problemm in my project but your seems similar so i will give you my solution in order to help.
In my case i was retrieving stocks from a database and each stock had extra 15 prices which i wanted to show everytime i tapped on a stock so check the below answer.
Code:
I created an OBject with String[] to help me retrieve all those 15 prices for each stock and then pass it through Intent.
public class StockList {
private String stockCurrentName;
private String stockCurrentPrice;
private String stockImage;
private String[] restPrices;
public StockList(String stockCurrentName, String stockCurrentPrice, String stockImage, String[] restPrices) {
this.stockCurrentName = stockCurrentName;
this.stockCurrentPrice = stockCurrentPrice;
this.stockImage = stockImage;
this.restPrices = restPrices;
}
public String getStockCurrentName() {
return stockCurrentName;
}
public void setStockCurrentName(String stockCurrentName) {
this.stockCurrentName = stockCurrentName;
}
public String getStockCurrentPrice() {
return stockCurrentPrice;
}
public void setStockCurrentPrice(String stockCurrentPrice) {
this.stockCurrentPrice = stockCurrentPrice;
}
public String getStockImage() {
return stockImage;
}
public void setStockImage(String stockImage) {
this.stockImage = stockImage;
}
public String[] getRestPrices() {
return restPrices;
}
public void setRestPrices(String[] restPrices) {
this.restPrices = restPrices;
}
}
Then is how i retrieved the data:
public class JsonReadTask extends AsyncTask<String, Void, String> {
public JsonReadTask() {
super();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ListLoaderActivity.this);
pDialog.setTitle(R.string.waiting);
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setMessage(getString(R.string.get_stocks));
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.setInverseBackgroundForced(true);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
} catch (Exception e) {
Intent intent1 = new Intent(ListLoaderActivity.this,
RefreshActivity.class);
startActivity(intent1);
ListLoaderActivity.this.finish();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
} catch (Exception e) {
Intent intent1 = new Intent(ListLoaderActivity.this,
RefreshActivity.class);
startActivity(intent1);
ListLoaderActivity.this.finish();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
ListDrawer();
pDialog.dismiss();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
task.execute(new String[]{url});
}
public void ListDrawer() {
customList = new ArrayList<StockList>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("metoxes");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
//for each stock i get its prices.
//In your List for each movie you can get its synopsis and anything else you need.
name = jsonChildNode.optString("name");
price = jsonChildNode.optString("price");
price1 = jsonChildNode.optString("price1");
price2 = jsonChildNode.optString("price2");
price3 = jsonChildNode.optString("price3");
price4 = jsonChildNode.optString("price4");
price5 = jsonChildNode.optString("price5");
price6 = jsonChildNode.optString("price6");
price7 = jsonChildNode.optString("price7");
price8 = jsonChildNode.optString("price8");
price9 = jsonChildNode.optString("price9");
price10 = jsonChildNode.optString("price10");
price11 = jsonChildNode.optString("price11");
price12 = jsonChildNode.optString("price12");
price13 = jsonChildNode.optString("price13");
price14 = jsonChildNode.optString("price14");
price15 = jsonChildNode.optString("price15");
image = jsonChildNode.optString("image");
justPrices = new String[]{price1, price2,
price3, price4, price5, price6, price7, price8, price9,
price10, price11, price12, price13, price14, price15};
loipesTimes = new String[]{"1st Day Value " + price1, "2nd Day Value " + price2, "3rd Day Value " + price3, "4th Day Value " + price4, "5th Day Value " + price5,
"6th Day Value " + price6, "7th Day Value " + price7, "8th Day Value " + price8, "9th Day Value " + price9,
"10th Day Value " + price10, "11th Day Value " + price11, "12th Day Value " + price12, "13th Day Value " + price13, "14th Day Value " + price14, "15th Day Value " + price15};
customList.add(new StockList(name, price, image, justPrices));
}
} catch (Exception e) {
Intent intent1 = new Intent(ListLoaderActivity.this,
RefreshActivity.class);
startActivity(intent1);
ListLoaderActivity.this.finish();
}
ArrayAdapter adapter = new MyStocksAdapter(ListLoaderActivity.this, R.layout.list_item, customList);
adapter.notifyDataSetChanged();
startList.setAdapter(adapter);
}
And then pass the through Intent
private void registerCallClickBack() {
startList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked, int position, long id) {
tv1 = (TextView) viewClicked.findViewById(R.id.stock_name);
tv2 = (TextView) viewClicked.findViewById(R.id.stock_price);
Intent intent = new Intent(ListLoaderActivity.this, StockItem.class);
intent.putExtra("name", tv1.getText().toString());
intent.putExtra("price", tv2.getText().toString());
intent.putExtra("stockInfo", customList.get(position).getRestPrices());
intent.putExtra("stockImage", customList.get(position).getStockImage());
startActivity(intent);
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_right);
}
}
}
I guess you can use it like this and this will help you get it done!!!
Hope i helped you!!!
if you show us what are you doing in your code we could help you more but to pass data from one activity to another you can use intent example :
String value= getIntent().getStringExtra("keyName");
Intent intent = new Intent(this, RatingDescriptionSearchActivity.class);
intent.putExtra("keyName", value);
startActivity(intent);
You should do something like this:
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
YourObject item = arraylist.get(arg2);
TextView textView = (TextView) arg1.findViewById(R.id.textView);
Intent intent = new Intent(ThisActivity.this, SecondActivity.class);
intent.putExtra("textview_value", textView.getText().toString());
startActivity(intent);
}
}
});
you can use intent for pass data from one activity to another exactly how Moudiz say and then retrieve received data like this
String value;
Intent intent = getIntent();
value = intent.getStringExtra("keyName");
If you would have pasted your code then it would be easier to understand your actual problem . But with the data and json given :
1.if you having problem in retrieving data from Json then please follow below link :
http://www.androidhive.info/2012/01/android-json-parsing-tutorial
If passing to next Activity then it would be done using Intent:
String value= getIntent().getStringExtra("Key");
Intent intent = new Intent(this, DataClassNameHere.class);
intent.putExtra("key", value);
startActivity(intent);

Pass Latitude and Longitude to Google API Places Search in Android

I have literally been searching for this for weeks. I am a novice java programmer but I have been able to piece together an app that can use a double latitude and longitude hard coded in the same class. It will show a list of current places surrounding those points. I have another separate class with a method that is able to get the current location based on the gps/network but I can't pass the variables created from this second class to the PlaceRequest class. I have looked through all of the tutorials on the above subjects but there isn't anything combining current location and place search results. I have two getters declared but can't call the variables in these. Again sort of a rookie so may be an easy fix. Any ideas?
Update - Here is my code so far:
GooglePlaceActivity.java
public class GooglePlaceActivity extends Activity {
/** Called when the activity is first created. */
Button btn1;
TextView txt1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.main);
btn1 = (Button)findViewById(R.id.button1);
txt1 = (TextView)findViewById(R.id.textView1);
btn1.setOnClickListener(l);
}
private class SearchSrv extends AsyncTask<Void, Void, PlacesList>{
#Override
protected PlacesList doInBackground(Void... params) {
PlacesList pl = null;
try {
pl = new PlaceRequest().performSearch();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return pl;
}
#Override
protected void onPostExecute(PlacesList result) {
String text = "Result \n";
if (result!=null){
for(Place place: result.results){
text = text + place.name +"\n";
}
txt1.setText(text);
}
setProgressBarIndeterminateVisibility(false);
}
}
View.OnClickListener l = new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
SearchSrv srv = new SearchSrv();
setProgressBarIndeterminateVisibility(true);
srv.execute();
}
};
}
//////////////////////
PlaceRequest.java
public class PlaceRequest {
private static final HttpTransport transport = new ApacheHttpTransport();
private static final String API_KEY = "keyhere";
private static final String LOG_KEY = "GGPlace";
// The different Places API endpoints.
private static final String PLACES_SEARCH_URL = "https://maps.googleapis.com/maps/api/place/search/json?";
private static final String PLACES_AUTOCOMPLETE_URL = "https://maps.googleapis.com/maps/api/place/autocomplete/json?";
private static final String PLACES_DETAILS_URL = "https://maps.googleapis.com/maps/api/place/details/json?";
private static final boolean PRINT_AS_STRING = true;
//double latitude;
//double longitude;
CurrentLocation clo = new CurrentLocation(null);
//clo.onLocationChanged(latitude);
//double longitude = CurrentLocation.getLongitude();
//double latitude = CurrentLocation.getLatitude();
double longi = clo.getLongitude();
double lat = clo.getLatitude();
public PlacesList performSearch() throws Exception {
try {
//CurrentLocation currlo = new CurrentLocation();
//double lat = currlo.getLatitude();
//double longi = currlo.getLongitude();
Log.v(LOG_KEY, "Start Search");
GenericUrl reqUrl = new GenericUrl(PLACES_SEARCH_URL);
reqUrl.put("key", API_KEY);
//reqUrl.put("location", latitude + "," + longitude);
//reqUrl.put("location", getLatitude(latitude) + "," + getLongitude());
reqUrl.put("location", lat + "," + longi);
reqUrl.put("radius", 1600);
reqUrl.put("types", "food");
reqUrl.put("sensor", "false");
Log.v(LOG_KEY, "url= " + reqUrl);
HttpRequestFactory httpRequestFactory = createRequestFactory(transport);
HttpRequest request = httpRequestFactory.buildGetRequest(reqUrl);
Log.v(LOG_KEY, request.execute().parseAsString());
PlacesList places = request.execute().parseAs(PlacesList.class);
Log.v(LOG_KEY, "STATUS = " + places.status);
for (Place place : places.results) {
Log.v(LOG_KEY, place.name);
}
return places;
} catch (HttpResponseException e) {
Log.v(LOG_KEY, e.getResponse().parseAsString());
throw e;
}
catch (IOException e) {
// TODO: handle exception
throw e;
}
}
public static HttpRequestFactory createRequestFactory(final HttpTransport transport) {
return transport.createRequestFactory(new HttpRequestInitializer() {
public void initialize(HttpRequest request) {
GoogleHeaders headers = new GoogleHeaders();
headers.setApplicationName("Google-Places-DemoApp");
request.setHeaders(headers);
JsonHttpParser parser = new JsonHttpParser(new JacksonFactory()) ;
//JsonHttpParser.builder(new JacksonFactory());
//parser.jsonFactory = new JacksonFactory();
request.addParser(parser);
}
});
}
}
/////////////
CurrentLocation.java
public class CurrentLocation {
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds
LocationManager locationManager ;
double latitude=0;
double longitude=0;
public CurrentLocation(Context ctxt) {
super();
locationManager = (LocationManager) ctxt.getSystemService(Context.LOCATION_SERVICE);
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onProviderDisabled(String provider) {}
#Override
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
}
});
}
public double getLatitude() {
return latitude;
}
public double getLongitude() {
return longitude;
}
}
Edit: After looking your complete code, I see a few fundamental design flaws so I'm going to show you how I did it and you can adapt it to your program flow. Please keep in mind that this example is vastly simplified from my original, but it should be enough to get you going.
First, the CurrentLocation.java file. My design decision for wrapping this in a Future was so that I can re-use it in multiple activities with the added bonus of killing it when necessary.
public class CurrentLocation implements Callable<Location> {
private static final String TAG = "CurrentLocation";
private Context context;
private LocationManager lm;
private Criteria criteria;
private Location bestResult;
private boolean locationListenerWorking;
public CurrentLocation(Context context) {
lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
this.context = context;
criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
bestResult = null;
locationListenerWorking = false;
}
public Location call() {
return getLoc();
}
private Location getLoc() {
String provider = lm.getBestProvider(criteria, true);
if (provider != null) {
Log.d(TAG, "Using provider: " +provider);
locationListenerWorking = true;
lm.requestLocationUpdates(provider,
0,
0,
singeUpdateListener,
context.getMainLooper());
} else {
Log.w(TAG, "Couldn't find a location provider");
return null;
}
while (locationListenerWorking) {
// Check for the interrupt signal - terminate if necessary
if (Thread.currentThread().isInterrupted()) {
Log.i(TAG, "User initiated interrupt (cancel signal)");
cleanup();
break;
}
try {
// ghetto implementation of a busy wait...
Thread.sleep(500); // Sleep for half a second
} catch (Exception e) {
Log.d(TAG, "Thread interrupted..");
cleanup();
break;
}
}
return bestResult;
}
private void cleanup() {
if (lm != null) {
Log.d(TAG, "Location manager not null - cleaning up");
lm.removeUpdates(singeUpdateListener);
} else {
Log.d(TAG, "Location manager was NULL - no cleanup necessary");
}
}
/**
* This one-off {#link LocationListener} simply listens for a single location
* update before unregistering itself. The one-off location update is
* returned via the {#link LocationListener} specified in {#link
* setChangedLocationListener}.
*/
private LocationListener singeUpdateListener = new LocationListener() {
public void onLocationChanged(Location location) {
Log.d(TAG, "Got a location update");
if (location == null) {
Log.d(TAG, "Seems as if we got a null location");
} else {
bestResult = location;
}
cleanup();
locationListenerWorking = false;
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
}
Then in your calling class (i.e. where you need the lat/lon coordinates - you want to do this from an Activity):
private class GetLocationTask extends AsyncTask <Void, Void, Location> {
private Future<Location> future;
private ExecutorService executor = new ScheduledThreadPoolExecutor(5);
private boolean cancelTriggered = false;
protected void onPreExecute() {
Log.d(TAG, "Starting location get...");
}
public Location doInBackground(Void... arg) {
CurrentLocation currLoc = new CurrentLocation(getApplicationContext());
future = executor.submit(currLoc);
long LOCATION_TIMEOUT = 20000; // ms = 20 sec
try {
// return future.get(Constants.LOCATION_TIMEOUT, TimeUnit.MILLISECONDS);
return future.get(LOCATION_TIMEOUT, TimeUnit.MILLISECONDS);
} catch (Exception e) {
Log.w(TAG, "Location get timed out");
future.cancel(true);
return null;
}
}
public boolean killTask() {
cancelTriggered = true;
boolean futureCancelRes = future.cancel(true);
this.cancel(true);
Log.d(TAG, "Result of cancelling task: " +futureCancelRes);
return futureCancelRes;
}
protected void onPostExecute(Location res) {
if (cancelTriggered) {
Log.d(TAG, "User initiated cancel - this is okay");
cancelTriggered = false;
} else if (res == null) {
Log.d(TAG, "Could not get a location result");
} else {
double lat = res.getLatitude();
double lon = res.getLongitude();
Log.d(TAG, "Latitude: " +lat);
Log.d(TAG, "Longitude: " +lon);
}
}
}
Finally to wrap things up, here's how you call it:
GetLocationTask t = new GetLocationTask();
t.execute();
And if you need to kill the location update for whatever reason (if your user switches out of your activity, etc), this will kill the AsyncTask as well as the associated Future task.
t.killTask();
P.S. You may want to get your API keys changed and edit it out of your post.

Categories