简体   繁体   中英

How to return a value from a html into an android java class using httpresponse

I need to get a return from my html page using javascript function. I always have do this using echo in a php code and it works, but now it is difficult for me because i don't know how to do it using html and javascript This is the javascript code ( I want to get the Json Object as return ):

<?php
    $Via = $_GET["Via"];

  ?>
  <p id=Via name = Via> </p>
  <script>

       var Via = '<?php echo $Via; ?>';


       setTimeout(init(),1);

       function init()
       {

         setTimeout( function(){initMapi(); },100);

       }


       function initMapi() {

         var geocoder = new google.maps.Geocoder();

         var latlng = geocodeAddress(geocoder,Via + ",Trieste");



       }

       function geocodeAddress(geocoder,address) {

         geocoder.geocode({'address': address}, function(results, status) {

           if (status === 'OK') {


           } else {
             alert('Geocode was not successful for the following reason: ' + status);
           }
           var latitude  = results[0].geometry.location.lat().toFixed(5);
           var longitude = results[0].geometry.location.lng().toFixed(5);


           var latlng = {lat: parseFloat(latitude), lng: parseFloat(longitude)};
           var coord = '[{"lat":' + latitude + '},{"lng":' + longitude + '}]';
           var arr = JSON.parse(coord);
           document.getElementById('Via').innerHTML = coord;
           return coord;
         });
       }

       function geocodeLatLng(geocoder , latlng) {

           geocoder.geocode({'location': latlng } , function(results, status) {
             if (status === 'OK') {
               if (results[0]) {

                 document.getElementById('Via').value = mysql_real_escape_string(results[0].formatted_address);

               } else {
                 window.alert('No results found');
               }
             } else {
               window.alert('Geocoder failed due to: ' + status);
             }
           });
         }


       </script>
       <script async defer
       src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB6m6fhBX0vIYDPoDJQTTUPefbFpsvYs6w">
       </script>

And then My Android class :

    package info.androidhive.materialdesign.BackgroudWorker;

/**
 * Created by Alessandro on 27/02/2017.
 */

import android.content.Context;
import android.os.AsyncTask;

import com.google.android.gms.maps.model.LatLng;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URL;
import java.net.URLEncoder;

import info.androidhive.materialdesign.utility.Bus;
import xdroid.toaster.Toaster;


public class BackgroundWorkerConvertAddressIntoLatLng extends AsyncTask<String,Void,String> {
    Context context;

    public boolean next = false;
    public Bus bus ;
    public String street ;
    public LatLng coords = null;
    public BackgroundWorkerConvertAddressIntoLatLng(Context ctx, Bus bus,String street) {
        context = ctx;
        this.street = street;
        this.bus = bus;
    }
    @Override
    protected String doInBackground(String... params) {
        if(params[0] == "coords" && bus.Nome_Linea.equals("29 Andata")) {
            manageBusses(params);
        }
        return null;
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }

    public void manageBusses(String... params){

            try{
                String value=null;

                String link = "http://2.234.155.73/android_TT/getCoordinates.php?Via=" + URLEncoder.encode(street+ ", Trieste", "UTF-8")  ;

                URL url = new URL(link);
                HttpClient client = new DefaultHttpClient();

                HttpGet request = new HttpGet();

                request.setURI(new URI(link));

                HttpResponse response = client.execute(request);

                BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

                StringBuffer sb = new StringBuffer("");

                String line="";

                while (true) {
                    line = in.readLine();
                    if(line.contains("<p id")){
                        if(line.indexOf("<p id=Via name = Via></p>") == -1){
                            sb.append(line);
                            break;
                        }else{
                            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                        }
                    }else {
                    }
                }
                value = sb.toString();
                in.close();
                Toaster.toast("string " + value);

                String json_string = EntityUtils.toString(response.getEntity());
                JSONArray jArray = new JSONArray(json_string);
               // JSONArray jArray = new JSONArray(value);
                // Extract data from json and store into ArrayList as class objects
                Toaster.toast("jArray " + jArray);

                for (int i = 0; i < jArray.length(); i++) {

                    JSONObject json_data = jArray.getJSONObject(i);
                    double lat = json_data.getDouble("lat");
                    double lng = json_data.getDouble("lng");
                    coords = new LatLng(lat,lng);
                    Toaster.toast("coords " + coords.toString());
                    next = true;
                }




            } catch(Exception e){

            }
    }



}

Pleas help me... i really don't know what i should do .

I would strongly advise against reading the HTML into a file and attempting to read it as a conventional file, as there are libraries for the Java platform that make this substantially easier.

http://unirest.io/java.html

This library allows for a json response to be deserialized into an object of your choice and would look something like this:

*Create a class for the data to be deserialized into

public class busLocation
{
   double lat;
   double long;
}

*Get the response and deserialize

This part I cannot do as I do not fully understand how your queries are made, but the link provided shows examples on how to form these.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM