Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/231.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在谷歌地图中下载URL时出现异常_Java_Android_Google Maps - Fatal编程技术网

Java 在谷歌地图中下载URL时出现异常

Java 在谷歌地图中下载URL时出现异常,java,android,google-maps,Java,Android,Google Maps,我的应用程序的一部分有一个地图,当在自动填充的文本视图中输入时,它应该显示在地图中的位置 我可以处理异常,但地图没有显示正确的位置,Log cat显示一条消息,说“下载URL时异常”。我不确定问题出在哪里 主要活动 public class Autocomplete extends FragmentActivity { AutoCompleteTextView atvPlaces; DownloadTask placesDownloadTask; DownloadTask

我的应用程序的一部分有一个地图,当在自动填充的文本视图中输入时,它应该显示在地图中的位置

我可以处理异常,但地图没有显示正确的位置,Log cat显示一条消息,说“下载URL时异常”。我不确定问题出在哪里

主要活动

public class Autocomplete extends FragmentActivity {
    AutoCompleteTextView atvPlaces;
    DownloadTask placesDownloadTask;
    DownloadTask placeDetailsDownloadTask;
    ParserTask placesParserTask;
    ParserTask placeDetailsParserTask;
    GoogleMap googleMap;

    final int PLACES=0;
    final int PLACES_DETAILS=1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_autocomplete);
// Getting a reference to the AutoCompleteTextView
        atvPlaces = (AutoCompleteTextView) findViewById(R.id.atv_places);
        atvPlaces.setThreshold(1);

// Adding textchange listener
        atvPlaces.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
// Creating a DownloadTask to download Google Places matching "s"
                placesDownloadTask = new DownloadTask(PLACES);

// Getting url to the Google Places Autocomplete api
                String url = getAutoCompleteUrl(s.toString());

// Start downloading Google Places
// This causes to execute doInBackground() of DownloadTask class
                placesDownloadTask.execute(url);
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
// TODO Auto-generated method stub
            }

            @Override
            public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
            }
        });

// Setting an item click listener for the AutoCompleteTextView dropdown list
        atvPlaces.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int index,
                                    long id) {

                ListView lv = (ListView) arg0;
                SimpleAdapter adapter = (SimpleAdapter) arg0.getAdapter();

                HashMap<String, String> hm = (HashMap<String, String>) adapter.getItem(index);

// Creating a DownloadTask to download Places details of the selected place
                placeDetailsDownloadTask = new DownloadTask(PLACES_DETAILS);

// Getting url to the Google Places details api
                String url = getPlaceDetailsUrl(hm.get("reference"));

// Start downloading Google Place Details
// This causes to execute doInBackground() of DownloadTask class
                placeDetailsDownloadTask.execute(url);

            }
        });
    }

    private String getAutoCompleteUrl(String place){

// Obtain browser key from https://code.google.com/apis/console
        String key = "key=AIzaSyCfdXATlz7jtM6MEvy9Xh_3_g_Ivc5ysXE";

// place to be be searched
        String input = "input="+place;

// place type to be searched
        String types = "types=geocode";

// Sensor enabled
        String sensor = "sensor=false";

// Building the parameters to the web service
        String parameters = input+"&"+types+"&"+sensor+"&"+key;

// Output format
        String output = "json";

// Building the url to the web service
        String url = "https://maps.googleapis.com/maps/api/place/autocomplete/"+output+"?"+parameters;

        return url;
    }

    private String getPlaceDetailsUrl(String ref){

// Obtain browser key from https://code.google.com/apis/console
        String key = "key=YOUR_API_KEY";

// reference of place
        String reference = "reference="+ref;

// Sensor enabled
        String sensor = "sensor=false";

// Building the parameters to the web service
        String parameters = reference+"&"+sensor+"&"+key;

// Output format
        String output = "json";

// Building the url to the web service
        String url = "https://maps.googleapis.com/maps/api/place/details/"+output+"?"+parameters;

        return url;
    }

    /** A method to download json data from url */
    private String downloadUrl(String strUrl) throws IOException {
        String data = "";
        InputStream iStream = null;
        HttpURLConnection urlConnection = null;
        try{
            URL url = new URL(strUrl);

 // Creating an http connection to communicate with url
            urlConnection = (HttpURLConnection) url.openConnection();

// Connecting to url
            urlConnection.connect();

// Reading data from url
            iStream = urlConnection.getInputStream();

            BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

            StringBuffer sb = new StringBuffer();

            String line = "";
            while( ( line = br.readLine()) != null){
                sb.append(line);
            }

            data = sb.toString();

            br.close();

        }catch(Exception e){
            Log.d("Exception while downloading url", e.toString());
        }finally{
            iStream.close();
            urlConnection.disconnect();
        }
        return data;
    }

    // Fetches data from url passed
    private class DownloadTask extends AsyncTask<String, Void, String>{

        private int downloadType=0;

        // Constructor
        public DownloadTask(int type){
            this.downloadType = type;
        }

        @Override
        protected String doInBackground(String... url) {

// For storing data from web service
            String data = "";

            try{
// Fetching the data from web service
                data = downloadUrl(url[0]);
            }catch(Exception e){
                Log.d("Background Task",e.toString());
            }
            return data;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);

            switch(downloadType){
                case PLACES:
// Creating ParserTask for parsing Google Places
                    placesParserTask = new ParserTask(PLACES);

// Start parsing google places json data
// This causes to execute doInBackground() of ParserTask class
                    placesParserTask.execute(result);

                    break;

                case PLACES_DETAILS :
// Creating ParserTask for parsing Google Places
                    placeDetailsParserTask = new ParserTask(PLACES_DETAILS);

// Starting Parsing the JSON string
// This causes to execute doInBackground() of ParserTask class
                    placeDetailsParserTask.execute(result);
            }
        }
    }

    /** A class to parse the Google Places in JSON format */
    private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>> {

        int parserType = 0;

        public ParserTask(int type){
            this.parserType = type;
        }

        @Override
        protected List<HashMap<String, String>> doInBackground(String... jsonData) {

            JSONObject jObject;
            List<HashMap<String, String>> list = null;

            try{
                jObject = new JSONObject(jsonData[0]);

                switch(parserType){
                    case PLACES :
                        PlaceJSONParser placeJsonParser = new PlaceJSONParser();
// Getting the parsed data as a List construct
                        list = placeJsonParser.parse(jObject);
                        break;
                    case PLACES_DETAILS :
                        PlaceDetailsJSONParser placeDetailsJsonParser = new PlaceDetailsJSONParser();
// Getting the parsed data as a List construct
                        list = placeDetailsJsonParser.parse(jObject);
                }

            }catch(Exception e){
                Log.d("Exception", e.toString());
            }
            return list;
        }

        @Override
        protected void onPostExecute(List<HashMap<String, String>> result) {

            switch(parserType){
                case PLACES :
                    String[] from = new String[] { "description"};
                    int[] to = new int[] { android.R.id.text1 };

// Creating a SimpleAdapter for the AutoCompleteTextView
                    SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), result, android.R.layout.simple_list_item_1, from, to);

// Setting the adapter
                    atvPlaces.setAdapter(adapter);
                    break;
                case PLACES_DETAILS :
                    HashMap<String, String> hm = result.get(0);

// Getting latitude from the parsed data
                    double latitude = Double.parseDouble(hm.get("lat"));

// Getting longitude from the parsed data
                    double longitude = Double.parseDouble(hm.get("lng"));

// Getting reference to the SupportMapFragment of the activity_main.xml
                    SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

// Getting GoogleMap from SupportMapFragment
                    googleMap = fm.getMap();

                    LatLng point = new LatLng(latitude, longitude);

                    CameraUpdate cameraPosition = CameraUpdateFactory.newLatLng(point);
                    CameraUpdate cameraZoom = CameraUpdateFactory.zoomBy(5);

// Showing the user input location in the Google Map
                    googleMap.moveCamera(cameraPosition);
                    googleMap.animateCamera(cameraZoom);

                    MarkerOptions options = new MarkerOptions();
                    options.position(point);
                    options.title("Position");
                    options.snippet("Latitude:"+latitude+",Longitude:"+longitude);

// Adding the marker in the Google Map
                    googleMap.addMarker(options);

                    break;
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
}
公共类自动完成扩展了碎片活动{
自动完成文本视图;
下载任务地点下载任务;
下载任务地点详情下载任务;
ParserTask placesParserTask;
ParserTask placeDetailsParserTask;
谷歌地图谷歌地图;
最终整数位数=0;
最终整数位置_详细信息=1;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u autocomplete);
//获取对AutoCompleteTextView的引用
atvPlaces=(自动完成文本视图)findViewById(R.id.atv_位置);
atvPlaces.设置阈值(1);
//添加文本更改侦听器
addTextChangedListener(新的TextWatcher(){
@凌驾
public void onTextChanged(字符序列、int start、int before、int count){
//创建下载任务以下载与“s”匹配的Google Places
placesDownloadTask=新的下载任务(地点);
//获取Google Places自动完成api的url
字符串url=getAutoCompleteUrl(s.toString());
//开始下载GooglePlaces
//这将导致执行DownloadTask类的doInBackground()
placesDownloadTask.execute(url);
}
@凌驾
更改前的公共无效(字符序列、整数开始、整数计数、,
整数后){
//TODO自动生成的方法存根
}
@凌驾
公共无效后文本已更改(可编辑){
//TODO自动生成的方法存根
}
});
//为AutoCompleteTextView下拉列表设置项目单击侦听器
setOnItemClickListener(新的AdapterView.OnItemClickListener(){
@凌驾
公共链接(AdapterView arg0、视图arg1、整数索引、,
长id){
ListView lv=(ListView)arg0;
SimpleAdapter=(SimpleAdapter)arg0.getAdapter();
HashMap hm=(HashMap)adapter.getItem(index);
//创建下载任务以下载所选地点的地点详细信息
placeDetailsDownloadTask=新的下载任务(PLACES\u DETAILS);
//获取Google Places details api的url
字符串url=getPlaceDetailsUrl(hm.get(“参考”);
//开始下载GooglePlace详细信息
//这将导致执行DownloadTask类的doInBackground()
placeDetailsDownloadTask.execute(url);
}
});
}
私有字符串getAutoCompleteUrl(字符串位置){
//从中获取浏览器密钥https://code.google.com/apis/console
String key=“key=AIzaSyCfdXATlz7jtM6MEvy9Xh_3_g_Ivc5ysXE”;
//搜查地点
字符串输入=“输入=”+位置;
//要搜索的位置类型
String types=“types=geocode”;
//传感器启用
字符串sensor=“sensor=false”;
//为web服务构建参数
字符串参数=输入+“&”+类型+“&”+传感器+“&”+键;
//输出格式
字符串输出=“json”;
//构建web服务的url
字符串url=”https://maps.googleapis.com/maps/api/place/autocomplete/“+输出+”?“+参数;
返回url;
}
私有字符串getPlaceDetailsUrl(字符串引用){
//从中获取浏览器密钥https://code.google.com/apis/console
String key=“key=YOUR\u API\u key”;
//地点参考
String reference=“reference=”+ref;
//传感器启用
字符串sensor=“sensor=false”;
//为web服务构建参数
字符串参数=参考+“&”+传感器+“&”+键;
//输出格式
字符串输出=“json”;
//构建web服务的url
字符串url=”https://maps.googleapis.com/maps/api/place/details/“+输出+”?“+参数;
返回url;
}
/**从url下载json数据的方法*/
私有字符串下载URL(字符串strUrl)引发IOException{
字符串数据=”;
InputStream iStream=null;
HttpURLConnection-urlConnection=null;
试一试{
URL=新URL(strUrl);
//创建http连接以与url通信
urlConnection=(HttpURLConnection)url.openConnection();
//连接到url
urlConnection.connect();
//从url读取数据
iStream=urlConnection.getInputStream();
BufferedReader br=新的BufferedReader(新的InputStreamReader(iStream));
StringBuffer sb=新的StringBuffer();
字符串行=”;
而((line=br.readLine())!=null){
某人附加(行);
}
data=sb.toString();
br.close();
}捕获(例外e){
Log.d(“下载url时出现异常”,例如toString());
}最后{
iStream.close();
urlConnection.disconnect();
}
返回数据;
}
//从传递的url获取数据
私有类DownloadTask扩展了AsyncTask{
私有int downloadType=0;
//建造师
公共下载任务(int类型){
this.downloadType=类型;
}
@凌驾
受保护的字符串doInBackground(字符串…url){
//用于存储来自web服务的数据
字符串数据=”;
试一试{
//从web服务获取数据
数据=下载url(url[0]);
}捕获(例外e){
Log.d(“后台任务”,例如toString());
}
返回数据;
}
@凌驾
受保护的void onPostExecute(字符串结果)
package zybo.example.ramz.map_webview;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


public class PlaceDetailsJSONParser {

/** Receives a JSONObject and returns a list */
public List<HashMap<String,String>> parse(JSONObject jObject){

    Double lat = Double.valueOf(0);
    Double lng = Double.valueOf(0);

    HashMap<String, String> hm = new HashMap<String, String>();
    List<HashMap<String, String>> list = new ArrayList<HashMap<String,String>>();

    try {
        lat = (Double)jObject.getJSONObject("result").getJSONObject("geometry").getJSONObject("location").get("lat");
        lng = (Double)jObject.getJSONObject("result").getJSONObject("geometry").getJSONObject("location").get("lng");

    } catch (JSONException e) {
        e.printStackTrace();
    }catch(Exception e){
        e.printStackTrace();
    }

    hm.put("lat", Double.toString(lat));
    hm.put("lng", Double.toString(lng));

    list.add(hm);

    return list;
}
}
 Reconstruct Branch: AU_LINUX_ANDROID_LA.BF.1.1.1_RB1.05.00.02.042.016   + 62ca4eb + acd831d + 9f8b442 + e027a02 + cba30ba + 53c303a + a649d79 +  23e16f8 + 5e97da7 + cbd2a44 + 33d072a + 7aacf06 + 72b33e7 + 28f6f60 +  b4c13d8 +  NOTHING
09-30 14:44:58.321    2965-3120/zybo.example.ramz.map_webview    I/OpenGLRenderer﹕ Initialized EGL, version 1.4
09-30 14:44:58.390    2965-3120/zybo.example.ramz.map_webview D/OpenGLRenderer﹕ Enabling debug mode 0
09-30 14:44:58.485    2965-3120/zybo.example.ramz.map_webview V/RenderScript﹕ Application requested CPU execution
09-30 14:44:58.498    2965-3120/zybo.example.ramz.map_webview V/RenderScript﹕ 0xb82914f0 Launching thread(s), CPUs 4
09-30 14:45:05.291    2965-3043/zybo.example.ramz.map_webview  D/Volley﹕ [8830] a.a: HTTP response for request=<[ ]  https://clients4.google.com/glm/mmap/api 0x99e6744e NORMAL 1>  [lifetime=7134], [size=60], [rc=200], [retryCount=0]
09-30 14:45:05.298    2965-2965/zybo.example.ramz.map_webview D/Volley﹕ [1] p.b: 7147 ms: [ ] https://clients4.google.com/glm/mmap/api 0x99e6744e NORMAL 1
09-30 14:45:05.712    2965-3044/zybo.example.ramz.map_webview D/Volley﹕ [8831] a.a: HTTP response for request=<[ ] https://csi.gstatic.com/csi?s=maps_android_api&v=3&action=map_start_up&it=map_load.1581,on_create.1,on_resume.1,init.378&irt=1581,379,399,378 0x4d844933 NORMAL 2> [lifetime=6368], [size=0], [rc=204], [retryCount=0]
09-30 14:45:05.759    2965-2965/zybo.example.ramz.map_webview D/Volley﹕ [1] p.b: 6416 ms: [ ] https://csi.gstatic.com/csi?s=maps_android_api&v=3&action=map_start_up&it=map_load.1581,on_create.1,on_resume.1,init.378&irt=1581,379,399,378 0x4d844933 NORMAL 2
09-30 14:45:14.452    2965-3124/zybo.example.ramz.map_webview D/Exception while downloading url﹕ java.io.FileNotFoundException: https://maps.googleapis.com/maps/api/place/autocomplete/json?input=Delhi, India&types=geocode&sensor=false&key=AIzaSyCfdXATlz7jtM6MEvy9Xh_3_g_Ivc5ysXE
09-30 14:45:14.459    2965-3124/zybo.example.ramz.map_webview D/Background Task﹕ java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.InputStream.close()' on a null object reference
09-30 14:45:17.503    2965-3124/zybo.example.ramz.map_webview D/Exception﹕ org.json.JSONException: End of input at character 0 of
09-30 14:45:17.516    2965-3124/zybo.example.ramz.map_webview W/System.err﹕ org.json.JSONException: No value for result
09-30 14:45:17.519    2965-3124/zybo.example.ramz.map_webview W/System.err﹕ at org.json.JSONObject.get(JSONObject.java:389)
09-30 14:45:17.519    2965-3124/zybo.example.ramz.map_webview W/System.err﹕ at org.json.JSONObject.getJSONObject(JSONObject.java:609)
09-30 14:45:17.520    2965-3124/zybo.example.ramz.map_webview W/System.err﹕ at  zybo.example.ramz.map_webview.PlaceDetailsJSONParser.parse(PlaceDetailsJSONParser.java:25)
09-30 14:45:17.520    2965-3124/zybo.example.ramz.map_webview W/System.err﹕ at zybo.example.ramz.map_webview.Autocomplete$ParserTask.doInBackground(Autocomplete.java:280)
09-30 14:45:17.520    2965-3124/zybo.example.ramz.map_webview W/System.err﹕ at zybo.example.ramz.map_webview.Autocomplete$ParserTask.doInBackground(Autocomplete.java:254)
09-30 14:45:17.520    2965-3124/zybo.example.ramz.map_webview W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:292)
09-30 14:45:17.521    2965-3124/zybo.example.ramz.map_webview W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:237)
09-30 14:45:17.521    2965-3124/zybo.example.ramz.map_webview W/System.err﹕ at  android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
09-30 14:45:17.521    2965-3124/zybo.example.ramz.map_webview   W/System.err﹕ at   java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)