Parsing multiple json object value leading in last value of that object. - android

i am working on an app, where i am getting response(Json) from my remote server.I am also able to parse and place markers based on that response.But i am failing in parsing ph data from response and passing it into another activity.
It is sending only phone number of last json object data in setOnInfoWindowClickListener event.
I know some minor modifications i have to made. Please suggest me in this.
This is the Json response i am getting.
[
{
id: 965,
distance: "1.47",
ph: "33441111",
name: "XYZ",
LS: " abcdef",
point: "77.588018,12.959282"
},
{
id: 965,
distance: "1.47",
ph: "33441111",
name: "XYZ",
LS: " abcdef",
point: "77.588018,12.959282"
},
.
.
]
I tried this way to parse
private class HttpGetTask extends AsyncTask<Void, Void, String> {
// Showing progress dialog
// Passing URL
#Override
protected String doInBackground(Void... params) {
// http stuff
}
#Override
protected void onPostExecute(String result) {
if (pDialog.isShowing())
pDialog.dismiss();
try {
JSONArray json = new JSONArray(result);
for (int i = 0; i < json.length(); i++) {
Log.v("Response", result);
final JSONObject e = json.getJSONObject(i);
String point = e.getString("point");
final String phone = e.getString("ph");
String[] point2 = point.split(",");
double lat1 = Double.parseDouble(point2[0]);
double lng1 = Double.parseDouble(point2[1]);
gMap.addMarker(new MarkerOptions()
.title(e.getString("name"))
.snippet(
e.getString("LS") + "*" + e.getString("ph"))
.position(new LatLng(lng1, lat1))
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.pmr)));
gMap.setInfoWindowAdapter(new InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public View getInfoContents(Marker mrkr) {
// TODO Auto-generated method stub
String name = mrkr.getTitle();
String detail = mrkr.getSnippet();
String trimmedDetail = detail.substring(0, 60);
Log.v("Info", name + " " + detail);
View v = getLayoutInflater().inflate(
R.layout.infowindow, null);
TextView title = (TextView) v
.findViewById(R.id.titleTV);
TextView snippet = (TextView) v
.findViewById(R.id.snippetTV);
title.setText("" + name);
snippet.setText("" + trimmedDetail);
return v;
}
});
gMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker arg0) {
Intent myIntent = new Intent(getBaseContext(),
DtActivity.class);
myIntent.putExtra("title", arg0.getTitle());
myIntent.putExtra("detail", arg0.getSnippet());
myIntent.putExtra("ph1", phone);
// How to access and send ph here.
try {
String ph = e.getString("ph");
myIntent.putExtra("ph", ph);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
startActivity(myIntent);
}
});
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (null != mClient)
mClient.close();
}
}

You need to Initialize the gMap Globaly and add the marker inside the for Loop. Remove the adapter and infowindow click listener codes from form loop and paste it outside. Kindly check the below sample.
public class Example extends FragmentActivity implements OnInfoWindowClickListener {
public static GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mapview);
mMap = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
mMap.setOnInfoWindowClickListener(this);
// Inside the Loop
mMap.addMarker(new MarkerOptions().title(e.getString("name"))
.snippet(e.getString("LS") + "*" + e.getString("ph"))
.position(new LatLng(lng1, lat1))
.icon(BitmapDescriptorFactory.fromResource(R.drawable.pmr)));
// Close the loop
}
#Override
public void onInfoWindowClick(Marker marker) {
// here you can get title, snippet, lat,lng of selected marker. then you
// can start activity.
}
}
Kindly paste the for loop inside the onPostExecute of your Asyntask Class.

Add this code snippet to get the phone number.I have marked it with you will get your phone number here
gMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker arg0) {
///////////////you will get your phone number here////////////////////////
for (int j = 0; j < json.length(); j++) {
JSONObject jo = json.getJSONObject(j);
if(arg0.getTitle().equals(jo.getString("title"))){
String phone= jo.getString("ph");
}
///////////////you will get your phone number here////////////////////////
Intent myIntent = new Intent(getBaseContext(),
DtActivity.class);
myIntent.putExtra("title", arg0.getTitle());
myIntent.putExtra("detail", arg0.getSnippet());
myIntent.putExtra("ph1", phone);
startActivity(myIntent);
}
});
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

The problem is that you are setting a new setInfoWindowAdapter and setOnInfoWindowClickListener
each time you iterate to ur for loop and the last iterate or the last json object will be the InfoWindowAdapter and InfoWindowClickListener that why you are getting the last json, you can only set it once not multiple times except for the add marker.
Dont put the setInfoWindowAdapter and setOnInfoWindowClickListener in the for loop

Related

How to add multiple markers on a google map parsed from json array?

I have written a program in which on button click i am getting the nearby atms from json . This is the link
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=19.052696,72.8713694&radius=1000&types=atm&sensor=true&key=AIzaSyA8szrI9Ue4EwyUwTgz7Nk0c39qMal0pN4
I want to plot the atms on google map but the problem is only the last atm is being displayed on the map
Code : Method to get the atm names , latitude , longitude and vicinity
public void showAtm(){
String getAtmUrl =
"https://maps.googleapis.com/maps/api/place/nearbysearch/json?
location="+lat+","+lng+"&radius=1000&types=atm&sensor=true
&key=AIzaSyA8szrI9Ue4EwyUwTgz7Nk0c39qMal0pN4";
try{
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder().url(getAtmUrl).build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
Map_Activity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getBaseContext(), "Request to atm
locations failed", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onResponse(Call call, Response response) throws
IOException {
Log.i("response ", "onResponse(): " + response);
String result = response.body().string();
Log.i("result",result);
try{
JSONObject jsonObject = new JSONObject(result);
String resultData = jsonObject.getString("results");
JSONArray urlDetails = new JSONArray(resultData);
for (int i = 0 ; i < urlDetails.length(); i++){
JSONObject json = urlDetails.getJSONObject(i);
geometry = json.getString(GOEMETRY);
vicinity = json.getString(VICINITY);
JSONObject jsonGeometry = new JSONObject(geometry);
String geoLocation =
jsonGeometry.getString(LOCATION);
JSONObject jsonLatLng = new JSONObject(geoLocation);
atmLat = jsonLatLng.getDouble(LATITUDE);
atmLong = jsonLatLng.getDouble(LONGITUDE);
atmName = json.getString(ATM_NAME);
Log.i("JsonArrayAtm", "" + atmName);
Log.i("JsonArrayGeometry",geometry);
Log.i("LatLong",""+atmLat+" , "+atmLong);
Log.i("Vicinity", vicinity);
runOnUiThread(new Runnable() {
#Override
public void run() {
moveAtmMap(atmLat ,atmLong );
}
});
}
}catch (Exception e){
e.printStackTrace();
}
}
});
}catch (Exception e){
e.printStackTrace();
}
}
///////////////////////////// atm locations map ///////////////////
private void moveAtmMap(Double amtLatitude,Double atmLongitude){
fragment.getMap().clear();
CameraPosition position = CameraPosition.builder()
.target(new LatLng(amtLatitude, atmLongitude))
.zoom(16f)
.bearing(0.0f)
.tilt(0.0f)
.build();
String msg = amtLatitude+ ", " + atmLongitude;
LatLng latLng = new LatLng(amtLatitude, atmLongitude);
fragment.getMap().addMarker(new MarkerOptions()
.position(latLng));
fragment.getMap().setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter()
{
#Override
public View getInfoWindow(Marker marker) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
View v = getLayoutInflater().inflate(R.layout.atm_custom_window,
null);
TextView atmHeader = (TextView) v.findViewById(R.id.atmName);
TextView atmLocation = (TextView)
v.findViewById(R.id.atmLocation);
atmHeader.setText(atmName);
atmLocation.setText(vicinity);
return v;
}
});
fragment.getMap().setMapType(GoogleMap.MAP_TYPE_NORMAL);
fragment.getMap().setTrafficEnabled(true);
fragment.getMap().setMyLocationEnabled(true);
fragment.getMap().animateCamera(CameraUpdateFactory
.newCameraPosition(position), null);
}
How do i achieve the above , can anyone suggest me ?
Thanks
You have written the method as,
private void moveAtmMap(Double amtLatitude,Double atmLongitude){
fragment.getMap().clear();
...
}
so every time this method will be called, it will clear all previous markers and you will end up having only the last marker.
Edit
for (int i = 0 ; i < urlDetails.length(); i++){
JSONObject json = urlDetails.getJSONObject(i);
String geometry = json.getString(GOEMETRY);
String vicinity = json.getString(VICINITY);
JSONObject jsonGeometry = new JSONObject(geometry);
String geoLocation = jsonGeometry.getString(LOCATION);
JSONObject jsonLatLng = new JSONObject(geoLocation);
double atmLat = jsonLatLng.getDouble(LATITUDE);
double atmLong = jsonLatLng.getDouble(LONGITUDE);
String atmName = json.getString(ATM_NAME);
runOnUiThread(new Runnable() {
#Override
public void run() {
moveAtmMap(atmLat, atmLong, atmName, vicinity, geometry);
}
});
}
and change method like,
private void moveAtmMap(Double amtLatitude,Double atmLongitude, String name, String vicinity, String geometry)
If you want to clear markers from previous web service hit, then do it before you start adding markers for new service hit, like before the for loop.
Remove this line from the method moveAtmMap:
fragment.getMap().clear();
For the first time, write it before for loop in onResponse.
Try this simple code,
for(int i=0;i<jsonArray.length();i++){
MarkerOptions markerOptions;
markerOptions = new MarkerOptions().position(new LatLng(lattitude,
longitude)
).title("Title").snippet("This is snippet");
markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_icon));
marker = googleMap.addMarker(markerOptions);
}
Just replace lattitude,longitude with your values.
If you want to have instance of each marker,then you can put each "marker" object into hashmap with key as marker id. Let me know your feedback.
Note: remove this line - fragment.getMap().clear(); because it will clear map everytime when compiler comes into loop and it will take only last object. this is what happenng right now.

Updating a SQLite database with AsyncTask effectively and efficiently

A SQLite database has fields to store Latitude and Longitude values in a table. A mailing address is input from users in an Add activity.
In the AsyncTask that fetches the LatLng object for the input address, the database write operation is the last statement of its doInBackground method. However, contrary to expectation, the write is happening BEFORE the JSON parsing of the response, writing NULL values for the lat and long initially.
The ListView that front-ends the table shows null Lat and Long values, but the right values after a refresh. The focus rushes back from the Add activity before the JSON parsing and all, which is not the desired behaviour. The ListView must return only after the right LatLng are populated in the table, until which an indeterminate progress bar should keep showing. This IS all working fine, except that
the progress bar appears and vanishes too fast
The ListView is back with other components of its list items properly populated, except the LatLong values.
The question is, how can the database write be forced to wait till the JSON parsing is complete?
Hope this verbose explanation of the situation will suffice. Please mention if more elaboration or code is required.
Many thanks in advance!
Relevant pseudo-code for your kind investigation:
The AsyncTask extension:
private class Geocode extends AsyncTask<String, Void, LatLng>
{
#Override
protected LatLng doInBackground(String...addressToGeocode)
{
int DELAY = 9000;
URL geoCodeURL;
String jsonResponse = null;
String geoCodeRequestURL = Contract.HTTPS_GOOGLE_GEOCODE_PRE_ADDRESS_URL
+ Uri.encode(addressToGeocode[0]);
// Get JSON response
try
{
geoCodeURL = new URL(geoCodeRequestURL);
URLConnection geoCodeURLConnection = geoCodeURL.openConnection();
BufferedReader responseReader = new BufferedReader(new InputStreamReader (geoCodeURLConnection.getInputStream()));
StringBuilder response = new StringBuilder();
int cp;
while((cp = responseReader.read()) != -1)
{
response.append((char)(cp));
}
jsonResponse = response.toString();
Thread.sleep(DELAY); // Force a delay, apparently not enough...
}
catch (relevantExceptions e)
{
Log.i(LOG_TAG, e.toString());
e.printStackTrace();
}
// Parse the LatLng from the JSON response
try
{
JSONObject responseObject = new JSONObject(jsonResponse);
double lat = ((JSONArray) responseObject
.get("results"))
.getJSONObject(0)
.getJSONObject("geometry")
.getJSONObject("location")
.getDouble("lat");
double lng = ((JSONArray) responseObject
.get("results"))
.getJSONObject(0)
.getJSONObject("geometry")
.getJSONObject("location")
.getDouble("lng");
addressLatLng = new LatLng(lat, lng);
object.setLat(lat);
objet.setLng(lng);
}
catch (JSONException e)
{
e.printStackTrace();
}
if (addressLatLng != null)
{
....
}
else
{
Toast.makeText(getApplicationContext(), "Unable to Geocode", Toast.LENGTH_SHORT).show();
}
// Write to the database
dbResult = dbHelper.commitRow(object);
return addressLatLng;
}
#Override
protected void onPreExecute()
{
setProgressBarIndeterminate(true);
setProgressBarIndeterminateVisibility(true);
}
#Override
protected void onPostExecute(LatLng addressLatLng)
{
setProgressBarIndeterminateVisibility(false);
}
} // of getLatLong()
Relevant code in the Add activity that instantiates the AsyncTask:
String addressToGeocode = address +
" " +
city +
country;
AsyncTask<String, Void, LatLng> geocodeTask = new Geocode();
geocodeTask.execute(addressToGeocode);
The Add activity is invoked by a ListView activity like so:
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
int itemId = item.getItemId();
switch (itemId)
{
case (R.id.action_menu_add):
{
Intent addIntent = new Intent(this, AddActivity.class);
startActivityForResult(addIntent, Contract.ADD_REQUEST_CODE);
return true;
}
default:
return false;
}
} // of onOptionsItemSelected()
The ListView's onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK)
{
Bundle b = data.getBundleExtra(GlobeShopperContract.NEW_BUNDLE);
MyObject d = (MyObject) b.get(Contract.NEW_BUNDLE_NAME);
collection.add(d);
dViewAdapter.setNotifyOnChange(true);
dViewAdapter.notifyDataSetChanged();
}
else
...
}

Wrong value for marker text passed to custom view

I am developing an android application which displays a map. When it loads, it displays some addresses and sets markers for them.
When I click on any marker it should display a value in a custom view. But the custom text which is received from a json parser, gets a null value. When I click on the marker again, it sets correct value.
When I click on second marker it display 1st marker value. When I click on 2nd marker again it displays correct value. This process continues
Here's my code:
private class GeocoderTask extends AsyncTask<String, Void, List<Address>>{
private Context mainContxt;
Geocoder geocoder;
public GeocoderTask(Context con){
mainContxt=con;
}
#Override
protected List<Address> doInBackground(String... locationName) {
Geocoder geocoder = new Geocoder(mainContxt);
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocationName(locationName[0],1);
} catch (IOException e) {
e.printStackTrace();
}
return addresses;
}
#Override
protected void onPostExecute(List<Address> addresses) {
for(int i=0;i<addresses.size();i++){
Address address = (Address) addresses.get(i);
latLng = new LatLng(address.getLatitude(), address.getLongitude());
String addressText = String.format("%s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getCountryName());
markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(addressText);
if(i==0) {
googleMap.animateCamera(CameraUpdateFactory.zoomBy(14),2000,null);
googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}
googleMap.addMarker(markerOptions);
}
googleMap.setOnMarkerClickListener(new OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker_address) {
location=marker_address.getTitle();
Toast.makeText(getApplicationContext(),location, Toast.LENGTH_LONG).show();
new LoadSingleProperty().execute();
//new LoadImage().execute();
return false;
}
});
googleMap.setInfoWindowAdapter(new InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker arg0) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
View myContentView = getLayoutInflater().inflate(
R.layout.custom_marker, null);
tempnew_price=getPrice(temptotal_price+"" +email);
TextView tvTitle = ((TextView) myContentView
.findViewById(R.id.title));
// tvTitle.setText(location);
tvSnippet = ((TextView) myContentView
.findViewById(R.id.snippet));
ivProperty = ((ImageView) myContentView
.findViewById(R.id.image_property));
tvTitle.setText(tempcovered_area+ " "+tempnew_price+System.getProperty("line.separator")+templocation);
tvSnippet.setText("A "+ tempbedroom + " "+tempproperty_type);
// new LoadImage().execute();
ivProperty.setImageBitmap(bmp);
return myContentView;
}
});
googleMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker arg0) {
Intent intent = new Intent(getBaseContext(),
search_property_activity.class);
intent.putExtra("Email", email);
startActivity(intent);
}
});
}
}
this is my loadsingle class coding.....
class LoadSingleProperty extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivityMap.this);
pDialog.setMessage("Loading Location. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
if(location!=null && !location.equals("")){
params.add(new BasicNameValuePair("Location", location));
json= jsonParser.makeHttpRequest(url_loc_address, "GET", params);
}
Log.d("MyLocation: ", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
address = json.getJSONArray(TAG_ALL_ADDRESS);
//for (int i = 0; i < address.length(); i++) {
JSONObject c = address.getJSONObject(0);
templocation = c.getString(TAG_LOCATION);
tempcovered_area=c.getString(TAG_COVERED_AREA);
temptotal_price=c.getString(TAG_Total_Price);
tempbedroom=c.getString(TAG_BEDROOM);
tempproperty_type=c.getString(TAG_PROPERTY_TYPE);
tempemail=c.getString(TAG_EMAIL);
//}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
new GeocoderTask(MainActivityMap.this).execute(location);
}
}
Help me friends ...thx in advance
Create a constructor for LoadSingleProperty
class LoadSingleProperty extends AsyncTask<String, String, String> {
Marker mMarker;
public LoadSingleProperty(Marker marker){
mMarker = marker;
}
.
.
.
}
and pass your marker object to it.
new LoadSingleProperty(marker_address).execute();
Once parsing is done set your marker's title using setTitle() method for the marker
mMarker.setTitle(c.getString(TAG_PROPERTY_TYPE));
where you currently do this
tempproperty_type=c.getString(TAG_PROPERTY_TYPE);
Don't forget to refresh your info window once title is reset
How to force refresh contents of the markerInfoWindow
You may also want to show some sort of a loading icon till this time since you're performing a network request.
EDIT:
In case you're using a custom titleview, get a reference to InfoWindowAdapter object before setting as a adapter to googleMap
InfoWindowAdapter infoWindowAdapter = new InfoWindowAdapter() {...
Once parsing is complete, get info window view for mMarker object by calling
infoWindowAdapter.getInfoWindow(mMarker);
Find your textView from the view obtained above and set its text. Then refresh your info window by calling showInfoWindow() to update the info window.
Also please refer this link.
The info window that is drawn is not a live view. The view is rendered
as an image (using View.draw(Canvas)) at the time it is returned. This
means that any subsequent changes to the view will not be reflected by
the info window on the map. To update the info window later (for
example, after an image has loaded), call showInfoWindow()
private class GeocoderTask extends AsyncTask<String, Void, List<Address>> {
private Context mainContxt;
Geocoder geocoder;
public GeocoderTask(Context con) {
mainContxt = con;
}
#Override
protected List<Address> doInBackground(String... locationName) {
Geocoder geocoder = new Geocoder(mainContxt);
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocationName(locationName[0], 1);
} catch (IOException e) {
e.printStackTrace();
}
return addresses;
}
#Override
protected void onPostExecute(List<Address> addresses) {
for (int i = 0; i < addresses.size(); i++) {
Address address = (Address) addresses.get(i);
latLng = new LatLng(address.getLatitude(),
address.getLongitude());
String addressText = String.format(
"%s, %s",
address.getMaxAddressLineIndex() > 0 ? address
.getAddressLine(0) : "", address
.getCountryName());
markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(addressText);
if (i == 0) {
googleMap.animateCamera(CameraUpdateFactory.zoomBy(14),
2000, null);
googleMap.animateCamera(CameraUpdateFactory
.newLatLng(latLng));
}
googleMap.addMarker(markerOptions);
}
}
}
Then you write below code
googleMap.setOnMarkerClickListener(new OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker_address) {
location = marker_address.getTitle();
new LoadSingleProperty().execute();
return false;
}
});
Take another customeWindowAdapter or else use the present one only and set that in onPostExecute() method of 'LoadSingleProperty' AsyncTask..
This will solve that.
ping here you have any queries

Auto Update markers if database was changed or records were added

public class Viewmap extends FragmentActivity implements LocationListener,OnMarkerClickListener
{
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<LatLng> Points;
// url to get all products list
private static String url_all_products = "http://192.168.254.107/android_connect/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_LAT = "lat";
private static final String TAG_LNG = "lng";
GoogleMap googleMap;
// products JSONArray
JSONArray products = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_viewmap);
// Hashmap for ListView
Points = new ArrayList<LatLng>();
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
// Getting Google Play availability status
// Showing status
if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
}else { // Google Play Services are available
// Getting reference to the SupportMapFragment of activity_main.xml
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
// Getting GoogleMap object from the fragment
googleMap = fm.getMap();
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// Enabling MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);
new LoadAllProducts().execute();
// Loading products in Background Thread
}
}
private void DrawMarker(LatLng point){
String add = "";
// Creating an instance of MarkerOptions
MarkerOptions markerOptions = new MarkerOptions();
// Setting latitude and longitude for the marker
markerOptions.position(point);
Geocoder geocoder = new Geocoder(Viewmap.this,
Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(point.latitude,
point.longitude, 1);
add = addresses.get(0).getAddressLine(0) + "," + addresses.get(0).getAddressLine(1) + "," +
addresses.get(0).getAddressLine(2)+","+addresses.get(0).getAddressLine(3);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
// Adding marker on the Google Map
googleMap.addMarker(markerOptions
.title("Click here to do desired action")
.snippet(add));
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Viewmap.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String LAT = c.getString(TAG_LAT);
String LNG = c.getString(TAG_LNG);
double lat = Double.valueOf(LAT);
double lng = Double.valueOf(LNG);
LatLng position = new LatLng(lat, lng);
// adding HashList to ArrayList
Points.add(position);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
if(Points.size()>0) {
for(LatLng point: Points) {
DrawMarker(point);
} }
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
// Setting the zoom level in the map on last position is clicked
}
#Override
public boolean onMarkerClick(Marker marker) {
return false;
}
}
I want to call again the AsyncTask if the DataBase was recently changed or another record was added.. I cant seem to find any codes that will solve this problem .. Basically this is AutoUpdate if the DataBase was changed
Basically you want communication with server that to down link. Every time the server database is updated by location you need the response.
At very beginning or simple level you can use of GCM. Every time the server DB get updated generate a push from server to update your map on device.
But if the frequency of location change is more, you have to write some logic to have minimum location change occur before generating a push from server .

Android looping through onlinedatabase

When i'm trying to loop through the database, my activity hang up and nothing happen.
final JSONArray jArray = new JSONArray(result);
while (i < jArray.length()) {
JSONObject json = jArray.getJSONObject(i);
title.setText(json.getString("PhoneName"));
price.setText("Price : " + json.getString("PhonePrice"));
modelnumber.setText(json.getString("ModelNumber"));
arrowfront.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
i++;
}
});
arrowback.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
i--;
}
});
}
} catch (Exception e) {
Log.e("tag", e.toString());
}
}
i'm trying to connect to the database, at first the textviews display the firstitem, then when i click on arrow i want to display the second row of the table and so on.. But when the activity launch, it hangs up and nothing happens even that i don't receive error's in logcat
And in the logcat, "tag" doesn't appear. Any suggestion??
Ok, do it this way :
final JSONArray jArray = new JSONArray(result);
private ArrayList<HashMap<String,String>> resultList = new ArrayList<HashMap<String,String>>();
int position=0;
for (int i=0;i<jArray.length();i++) {
HashMap<String,String> hm= new HashMap<String,String>();
JSONObject json = jArray.getJSONObject(i);
hm.put("title",json.getString("PhoneName"));
hm.put("price","Price : " + json.getString("PhonePrice"));
hm.put("modelNumber",json.getString("ModelNumber"));
resultList.add(hm);
}
arrowfront.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
position++;
HashMap <String,String> frontHm = new HashMap <String,String>();
frontHm=resultList.get(position);
title.setText(frontHM.get("title");
price.setText(frontHM.get("price"));
modelnumber.setText(frontHM.get("modelNumber"));
}
});
arrowback.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
position--;
HashMap <String,String> backHm = new HashMap <String,String>();
backHm=resultList.get(position);
title.setText(backHM.get("title");
price.setText(backHM.get("price"));
modelnumber.setText(backHM.get("modelNumber"));
}
});
So idea is to keep tracking the position inside global "position" variable. Also I didn't add logic inside click listeners to check first and last position because you can not go out of bounds of arraylist, please do it yourself.

Categories

Resources