如何从网址获取json到地图

时间:2017-06-11 10:11:13

标签: android json

我想将我的坐标标记为谷歌地图,但是当我尝试从json url显示坐标时我有一些错误,如果我在字符串变量中使用json,它的工作原理,但是如果我使用json输出的url我得到了一些错误,这是我的错误通知:

06-11 17:09:03.350 8874-8874/? I/art: Late-enabling -Xcheck:jni
06-11 17:09:03.496 8874-8884/com.spp.udi.udi I/art: Background sticky concurrent mark sweep GC freed 3264(175KB) AllocSpace objects, 0(0B) LOS objects, 67% free, 412KB/1286KB, paused 6.981ms total 57.503ms
06-11 17:09:03.535 8874-8874/com.spp.udi.udi W/System: ClassLoader referenced unknown path: /data/app/com.spp.udi.udi-1/lib/arm64
06-11 17:09:03.542 8874-8874/com.spp.udi.udi I/InstantRun: Instant Run Runtime started. Android package is com.spp.udi.udi, real application class is null.
06-11 17:09:05.153 8874-8874/com.spp.udi.udi W/System: ClassLoader referenced unknown path: /data/app/com.spp.udi.udi-1/lib/arm64
06-11 17:09:05.233 8874-8874/com.spp.udi.udi I/GMPM: App measurement is starting up, version: 8487
06-11 17:09:05.233 8874-8874/com.spp.udi.udi I/GMPM: To enable debug logging run: adb shell setprop log.tag.GMPM VERBOSE
06-11 17:09:05.382 8874-8874/com.spp.udi.udi V/Monotype: SetAppTypeFace- try to flip, app = com.spp.udi.udi
06-11 17:09:05.390 8874-8874/com.spp.udi.udi V/Monotype:     Typeface getFontPathFlipFont - systemFont = /data/data/flipfont/app_fonts/Felbridge#Felbridge
06-11 17:09:05.418 8874-8874/com.spp.udi.udi V/Monotype: SetAppTypeFace- try to flip, app = com.spp.udi.udi
06-11 17:09:05.418 8874-8874/com.spp.udi.udi V/Monotype:     Typeface getFontPathFlipFont - systemFont = /data/data/flipfont/app_fonts/Felbridge#Felbridge
06-11 17:09:05.648 8874-8874/com.spp.udi.udi V/Monotype: SetAppTypeFace- try to flip, app = com.spp.udi.udi
06-11 17:09:05.648 8874-8874/com.spp.udi.udi V/Monotype:     Typeface getFontPathFlipFont - systemFont = /data/data/flipfont/app_fonts/Felbridge#Felbridge
06-11 17:09:05.832 8874-8874/com.spp.udi.udi I/zzad: Making Creator dynamically
06-11 17:09:05.974 8874-8884/com.spp.udi.udi I/art: Background partial concurrent mark sweep GC freed 401(23KB) AllocSpace objects, 5(84KB) LOS objects, 39% free, 3MB/5MB, paused 7.671ms total 33.791ms
06-11 17:09:06.151 8874-8874/com.spp.udi.udi I/Google Maps Android API: Google Play services client version: 8487000
06-11 17:09:06.168 8874-8874/com.spp.udi.udi I/Google Maps Android API: Google Play services package version: 11055446
06-11 17:09:06.635 8874-8969/com.spp.udi.udi W/agl: copyMemory is missing from platform - proto runtime falling back to safer methods.
06-11 17:09:06.653 8874-8950/com.spp.udi.udi I/DpmTcmClient: RegisterTcmMonitor from: com.android.okhttp.TcmIdleTimerMonitor
06-11 17:09:06.953 8874-8987/com.spp.udi.udi D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
06-11 17:09:07.242 8874-8874/com.spp.udi.udi I/DpmTcmClient: RegisterTcmMonitor from: org.apache.http.impl.conn.TcmIdleTimerMonitor
06-11 17:09:07.248 8874-8874/com.spp.udi.udi W/System: ClassLoader referenced unknown path: /system/framework/com.qualcomm.qti.GBAHttpAuthentication.jar
06-11 17:09:07.257 8874-8874/com.spp.udi.udi D/AndroidRuntime: Shutting down VM
06-11 17:09:07.259 8874-8874/com.spp.udi.udi E/AndroidRuntime: FATAL EXCEPTION: main
                                                               Process: com.spp.udi.udi, PID: 8874
                                                               android.os.NetworkOnMainThreadException
                                                                   at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273)
                                                                   at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:110)
                                                                   at libcore.io.IoBridge.connectErrno(IoBridge.java:137)
                                                                   at libcore.io.IoBridge.connect(IoBridge.java:122)
                                                                   at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
                                                                   at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:452)
                                                                   at java.net.Socket.connect(Socket.java:884)
                                                                   at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:124)
                                                                   at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:149)
                                                                   at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:169)
                                                                   at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:124)
                                                                   at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:370)
                                                                   at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:560)
                                                                   at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:492)
                                                                   at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:470)
                                                                   at com.spp.udi.udi.JSONParser.AmbilJson(JSONParser.java:100)
                                                                   at com.spp.udi.udi.MainActivity.fetchDataFromJSON(MainActivity.java:49)
                                                                   at com.spp.udi.udi.MainActivity.onMapReady(MainActivity.java:43)
                                                                   at com.google.android.gms.maps.SupportMapFragment$zza$1.zza(Unknown Source)
                                                                   at com.google.android.gms.maps.internal.zzo$zza.onTransact(Unknown Source)
                                                                   at android.os.Binder.transact(Binder.java:387)
                                                                   at com.google.android.gms.maps.internal.aq.a(:com.google.android.gms.DynamiteModulesB:5)
                                                                   at com.google.maps.api.android.lib6.impl.bb.run(:com.google.android.gms.DynamiteModulesB:5)
                                                                   at android.os.Handler.handleCallback(Handler.java:739)
                                                                   at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                   at android.os.Looper.loop(Looper.java:148)
                                                                   at android.app.ActivityThread.main(ActivityThread.java:5451)
                                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
06-11 17:09:08.915 8874-8985/com.spp.udi.udi W/DynamiteModule: Local module descriptor class for com.google.android.gms.googlecertificates not found.
06-11 17:09:08.923 8874-8985/com.spp.udi.udi W/DynamiteModule: Failed to load module via V2: java.lang.ClassNotFoundException: Didn't find class "com.google.android.gms.dynamite.DynamiteModule$DynamiteLoaderClassLoader" on path: DexPathList[[zip file "/data/app/com.spp.udi.udi-1/base.apk"],nativeLibraryDirectories=[/data/app/com.spp.udi.udi-1/lib/arm64, /vendor/lib64, /system/lib64]]
06-11 17:09:08.927 8874-8985/com.spp.udi.udi I/DynamiteModule: Considering local module com.google.android.gms.googlecertificates:0 and remote module com.google.android.gms.googlecertificates:3
06-11 17:09:08.928 8874-8985/com.spp.udi.udi I/DynamiteModule: Selected remote version of com.google.android.gms.googlecertificates, version >= 3
06-11 17:09:08.960 8874-8985/com.spp.udi.udi W/System: ClassLoader referenced unknown path: /data/data/com.google.android.gms/app_chimera/m/00000004/n/arm64-v8a

这是我的主要活动:

package com.spp.udi.udi;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

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

public class MainActivity extends FragmentActivity implements OnMapReadyCallback {
    Context mContext;
    private GoogleMap mMap;
    JSONParser jParser = new JSONParser();
    String link_url = "http://10.0.0.2/project/s9/udi/android/peta.php";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));

        // Fetch data
        fetchDataFromJSON();
    }

    private void fetchDataFromJSON()
    {
        // JSON response
        JSONObject json = jParser.AmbilJson(link_url);

        try
        {
            JSONArray jsonArray = json.getJSONArray("info");

            // Clear old markers
            mMap.clear();

            // Looping through all info and show on map
            for (int i = 0; i < jsonArray.length(); i++) {

                JSONObject jsonObject = jsonArray.getJSONObject(i);


                String name = jsonObject.getString("nama");
                String description = jsonObject.getString("deskripsi");
                String latitude = jsonObject.getString("lat");
                String longitude = jsonObject.getString("lng");

                // Add marker
                addMarkerToMap(latitude, longitude, name, description);
            }

        } catch (JSONException e) {
            e.printStackTrace();
            Toast.makeText(mContext, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }

    }

    public void addMarkerToMap(String latitude, String longitude, String title, String description)
    {
        double lat = Double.parseDouble(latitude);
        double lng = Double.parseDouble(longitude);

        // create marker
        MarkerOptions marker = new MarkerOptions().position(new LatLng(lat, lng))
                .title(title)
                .snippet(description);

        // Marker icon
        marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));

        // Add marker to map
        mMap.addMarker(marker);
    }
}

1 个答案:

答案 0 :(得分:0)

  

您正在主线程中执行网络任务,了解其获取的原因   强制关闭,作为android规则和规则,我们不能预先形成任何   任何Activity的主线程中的网络操作。所以你应该使用   AsyncTask用于在主线程中执行网络任务。如下:

private class NetWorkTask extends AsyncTask<String, Void, String>{

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... params) {
            return null;
        }

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

详情请参阅以下链接

http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html