使用android中的json从数据库中检索标记作为数组

时间:2015-07-03 08:30:12

标签: android json google-maps

我可以从我的数据库中检索标记(Lat& Lng),但我不会将检索到的标记存储为数组,然后在adroid的另一个活动中使用它

 package com.map.driver;

    import android.os.AsyncTask;
    import android.support.v4.app.FragmentActivity;
    import android.os.Bundle;

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

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.util.HashMap;
    import java.util.List;

    public class DriRetMap extends FragmentActivity {

    private GoogleMap mMap; // Might be null if Google Play services APK is not available.

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dri_ret_map);
        setUpMapIfNeeded();

        mMap.setMyLocationEnabled(true);

        // Starting locations retrieve task
         new RetrieveTask().execute();


    }

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

    /**
     * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
     * installed) and the map has not already been instantiated.. This will ensure that we only ever
     * call {@link #setUpMap()} once when {@link #mMap} is not null.
     * <p/>
     * If it isn't installed {@link SupportMapFragment} (and
     * {@link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
     * install/update the Google Play services APK on their device.
     * <p/>
     * A user can return to this FragmentActivity after following the prompt and correctly
     * installing/updating/enabling the Google Play services. Since the FragmentActivity may not
     * have been completely destroyed during this process (it is likely that it would only be
     * stopped or paused), {@link #onCreate(Bundle)} may not be called again so we should call this
     * method in {@link #onResume()} to guarantee that it will be called.
     */
    private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.
            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                    .getMap();
            // Check if we were successful in obtaining the map.
            if (mMap != null) {
                setUpMap();
            }
        }
    }

    // Adding marker on the GoogleMaps
    private void addMarker(LatLng latlng) {
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latlng);
        markerOptions.title(latlng.latitude + "," + latlng.longitude);
        mMap.addMarker(markerOptions);
    }

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

        @Override
        protected String doInBackground(Void... params) {
            String strUrl = "http://192.168.43.77/location_marker_mysql/retrieve.php";
            URL url = null;
            StringBuffer sb = new StringBuffer();
            try {
                url = new URL(strUrl);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.connect();
                InputStream iStream = connection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(iStream));
                String line = "";
                while( (line = reader.readLine()) != null){
                    sb.append(line);
                }

                reader.close();
                iStream.close();

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return sb.toString();
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            new ParserTask().execute(result);
        }

    }

    // Background thread to parse the JSON data retrieved from MySQL server
    private class ParserTask extends AsyncTask<String, Void, List<HashMap<String, String>>>{
        @Override
        protected List<HashMap<String,String>> doInBackground(String... params) {
            MarkerJSONParser markerParser = new MarkerJSONParser();
            JSONObject json = null;
            try {
                json = new JSONObject(params[0]);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            List<HashMap<String, String>> markersList = markerParser.parse(json);
            return markersList;
        }

        @Override
        protected void onPostExecute(List<HashMap<String, String>> result) {
            for(int i=0; i<result.size();i++){
                HashMap<String, String> marker = result.get(i);
                LatLng latlng = new LatLng(Double.parseDouble(marker.get("lat")), Double.parseDouble(marker.get("lng")));
                addMarker(latlng);
            }
        }
    }
    /**
     * This is where we can add markers or lines, add listeners or move the camera. In this case, we
     * just add a marker near Africa.
     * <p/>
     * This should only be called once and when we are sure that {@link #mMap} is not null.
     */
    private void setUpMap() {
        mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
    }
}

2 个答案:

答案 0 :(得分:0)

如果你想将你的lat和long传递给另一个活动,请使用下面的包,

在活动A中,

Intent mIntent = new Intent(this, ActivityB.class);
Bundle extras = mIntent.getExtras();
extras.putString("lat", latitudevalue); 
extras.putString("long", longitudevalue); 

在活动B中,

String lat= getIntent().getExtras().getString("lat");
String long= getIntent().getExtras().getString("long");

答案 1 :(得分:0)

为什么不在第二个活动中再次检索它们或将其存储在&#34;缓存&#34;目录或数据库?如果他们是少数也许不值得,但如果他们是数千,那么避免太大的可分解的东西可能是好的。

在任何情况下,当您将标记添加到地图时,您可以将它们保存到本地列表(您将列表设置并初始化为本地变量)

List<LatLng> markerPositions = new ArrayList<LatLng> 
// Adding marker on the GoogleMaps
private void addMarker(LatLng latlng) {
    MarkerOptions markerOptions = new MarkerOptions();
    markerOptions.position(latlng);
    markerOptions.title(latlng.latitude + "," + latlng.longitude);
    mMap.addMarker(markerOptions);
markerPositions.add(latlng);
}

你不能传递Marker对象,因为它不是可分辨的,而LatLng是。 然后将列表添加到intent中: http://developer.android.com/reference/android/content/Intent.html#putParcelableArrayListExtra(java.lang.String,java.util.ArrayList)

做的:

intent.putParcelableArrayListExtra("points",markerPositions);

并在到达的活动中检索: http://developer.android.com/reference/android/content/Intent.html#getParcelableArrayListExtra(java.lang.String)

List<LatLng> positions = intent.getParcelableArrayListExtra("points");

然后,您再次向地图添加新标记或对位置执行任何操作。 标记不能直接传递,因为它们与父图很紧密。