JSON getmap()方法和输入流阅读器

时间:2016-07-13 13:51:06

标签: java android json google-maps google-maps-markers

尝试使用来自JSON文件的google maps android api向地图添加标记。第一个问题是getmap()方法无法解析,第二个是流式传输本地JSON文件,因为它无法应用于int类型。

package pcbapps.pokemap;

import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
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;

import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection; 
import java.net.URL;


public class MapsActivity extends FragmentActivity {
private static final String LOG_TAG = "ExampleApp";

//private static final  SERVICE_URL = canberra;


protected GoogleMap map;
/**
 * ATTENTION: This was auto-generated to implement the App Indexing API.
 * See https://g.co/AppIndexing/AndroidStudio for more information.
 */
private GoogleApiClient client;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    setUpMapIfNeeded();
    // ATTENTION: This was auto-generated to implement the App Indexing API.
    // See https://g.co/AppIndexing/AndroidStudio for more information.
    client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}

@Override
protected void onResume() {
    super.onResume();
    setUpMapIfNeeded();
}

private void setUpMapIfNeeded() {
    if (map == null) {
        map = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map).getMap();
        if (map != null) {
            setUpMap();
        }
    }
}

private void setUpMap() {
    // Retrieve the city data from the web service
    // In a worker thread since it's a network operation.
    new Thread(new Runnable() {
        public void run() {
            try {
                retrieveAndAddCities();
            } catch (IOException e) {
                Log.e(LOG_TAG, "Cannot retrive cities", e);
                return;
            }
        }
    }).start();
}

这是json文件的输入

protected void retrieveAndAddCities() throws IOException {
    HttpURLConnection conn = null;
    final StringBuilder json = new StringBuilder();
    BufferedReader reader = null;
    try {
        // Connect to the web service
       // URL url = new URL(SERVICE_URL);
        //conn = (HttpURLConnection) url.openConnection();

        reader = new BufferedReader(new InputStreamReader(R.raw.canberra));

        // Read the JSON data into the StringBuilder
        int read;
        char[] buff = new char[1024];
        while ((read = reader.read(buff)) != -1) {
            json.append(buff, 0, read);
        }
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error connecting to service", e);
        throw new IOException("Error connecting to service", e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }

    // Create markers for the city data.
    // Must run this on the UI thread since it's a UI operation.
    runOnUiThread(new Runnable() {
        public void run() {
            try {
                createMarkersFromJson(json.toString());
            } catch (JSONException e) {
                Log.e(LOG_TAG, "Error processing JSON", e);
            }
        }
    });
}

void createMarkersFromJson(String json) throws JSONException {
    // De-serialize the JSON string into an array of city objects
    JSONArray jsonArray = new JSONArray(json);
    for (int i = 0; i < jsonArray.length(); i++) {
        // Create a marker for each city in the JSON data.
        JSONObject jsonObj = jsonArray.getJSONObject(i);
        map.addMarker(new MarkerOptions()
                .title(jsonObj.getString("name"))
                .snippet(Integer.toString(jsonObj.getInt("population")))
                .position(new LatLng(
                        jsonObj.getJSONArray("latlng").getDouble(0),
                        jsonObj.getJSONArray("latlng").getDouble(1)
                ))
        );
    }
}

@Override
public void onStart() {
    super.onStart();

    // ATTENTION: This was auto-generated to implement the App Indexing API.
    // See https://g.co/AppIndexing/AndroidStudio for more information.
    client.connect();
    Action viewAction = Action.newAction(
            Action.TYPE_VIEW, // TODO: choose an action type.
            "Main Page", // TODO: Define a title for the content shown.
            // TODO: If you have web page content that matches this app activity's content,
            // make sure this auto-generated web page URL is correct.
            // Otherwise, set the URL to null.
            Uri.parse("http://host/path"),
            // TODO: Make sure this auto-generated app URL is correct.
            Uri.parse("android-app://pcbapps.pokemap/http/host/path")
    );
    AppIndex.AppIndexApi.start(client, viewAction);
}

@Override
public void onStop() {
    super.onStop();

    // ATTENTION: This was auto-generated to implement the App Indexing API.
    // See https://g.co/AppIndexing/AndroidStudio for more information.
    Action viewAction = Action.newAction(
            Action.TYPE_VIEW, // TODO: choose an action type.
            "Main Page", // TODO: Define a title for the content shown.
            // TODO: If you have web page content that matches this app activity's content,
            // make sure this auto-generated web page URL is correct.
            // Otherwise, set the URL to null.
            Uri.parse("http://host/path"),
            // TODO: Make sure this auto-generated app URL is correct.
            Uri.parse("android-app://pcbapps.pokemap/http/host/path")
    );
    AppIndex.AppIndexApi.end(client, viewAction);
    client.disconnect();
}
}

0 个答案:

没有答案