0

Код:

public class MapsActivity3 extends FragmentActivity {


  GoogleMap map;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps3);
       setUpMapIfNeeded();
        new MarkerTask().execute();
    }


    private void setUpMapIfNeeded() {
        if (map != null) {
            MapFragment mapFragment = (MapFragment) getFragmentManager()
                    .findFragmentById(R.id.map);
            map = mapFragment.getMap();
        }
    }

  52!  private class MarkerTask extends AsyncTask<Void, Void, String> {

        private static final String LOG_TAG = "ExampleApp";
        private static final String SERVICE_URL = "http://wewdemo.esy.es/create_product.php";
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        String resultJson = "";


        @Override
        protected String doInBackground(Void... params) {

            try {
                URL url = new URL(SERVICE_URL);
                conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.connect();
                InputStream inputStream = conn.getInputStream();
                StringBuffer buffer = new StringBuffer();
                reader = new BufferedReader(new InputStreamReader(inputStream));
                String line;
                while ((line = reader.readLine()) != null) {
                    buffer.append(line);
                }
                resultJson = buffer.toString();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return resultJson;
        }


        @Override
        protected void onPostExecute(String strJson) {

           // Log.d(LOG_TAG, strJson);

            try
            {
               JSONObject obj = new JSONObject(strJson);
                JSONArray arr = obj.getJSONArray("markers");
                for (int i = 0; i<arr.length(); i++)
                {
                    JSONObject item  = arr.getJSONObject(i);
                   // String lng = item.getString("lng");
                   // String lat = item.getString("lat");
                   // Log.d(LOG_TAG, lng);
                   // Log.d(LOG_TAG, lat);
                    LatLng latLng = new LatLng(item.getDouble("lng"),item.getDouble("lat"));
                    Log.d(LOG_TAG, String.valueOf(latLng));
                   102! map.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)).position(latLng));
                }


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


        }
    }
}

log- отметил на какие строки ругается

java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.model.Marker com.google.android.gms.maps.GoogleMap.addMarker(com.google.android.gms.maps.model.MarkerOptions)' on a null object reference
                                                                                 at com.example.admin.myapplication.MapsActivity3$MarkerTask.onPostExecute(MapsActivity3.java:102)
                                                                                 at com.example.admin.myapplication.MapsActivity3$MarkerTask.onPostExecute(MapsActivity3.java:52)

Сильно не пинать, начинающий=)))

1 ответ 1

1

Рабочий код: Если кому нужно, то могу на github вылить

public class MapsActivity3 extends FragmentActivity {

    SupportMapFragment mapFragment;
  GoogleMap map;

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

        new MarkerTask().execute();
        mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        map = mapFragment.getMap();
        if (map == null) {
            finish();
            return;
        }

       }


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

        private static final String LOG_TAG = "ExampleApp";
        private static final String SERVICE_URL = "http://wewdemo.esy.es/create_product.php";
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        String resultJson = "";


        @Override
        protected String doInBackground(Void... params) {

            try {
                URL url = new URL(SERVICE_URL);
                conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.connect();
                InputStream inputStream = conn.getInputStream();
                StringBuffer buffer = new StringBuffer();
                reader = new BufferedReader(new InputStreamReader(inputStream));
                String line;
                while ((line = reader.readLine()) != null) {
                    buffer.append(line);
                }
                resultJson = buffer.toString();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return resultJson;
        }


        @Override
        protected void onPostExecute(String strJson) {

           // Log.d(LOG_TAG, strJson);

            try
            {
                JSONObject oblect = new JSONObject(strJson);
                JSONArray jsonArray =oblect.getJSONArray("markers");
                for (int i = 0; i<jsonArray.length(); i++)
                {
                    JSONObject item  = jsonArray.getJSONObject(i);



                    String lng = item.getString("lng");
                    String lat = item.getString("lat");
                    double latitude = Double.parseDouble(lat);
                    double longitude = Double.parseDouble(lng);

                    LatLng latLng = new LatLng(latitude, longitude);
                    Log.d(LOG_TAG, String.valueOf(latLng));
                    map.addMarker(new MarkerOptions().position(latLng).icon(
                            BitmapDescriptorFactory
                                    .defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));

                }



            }catch (JSONException e)
            {
                Log.e(LOG_TAG,"Error");
            }


        }
    }
}

Ваш ответ

Нажимая «Отправить ответ», вы соглашаетесь с условиями пользования и подтверждаете, что прочитали политику конфиденциальности.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.