-2

google map is loading on emulator givin error that application is stopped unfortunately following is my code package com.ayesha.MIT;

import java.io.BufferedReader;
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.net.HttpURLConnection; 
import java.net.URL; 
import java.util.ArrayList; 
import java.util.HashMap; 
import java.util.List;  
import org.json.JSONObject;  
import android.app.Dialog; 
import android.content.Context; 
import android.content.Intent; 
import android.location.Criteria; 
import android.location.Location; 
import android.location.LocationListener;
import android.location.LocationManager; 
import android.net.ConnectivityManager;
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.os.Handler;
import android.support.v4.app.FragmentActivity; 
import android.util.Log; 
import android.view.KeyEvent;
import android.view.View; 
import android.view.View.OnClickListener;
import android.view.Window; 
import android.widget.ArrayAdapter; 
import android.widget.Button; 
import android.widget.Spinner;  
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory; 
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;


public class Spot_Location_Screen extends FragmentActivity implements
        LocationListener {

    Database_Table_Operations database;
    ArrayList<String> locations = new ArrayList<String>();
    ArrayList<String> latitude = new ArrayList<String>();
    ArrayList<String> longitude = new ArrayList<String>();
    GoogleMap mGoogleMap;
    Spinner mSprPlaceType;
    Intent intent;
    String[] mPlaceType = null;
    String[] mPlaceTypeName = null;
    double mLatitude = 0;
    double mLongitude = 0;
    Button btnFind;
    Button doneButton;
    boolean isFound = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.spot_location_screen);
        mPlaceType = getResources().getStringArray(R.array.place_type);
        mPlaceTypeName = getResources().getStringArray(R.array.place_type_name);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_dropdown_item, mPlaceTypeName);
        mSprPlaceType = (Spinner) findViewById(R.id.spr_place_type);

        mSprPlaceType.setAdapter(adapter);

        btnFind = (Button) findViewById(R.id.btn_find);
        doneButton = (Button) findViewById(R.id.doneButton);
        SupportMapFragment fragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mGoogleMap = fragment.getMap();
        mGoogleMap.setMyLocationEnabled(true);
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        String provider = locationManager.getBestProvider(criteria, true);
        Location location = locationManager.getLastKnownLocation(provider);
        locationManager.requestLocationUpdates(provider, 20000, 0, this);
        database = new Database_Table_Operations(getApplicationContext());
        if (getIntent().getStringExtra("Update") != null) {
            if (getIntent().getStringExtra("Update").equals("true")) {
                addMarker(getIntent().getStringExtra("Date"));
            }
        }
        int status = GooglePlayServicesUtil
                .isGooglePlayServicesAvailable(getBaseContext());
        if (status != ConnectionResult.SUCCESS) {
            int requestCode = 10;
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
                    requestCode);
            dialog.show();
        } else {
            if (location != null) {
                onLocationChanged(location);
            }
            btnFind.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (checkInternetConnection(getApplicationContext())) { // browser
                                                                            // key
                        mGoogleMap.clear();
                        locations.clear();
                        latitude.clear();
                        longitude.clear();
                        int selectedPosition = mSprPlaceType
                                .getSelectedItemPosition();
                        String type = mPlaceType[selectedPosition];
                        StringBuilder sb = new StringBuilder(
                                "https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
                        sb.append("location=" + 33.6000 + "," + 73.0333);
                        sb.append("&radius=20000");
                        sb.append("&types=" + type);
                        sb.append("&sensor=true");

                        sb.append("&key=AIzaSyAVhTyd9GXAkJ9VJ1S7OD9ldrBsQgOH69c");
                        PlacesTask placesTask = new PlacesTask();
                        placesTask.execute(sb.toString());
                    }
                }
            });
            doneButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    // TODO Auto-generated method stub
                    if (checkInternetConnection(getApplicationContext())) {
                        if (getIntent().getStringExtra("Update").equals("true")) {
                            database.open();
                            String myDate = getIntent().getStringExtra("Date");
                            locations.add(database.getLocation(myDate));
                            latitude.add(database.getLatitude(myDate));
                            longitude.add(database.getLongitude(myDate));
                            intent = new Intent(Spot_Location_Screen.this,
                                    Locations_List_View_Screen.class);
                            intent.putStringArrayListExtra("Locations",
                                    locations);
                            intent.putStringArrayListExtra("Latitude", latitude);
                            intent.putStringArrayListExtra("Longitude",
                                    longitude);
                            intent.putExtra("Date",
                                    getIntent().getStringExtra("Date"));
                            intent.putExtra("Update", getIntent()
                                    .getStringExtra("Update"));
                            database.close();
                            startActivity(intent);
                            finish();
                        } else {
                            if (locations.size() != 0) {
                                intent = new Intent(Spot_Location_Screen.this,
                                        Locations_List_View_Screen.class);
                                intent.putStringArrayListExtra("Locations",
                                        locations);
                                intent.putStringArrayListExtra("Latitude",
                                        latitude);
                                intent.putStringArrayListExtra("Longitude",
                                        longitude);
                                intent.putExtra("Date", getIntent()
                                        .getStringExtra("Date"));
                                intent.putExtra("Update", getIntent()
                                        .getStringExtra("Update"));
                                startActivity(intent);
                                finish();
                            }
                        }
                    }
                }
            });
        }
    }

    private String downloadUrl(String strUrl) throws IOException {
        String data = "";
        InputStream iStream = null;
        HttpURLConnection urlConnection = null;
        try {
            URL url = new URL(strUrl);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.connect();
            iStream = urlConnection.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    iStream));
            StringBuffer sb = new StringBuffer();
            String line = "";
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            data = sb.toString();
            br.close();
        } catch (Exception e) {
            Log.d("Exception while downloading url", e.toString());
        } finally {
            iStream.close();
            urlConnection.disconnect();
        }
        return data;
    }

    /** A class, to download Google Places */
    private class PlacesTask extends AsyncTask<String, Integer, String> {
        String data = null;

        @Override
        protected String doInBackground(String... url) {
            try {
                data = downloadUrl(url[0]);
            } catch (Exception e) {
                Log.d("Background Task", e.toString());
            }
            return data;
        }

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

    /** A class to parse the Google Places in JSON format */
    private class ParserTask extends
            AsyncTask<String, Integer, List<HashMap<String, String>>> {
        JSONObject jObject;

        @Override
        protected List<HashMap<String, String>> doInBackground(
                String... jsonData) {
            List<HashMap<String, String>> places = null;
            PlaceJSONParser placeJsonParser = new PlaceJSONParser();
            try {
                jObject = new JSONObject(jsonData[0]);
                places = placeJsonParser.parse(jObject);
            } catch (Exception e) {
                Log.d("Exception", e.toString());
            }
            return places;
        }

        @Override
        protected void onPostExecute(List<HashMap<String, String>> list) {
            mGoogleMap.clear();
            for (int i = 0; i < list.size(); i++) {
                MarkerOptions markerOptions = new MarkerOptions();
                HashMap<String, String> hmPlace = list.get(i);
                double lat = Double.parseDouble(hmPlace.get("lat"));
                latitude.add(String.valueOf(lat));
                double lng = Double.parseDouble(hmPlace.get("lng"));
                longitude.add(String.valueOf(lng));
                String name = hmPlace.get("place_name");
                String vicinity = hmPlace.get("vicinity");
                locations.add(name + ", " + vicinity);
                LatLng latLng = new LatLng(lat, lng);
                markerOptions.position(latLng);
                markerOptions.title(name + " : " + vicinity);
                mGoogleMap.addMarker(markerOptions);
            }
            if (locations.size() > 1) {
                int median = locations.size();
                median = median / 2;
                LatLng myLatLng = new LatLng(Double.parseDouble(latitude
                        .get(median)),
                        Double.parseDouble(longitude.get(median)));
                mGoogleMap.animateCamera(CameraUpdateFactory
                        .newLatLng(myLatLng));
            } else if (locations.size() == 1) {
                LatLng myLatLng = new LatLng(
                        Double.parseDouble(latitude.get(0)),
                        Double.parseDouble(longitude.get(0)));
                mGoogleMap.animateCamera(CameraUpdateFactory
                        .newLatLng(myLatLng));
            }
        }
    }

    @Override
    public void onLocationChanged(Location location) {
        mLatitude = location.getLatitude();
        mLongitude = location.getLongitude();
        LatLng latLng = new LatLng(mLatitude, mLongitude);
        mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(12));
    }

    @Override
    public void onProviderDisabled(String provider) {

        // TODO Auto-generated method stub
    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            intent = new Intent(Spot_Location_Screen.this,
                    SetMeetup_Screen.class);
            startActivity(intent);
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    public void addMarker(String date) {
        database.open();
        MarkerOptions markerOptions = new MarkerOptions();
        final LatLng latLng = new LatLng(Double.parseDouble(database
                .getLatitude(date)), Double.parseDouble(database
                .getLongitude(date)));
        markerOptions.position(latLng);
        markerOptions.title("Your saved location:\n"
                + database.getLocation(date));
        mGoogleMap.addMarker(markerOptions);
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub

                mGoogleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
                database.close();
            }
        }, 2500);
    }

    public boolean checkInternetConnection(Context context) {
        ConnectivityManager conMgr = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (conMgr.getActiveNetworkInfo() != null
                && conMgr.getActiveNetworkInfo().isAvailable()
                && conMgr.getActiveNetworkInfo().isConnected()) {
            isFound = true;
        } else {
            isFound = false;
        }
        return isFound;
    }
}
Angel Angel
  • 19,670
  • 29
  • 79
  • 105
Ayesha
  • 1
  • 2
    Could you please format that so it's readable? I had a look at editing it, but it looks like there are no linebreaks in your code. – andrewsi Jan 02 '15 at 03:12
  • you are going to have to do a better job of formatting your code. Paste in the code (with line feeds) and then hit the {} – nPn Jan 02 '15 at 03:12
  • Unreadable question as it stands. Format it properly. – NickT Jan 02 '15 at 04:36
  • You need to run your project in your real device. – RockStar Jan 02 '15 at 04:52
  • you also need to show the error messages that show up in logcat. It __is__ possible to run google maps on an emulator, provided the emulator has google play services. – nPn Jan 02 '15 at 05:55

2 Answers2

0

Google Android Map API is not able to run Google Maps on the Android emulator. You must use an Real Android device for testing your app.

Refer this link to run Google Map on emulator.

Community
  • 1
  • 1
surhidamatya
  • 2,419
  • 32
  • 56
0

hey ma problem is solved but the emulator is not working with Google maps I think its about the device problem but before it was also not working with the blue stacks for that I've changed the package name

right click the package from

src folder->refactor->rename and

change the package name then change the package name in the manifest then click the on the project ctrl+shiftz+o

it will change the package name throughout your project..

then again create the browser key and android key with new package name and it will load the map.....

and don forget to turn on the API's in Google console... and also check the minimum SDK version if its 9 then go to SSDK manager and install API 9 by clicking the obsolete option there...

surhidamatya
  • 2,419
  • 32
  • 56
Ayesha
  • 1