Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/205.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 在Android中解析Google地图标记的JSON响应_Java_Android_Json_Google Maps - Fatal编程技术网

Java 在Android中解析Google地图标记的JSON响应

Java 在Android中解析Google地图标记的JSON响应,java,android,json,google-maps,Java,Android,Json,Google Maps,我试图从服务器检索JSON响应,对其进行解析,并将标记添加到映射中。我有一个工作地图,并添加了按钮,其中一个我想从服务器加载标记。 调用这样的操作: public void onClick(View v) { switch (v.getId()){ case R.id.btnLoc: if(LocOn == 0){ googleMap.setMyLocationEnabled(tru

我试图从服务器检索JSON响应,对其进行解析,并将标记添加到映射中。我有一个工作地图,并添加了按钮,其中一个我想从服务器加载标记。 调用这样的操作:

 public void onClick(View v) {
        switch (v.getId()){
            case R.id.btnLoc:
                if(LocOn == 0){
                    googleMap.setMyLocationEnabled(true);
                    double lat= googleMap.getMyLocation().getLatitude();
                    double lng = googleMap.getMyLocation().getLongitude();
                    LatLng ll = new LatLng(lat, lng);
                    googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(ll, 18));
                    Loc.setBackgroundResource(R.drawable.loc);
                    LocOn = 1;
                    LoadMarkers.setText("Clear Markers");
                    GetMarkers markers = new GetMarkers();
                    markers.execute();


                } else {
                    LocOn = 0;
                    Loc.setBackgroundResource(R.drawable.noloc);
                    LoadMarkers.setText("Load Markers");
                    googleMap.clear();
                }

        }
    }
“GetMarkers”操作将调用以下内容:

class GetMarkers extends AsyncTask<User, Void, List<JMarker>>{

@Override
protected List<JMarker> doInBackground(User... params) {

    try {
        URL url = new URL("someurl.php");
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        String param = "username="+user.username+"&pw="+user.password;
        OutputStream out = conn.getOutputStream();
        DataOutputStream dataOut = new DataOutputStream(out);
        dataOut.writeBytes(param.trim());

        InputStream in = conn.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line;
        StringBuilder builder = new StringBuilder();
        while((line = reader.readLine()) != null) {
            builder.append(line);
        }
        reader.close();
        String response = builder.toString();

        System.out.println(response); //This works, I'm getting a JSON response. Just need to parse it and return it to onPostExecute for processing. 

    }

    catch (IOException e) {
        e.printStackTrace();
    }

    return null; //This will eventually return the JSON object
}
@Override
protected void onPostExecute(List<JMarker> jMarkers) {
    for(JMarker marker: jMarkers) {
        LatLng position = new LatLng(marker.LAT, marker.LNG);
        googleMap.addMarker(new MarkerOptions().position(position));
    }
}
class GetMarkers扩展异步任务{
@凌驾
受保护列表doInBackground(用户…参数){
试一试{
URL=新URL(“someurl.php”);
HttpsURLConnection conn=(HttpsURLConnection)url.openConnection();
conn.setRequestMethod(“POST”);
连接设置输出(真);
字符串param=“username=“+user.username+”&pw=“+user.password;
OutputStream out=conn.getOutputStream();
DataOutputStream dataOut=新的DataOutputStream(输出);
dataOut.writeBytes(param.trim());
InputStream in=conn.getInputStream();
BufferedReader reader=新的BufferedReader(新的InputStreamReader(in));
弦线;
StringBuilder=新的StringBuilder();
而((line=reader.readLine())!=null){
builder.append(行);
}
reader.close();
字符串响应=builder.toString();
System.out.println(response);//这样做有效,我得到一个JSON响应。只需解析它并将其返回到onPostExecute进行处理。
}
捕获(IOE异常){
e、 printStackTrace();
}
return null;//这将最终返回JSON对象
}
@凌驾
受保护的void onPostExecute(列出jMarker){
for(JMarker标记:jMarkers){
LatLng位置=新LatLng(marker.LAT,marker.LNG);
addMarker(新的MarkerOptions().position(位置));
}
}
}

onPostExecute正在尝试将最终返回的标记添加到映射中


我希望有人能帮助我。先谢谢你

我想在Map.java的第148行有NPE

我想这是

BufferedReader reader = new BufferedReader(new InputStreamReader(in));
这意味着您的输入流为空

这里有两件事:

1) 您应该在获取响应之前关闭OutputStream(out.close())

2) 当收到响应时,如果代码>200,您将无法从conn.getInputStream()获得任何信息;但是在conn.getErrorStream()中出现了服务器错误

您可以这样应用smth:

 StringBuffer response = new StringBuffer();
    System.out.println(conn.getResponseCode());
    try {
        BufferedReader in;

        if (conn.getResponseCode() > 299) {
            in = new BufferedReader(
                    new InputStreamReader(conn.getErrorStream()));
        } else {
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
        }
        String inputLine;


        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

    } catch (Exception ex) {
        ex.printStackTrace();
    }

然而,我会放弃AsyncTask,我会使用http客户端作为改进或截取,因为它可以优雅地处理许多http场景。

我想在Map.java中的第148行有NPE

我想这是

BufferedReader reader = new BufferedReader(new InputStreamReader(in));
这意味着您的输入流为空

这里有两件事:

1) 您应该在获取响应之前关闭OutputStream(out.close())

2) 当收到响应时,如果代码>200,您将无法从conn.getInputStream()获得任何信息;但是在conn.getErrorStream()中出现了服务器错误

您可以这样应用smth:

 StringBuffer response = new StringBuffer();
    System.out.println(conn.getResponseCode());
    try {
        BufferedReader in;

        if (conn.getResponseCode() > 299) {
            in = new BufferedReader(
                    new InputStreamReader(conn.getErrorStream()));
        } else {
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
        }
        String inputLine;


        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

    } catch (Exception ex) {
        ex.printStackTrace();
    }

然而,我会放弃异步任务,我会使用http客户端作为改进或截取,因为它可以优雅地处理大量http场景。

我收到的答案和评论帮助我“搔搔头”,并得出了这个答案。应用程序无法运行并崩溃的原因是我向参数传递了null值。一旦我传递了信息,我就能够得到JSON响应,创建一个JSONArray并返回它。一旦它被发送到onPostExecute,我就在那里解析了JSONArray,并添加了标记。工作代码:

首先,我启动任务

GetMarkers markers = new GetMarkers();
markers.execute(user); //pass the user to the task
任务:

class GetMarkers extends AsyncTask<User, Void, JSONArray>{

        User markeruser = new User(userLocalStore.getLoggedInUser().username, userLocalStore.getLoggedInUser().password);
        JSONArray jsonarray = null;
        @Override
        protected JSONArray doInBackground(User... params) {

            try {
                URL url = new URL("https://someurl.com/file.php");
                HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
                String param = "Username="+markeruser.username+"&pw="+markeruser.password;
                OutputStream out = conn.getOutputStream();
                DataOutputStream dataOut = new DataOutputStream(out);
                dataOut.writeBytes(param.trim());

                InputStream in = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                String line;
                StringBuilder builder = new StringBuilder();
                while((line = reader.readLine()) != null) {
                    builder.append(line);
                }
                reader.close();
                String response = builder.toString();

                jsonarray = new JSONArray(response);
            }

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

            return jsonarray;
        }

        @Override
        protected void onPostExecute(JSONArray jsonarray) {

            try {

                for(int i=0; i<jsonarray.length(); i++){
                    JSONObject obj = jsonarray.getJSONObject(i);

                    String PT = obj.getString("NUMBER");
                    Double LAT = obj.getDouble("LATITUDE");
                    Double LNG = obj.getDouble("LONGITUDE");
                    LatLng position = new LatLng(LAT, LNG);

                    String title = "PT: " + PT;

                    googleMap.addMarker(new MarkerOptions().position(position).title(title).icon(BitmapDescriptorFactory.fromResource(R.drawable.red)));
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
class GetMarkers扩展异步任务{
User markeruser=新用户(userLocalStore.getLoggedInUser().username,userLocalStore.getLoggedInUser().password);
JSONArray JSONArray=null;
@凌驾
受保护的JSONArray doInBackground(用户…参数){
试一试{
URL=新URL(“https://someurl.com/file.php");
HttpsURLConnection conn=(HttpsURLConnection)url.openConnection();
conn.setRequestMethod(“POST”);
连接设置输出(真);
String param=“Username=“+markeruser.Username+”&pw=“+markeruser.password;
OutputStream out=conn.getOutputStream();
DataOutputStream dataOut=新的DataOutputStream(输出);
dataOut.writeBytes(param.trim());
InputStream in=conn.getInputStream();
BufferedReader reader=新的BufferedReader(新的InputStreamReader(in));
弦线;
StringBuilder=新的StringBuilder();
而((line=reader.readLine())!=null){
builder.append(行);
}
reader.close();
字符串响应=builder.toString();
jsonarray=新jsonarray(响应);
}
捕获(IOE异常){
e、 printStackTrace();
}捕获(JSONException e){
e、 printStackTrace();
}
返回jsonarray;
}
@凌驾
受保护的void onPostExecute(JSONArray JSONArray){
试一试{

因为(int i=0;i我收到的答案和评论帮助我“搔搔头”然后得出这个答案。应用程序无法运行和崩溃的原因是我向参数传递了null值。一旦传递了信息,我就能够得到JSON响应,创建JSONArray并返回该响应。一旦发送到onPostExecute,我就在那里解析JSONArray,并添加了标记。工作代码:

首先,我启动任务

GetMarkers markers = new GetMarkers();
markers.execute(user); //pass the user to the task
任务:

class GetMarkers extends AsyncTask<User, Void, JSONArray>{

        User markeruser = new User(userLocalStore.getLoggedInUser().username, userLocalStore.getLoggedInUser().password);
        JSONArray jsonarray = null;
        @Override
        protected JSONArray doInBackground(User... params) {

            try {
                URL url = new URL("https://someurl.com/file.php");
                HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
                String param = "Username="+markeruser.username+"&pw="+markeruser.password;
                OutputStream out = conn.getOutputStream();
                DataOutputStream dataOut = new DataOutputStream(out);
                dataOut.writeBytes(param.trim());

                InputStream in = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                String line;
                StringBuilder builder = new StringBuilder();
                while((line = reader.readLine()) != null) {
                    builder.append(line);
                }
                reader.close();
                String response = builder.toString();

                jsonarray = new JSONArray(response);
            }

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

            return jsonarray;
        }

        @Override
        protected void onPostExecute(JSONArray jsonarray) {

            try {

                for(int i=0; i<jsonarray.length(); i++){
                    JSONObject obj = jsonarray.getJSONObject(i);

                    String PT = obj.getString("NUMBER");
                    Double LAT = obj.getDouble("LATITUDE");
                    Double LNG = obj.getDouble("LONGITUDE");
                    LatLng position = new LatLng(LAT, LNG);

                    String title = "PT: " + PT;

                    googleMap.addMarker(new MarkerOptions().position(position).title(title).icon(BitmapDescriptorFactory.fromResource(R.drawable.red)));
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
class GetMarkers扩展异步任务{
User markeruser=新用户(userLocalStore.getLoggedInUser().username,userLocalStore.getLoggedInUser().password);
JSONArray JSONArray=null;
@凌驾
受保护的JSONArray doInBackground(用户…参数){
试一试{
URL=新URL(“https://someurl.com/file.php");
Https