繁体   English   中英

在另一个类别中使用一个类别中的变量

[英]use a variable from one class in another class

我正在用android做一个应用程序,正在使用谷歌地图。

我有一个导航屏幕,用户可以在其中放置位置。

然后他们点击一个按钮,就会打开一个地图视图。

在此也应浏览他们输入的位置。

当我运行此代码时,我在map.class中得到了plaats的nullpointerexception

我的导航代码是:

   public class Navigatie extends Activity{
        public String plaats;   

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.navigatie);

            EditText text = (EditText)findViewById(R.id.title);
            this.plaats = text.getText().toString();

            // We create a new ImageButton which links to the map.java class 
            ImageButton imageButton = (ImageButton) findViewById(R.id.imageButton1);
            // We give a onclicklistener method to the button imageButton
                   imageButton.setOnClickListener(new OnClickListener() {

                // if the imageButton is clicked we start a new activity called "Map"
                public void onClick(View v) {
                    startActivity(new Intent(Navigatie.this, Map.class));
                }
            });
        }
    }

编码了位置显示的我的地图的代码是:(只是代码的一部分)

 public Navigatie nav;

 @Override
 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.map);

 mapView = (MapView) findViewById(R.id.mapview1);

 mc = mapView.getController();

 mapView.setBuiltInZoomControls(true);
 String plaats = nav.plaats;
 Geocoder geoCoder = new Geocoder(this, Locale.getDefault());
 try 
 {
   List<Address> addresses = geoCoder.getFromLocationName(plaats, 5);
   String strCompleteAddress = "";
   if (addresses.size() > 0) {
   GeoPoint p = new GeoPoint(
   (int) (addresses.get(0).getLatitude() * 1E6),
   (int) (addresses.get(0).getLongitude() * 1E6));
   mc.animateTo(p);
   mapView.invalidate();
   }
 } catch (IOException e) {
       e.printStackTrace();
 }

将斑纹添加到您的意图中,这会使用

intent.putExtra("location", this.plaats);

然后在地图活动中,在oncreate中:

String map_plaats = this.getIntent().getStringExtra("location");

您似乎想将字符串发送到其他活动。

为此,您可以使用putExtra("key", "value");

您可以像这样在Map.class中获取此字符串

getIntent().getStringExtra("key");

在这里学习以了解有关Intent的更多信息

问题未解决?试试以下方法:

在另一个类别中使用一个类别中的变量

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2023 STACKOOM.COM