【问题标题】:Google Maps: Create marker from different class谷歌地图:从不同的类别创建标记
【发布时间】:2016-10-31 21:25:48
【问题描述】:

在我的 android studio 项目中,我有两个活动:一个 MapsActivity,另一个只是基本的。

当我单击地图时,会启动其他活动,其中包含一组 EditText(文本字段),允许用户为标记定义自定义属性。但是,当我尝试从该类创建标记时,Android Studio 给了我一个错误。

这里是代码,MapsActivity.java:

package com.geekybrackets.virtualtourguide;

import android.content.Intent;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    public GoogleMap mMap;
    double lat = 0;
    double lon = 0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

    }


    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {

            public void onMapClick(LatLng latLng) {

                lat = latLng.latitude;
                lon = latLng.longitude;
                startActivity(new Intent(MapsActivity.this, newMarker.class));



            }
        });


    }



}

NewMarker.java(用户输入标记属性的活动)

package com.geekybrackets.virtualtourguide;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class newMarker extends AppCompatActivity{
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_marker);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);


        Button save_btn = (Button)findViewById(R.id.btn_save);
        save_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                EditText editName = (EditText)findViewById(R.id.editName);
                String marker_title = editName.getText().toString();
                MapsActivity i = new MapsActivity();
                i.mMap.addMarker(new MarkerOptions()
                        .position(new LatLng(i.lat, i.lon))
                        .title(marker_title));
                i.mMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(i.lat, i.lon)));
                finish();
            }
        });
    }

}

这是我得到的错误:

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.geekybrackets.virtualtourguide.newMarker$2.onClick(newMarker.java:42)

我该如何解决这个问题?任何输入将不胜感激:)

【问题讨论】:

    标签: java android google-maps google-maps-api-3


    【解决方案1】:

    哦,孩子,你有几件事要学。

    首先,您永远不应该调用Activity 的构造函数——这个想法是框架创建您的Activity 的一个实例,并且您在onCreate(Bundle savedInstanceState) 上处理初始化逻辑。如果你只是调用构造函数,你会创建一个随机对象,它甚至不会成为你的 UI 的一部分,更不用说你想要使用的 MapsActivity 实例了。

    其次,newMarker 是一个可怕的类名,你应该遵守 Java 约定,类名以大写字母开头,例如 NewMarkerActivity

    第三,如果你想从另一个Activity 更新MapsActivity,你需要从第一个活动开始为了一个结果的第二个活动。基本上,您应该调用startActivityForResult(new Intent(MapsActivity.this, NewMarkerActivity.class)) 而不是当前的调用,并在MapsActivity 中覆盖onActivityResult。 在结果Bundle 中将标题作为额外内容传递并在onActivityResult 中检索它。

    Consult the documentation for getting results

    编辑: 要传递标题,您需要创建一个Intent 并通过调用Intent.putExtra("someKey", theTitle) 传递标题。然后, 用那个Intent 打电话给Activity.setResult(int, Intent)。在onActivityResult,可以通过调用getStringExtra("someKey")获取标题

    最好将该键设置为 public static final 类的 public static final 字段,这样您就不会打错字。

    【讨论】:

    • 非常感谢您的详细回复。收到结果时,我有一个意图,但是我不确定如何将“标题”作为额外的传递。文档似乎也没有帮助。
    • 没问题。查看编辑以了解如何传递您的标题。
    • 啊,是的,听起来不错,太棒了!再次感谢先生的帮助。
    【解决方案2】:

    您无法通过这种方式获取地图实例。您正在创建 MapsActivity 对象的新实例,该对象的 mMap 字段设置为 null。您必须通过setResult(int, Intent)newMarker 中的EditText 返回值。在此处查看更多信息:Getting a Result from an Activity

    【讨论】:

    • @npace 比较快,而且他不怕批评,所以我应该参考他的回复。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-26
    • 2013-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-19
    • 2012-06-19
    相关资源
    最近更新 更多