【问题标题】:Preventing NPE on a google maps object防止谷歌地图对象上的 NPE
【发布时间】:2014-07-19 04:52:55
【问题描述】:

我正在使用谷歌地图创建一个项目。但是谷歌地图对象在开始时没有初始化。它发生在课程的后期。但是当没有互联网连接时,课程的另一部分不会加载。那是当我在地图对象的侦听器处获得 NPE 时。如何防止谷歌地图对象上的 NPE。我的 oncreate 方法。

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        list_categories=(ListView) findViewById(R.id.list_categories);
         custom_layout = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.custom_marker_layout,null);
        iv_category_logo=(ImageView) custom_layout.findViewById(R.id.iv_category_logo);

        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();


        }
        //I am getting the NPE at the googleMap object below.How do i initialise it?
        googleMap.setOnMapClickListener(new OnMapClickListener() {

            public void onMapClick(LatLng arg0) {
                Intent i=new Intent(getApplicationContext(),MapFullScreen.class);
                startActivity(i);

            }
        });


    }

【问题讨论】:

  • 为什么不将侦听器包装在一个简单的空检查中?即if(googlemap!=null){ /*your listener*/ }

标签: java android eclipse google-maps


【解决方案1】:

1) 使用 findViewById() 找到您的 mapView。或者你的 MapFragment,如果你是这样做的。

2)在您的地图视图或地图片段上调用 ​​getMap()。

【讨论】:

  • 这是在类中进一步使用的代码: googleMap = ( (SupportMapFragment) getSupportFragmentManager().findFragmentById( R.id.map)).getMap();. 我可以在oncreate 本身。
  • 片段创建后随时可以使用。我不知道你的代码在哪里。如果onCreate中没有创建,那么你还不能设置点击监听。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-30
  • 2014-05-27
  • 2015-06-15
  • 1970-01-01
  • 2023-03-21
  • 1970-01-01
相关资源
最近更新 更多