使用来自服务器的图像作为谷歌地图android中的标记引脚

时间:2014-07-15 12:00:26

标签: java android eclipse google-maps

我想使用来自服务器的图像作为谷歌地图项目的图标图标。但我得到一个空指针异常。代码如下

package com.igloo.storelocater;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

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.UiSettings;
import com.google.android.gms.maps.model.BitmapDescriptor;
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 com.igloo.classes.ConnectionDetector;
import com.igloo.classes.Store_data;




import com.igloo.constants.Constants.Config;

import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.view.Menu;
import android.widget.Toast;

public class MainActivity extends FragmentActivity {
String URL_store="http://footballultimate.com/storelocator/index.php/api/getStoreData";
String URL_image="http://footballultimate.com/storelocator/resource/uploads/";
private ConnectionDetector cd;
private GoogleMap googleMap;
FragmentManager fragManager;
ProgressDialog progressDialog;
double current_latitude,current_longitude;
int bound_radius=10;
HttpResponse response;
String result;
JSONObject jsonobj;
JSONArray category_array;
String[] catarr;
Store_data sobj;
ArrayList<Store_data> list;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        cd = new ConnectionDetector(MainActivity.this);
        Config.isInternetPresent = cd.isConnectingToInternet();
        if (!Config.isInternetPresent) {

            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            // Shuld be fail icon
            builder.setIcon(R.drawable.ic_launcher);
            builder.setMessage("Connection Not Available !" + "\n"
                    + "Please enable your Internet Connection");
            builder.setTitle("INTERNET CONNECTION");
            builder.setPositiveButton("OK",
                    new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    dialog.cancel();
                }
            });
            AlertDialog alert = builder.create();
            alert.show();
        }
        else{
            getcurrentlocation();
        initialiseMap();
        new RetrieveStoreDetails().execute();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    public void getcurrentlocation()
    {
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        // Creating a criteria object to retrieve provider
        Criteria criteria = new Criteria();
        // Getting the name of the best provider
        String provider = locationManager.getBestProvider(criteria, true);
        // Getting Current Location
        Location location = locationManager.getLastKnownLocation(provider);
     // Getting latitude of the current location
        current_latitude=location.getLatitude();

        // Getting longitude of the current location
         current_longitude= location.getLongitude();

    }
    public void initialiseMap()
    {
        if (googleMap == null) {
             googleMap = ( (SupportMapFragment) getSupportFragmentManager().findFragmentById(
                        R.id.map)).getMap();


       }
        // check if map is created successfully or not
        if (googleMap == null) {
            Toast.makeText(getApplicationContext(),
                    "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                    .show();
        }
        else
        {
        googleMap.setMyLocationEnabled(true);
        googleMap.getUiSettings().setMyLocationButtonEnabled(true);
        googleMap.getUiSettings().setCompassEnabled(true);
//          UiSettings uiSettings = googleMap.getUiSettings();
//          uiSettings.setMyLocationButtonEnabled(true);



            }
            //locationManager.requestLocationUpdates(provider, 20000, 0, this);
        LatLng latLng = new LatLng(current_latitude, current_longitude);
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

        // Zoom in the Google Map
        //googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
        googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 12.0f));

        }



    public class RetrieveStoreDetails  extends AsyncTask<String,Void,Void>
    {
            @Override
            protected void onPreExecute() {
                progressDialog = new ProgressDialog(MainActivity.this); 
                progressDialog.setTitle("Processing...");
                progressDialog.setMessage("Please wait...");
                progressDialog.setCancelable(false);
                progressDialog.show();
            }
        @Override
        protected Void doInBackground(String... arg0) {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(URL_store);
            List<NameValuePair> pairs = new ArrayList<NameValuePair>();
            pairs.add(new BasicNameValuePair("current_latitude",""+current_latitude));
            pairs.add(new BasicNameValuePair("current_longitude",""+current_longitude));
            pairs.add(new BasicNameValuePair("bound_radius",""+bound_radius));
            try {
                httppost.setEntity(new UrlEncodedFormEntity(pairs));
                response = httpclient.execute(httppost);
                result=responsetostring.getResponseBody(response);

            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;
        }
        @Override
        protected void onPostExecute(Void result1) {

            getstorevalues(result);
            try{
                   if(progressDialog.isShowing()){
                            progressDialog.dismiss();
                   }  
            }
          catch(Exception e){
              e.printStackTrace();
          }
          finally
          {
               progressDialog.dismiss();
          }

        }

        }
        public void getstorevalues(String result)
        {
            if(result!=null)
            {

                try {
                    list=new ArrayList<Store_data>();
                    jsonobj=new JSONObject(result);
                    category_array=jsonobj.getJSONArray("category");
                    catarr=new String[category_array.length()];
                    JSONObject store_data=jsonobj.getJSONObject("store_data");
                    for(int i=0;i<category_array.length();i++)
                    {
                        catarr[i]=category_array.getString(i);
                    }
                    for(int i=0;i<category_array.length();i++)
                    {
                        JSONArray arrsub=store_data.getJSONArray(catarr[i]);
                        for(int j=0;j<arrsub.length();j++)
                        {
                            sobj=new Store_data();
                            JSONObject d=arrsub.getJSONObject(j);

                            sobj.store_name=d.getString("store_name");
                            sobj.store_image=d.getString("store_image");
                            sobj.store_address=d.getString("store_address");
                            sobj.store_phone=d.getString("store_phone");
                            sobj.store_description=d.getString("store_description");
                            sobj.store_url=d.getString("store_url");
                            sobj.store_latitude=d.getString("store_latitude");
                            sobj.store_longitude=d.getString("store_longitude");
                            sobj.category=catarr[i];
                            list.add(sobj);
                        }
                    }

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
            setvaluesonmap();
        }

    public void setvaluesonmap()
    {
    for(int i=0;i<list.size();i++)
    {
        Store_data s=list.get(i);

        MarkerOptions marker = new MarkerOptions().position(new LatLng(Double.parseDouble(s.store_latitude),Double.parseDouble(s.store_longitude))).title(s.store_name);
      marker.icon(BitmapDescriptorFactory.fromPath(URL_image+s.category+".png"));
      // adding marker
      googleMap.addMarker(marker);
    }
    }

}

LOGCAT如下

07-15 17:09:13.710: E/AndroidRuntime(19588):    at com.google.android.gms.maps.GoogleMap.addMarker(Unknown Source)
07-15 17:28:34.523: E/AndroidRuntime(20295): FATAL EXCEPTION: main
07-15 17:28:34.523: E/AndroidRuntime(20295): java.lang.NullPointerException
07-15 17:28:34.523: E/AndroidRuntime(20295):    at ouq.a(Unknown Source)
07-15 17:28:34.523: E/AndroidRuntime(20295):    at ouq.a(Unknown Source)
07-15 17:28:34.523: E/AndroidRuntime(20295):    at oyg.a(Unknown Source)
07-15 17:28:34.523: E/AndroidRuntime(20295):    at grm.onTransact(SourceFile:167)
07-15 17:28:34.523: E/AndroidRuntime(20295):    at android.os.Binder.transact(Binder.java:279)
07-15 17:28:34.523: E/AndroidRuntime(20295):    at com.google.android.gms.maps.internal.IGoogleMapDelegate$a$a.addMarker(Unknown Source)
07-15 17:28:34.523: E/AndroidRuntime(20295):    at com.google.android.gms.maps.GoogleMap.addMarker(Unknown Source)
07-15 17:28:34.523: E/AndroidRuntime(20295):    at com.igloo.storelocater.MainActivity.setvaluesonmap(MainActivity.java:266)
07-15 17:28:34.523: E/AndroidRuntime(20295):    at com.igloo.storelocater.MainActivity.getstorevalues(MainActivity.java:254)
07-15 17:28:34.523: E/AndroidRuntime(20295):    at com.igloo.storelocater.MainActivity$RetrieveStoreDetails.onPostExecute(MainActivity.java:195)
07-15 17:28:34.523: E/AndroidRuntime(20295):    at com.igloo.storelocater.MainActivity$RetrieveStoreDetails.onPostExecute(MainActivity.java:1)
07-15 17:28:34.523: E/AndroidRuntime(20295):    at android.os.AsyncTask.finish(AsyncTask.java:417)
07-15 17:28:34.523: E/AndroidRuntime(20295):    at android.os.AsyncTask.access$300(AsyncTask.java:127)
07-15 17:28:34.523: E/AndroidRuntime(20295):    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
07-15 17:28:34.523: E/AndroidRuntime(20295):    at android.os.Handler.dispatchMessage(Handler.java:99)
07-15 17:28:34.523: E/AndroidRuntime(20295):    at android.os.Looper.loop(Looper.java:130)
07-15 17:28:34.523: E/AndroidRuntime(20295):    at android.app.ActivityThread.main(ActivityThread.java:3689)
07-15 17:28:34.523: E/AndroidRuntime(20295):    at java.lang.reflect.Method.invokeNative(Native Method)
07-15 17:28:34.523: E/AndroidRuntime(20295):    at java.lang.reflect.Method.invoke(Method.java:507)
07-15 17:28:34.523: E/AndroidRuntime(20295):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842)
07-15 17:28:34.523: E/AndroidRuntime(20295):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
07-15 17:28:34.523: E/AndroidRuntime(20295):    at dalvik.system.NativeStart.main(Native Method)

麻烦的代码似乎是

MarkerOptions marker = new MarkerOptions().position(new LatLng(Double.parseDouble(s.store_latitude),Double.parseDouble(s.store_longitude))).title(s.store_name);
      marker.icon(BitmapDescriptorFactory.fromPath(URL_image+s.category+".png"));
      // adding marker
      googleMap.addMarker(marker);

网址正确但我仍然收到错误。请帮忙!

1 个答案:

答案 0 :(得分:1)

fromPath()仅适用于本地文件(&#34;从绝对文件路径创建位图描述符&#34;)。您需要自己下载图像。