简体   繁体   English

从另一个班级获得价值

[英]Get value from another class

I want to get value from another class, but when I get it in second class it is null. 我想从另一个班级获得价值,但是当我在第二堂课上获得价值时,它为null。 I think it is caused bcs when is something added to this String that code does not run. 我认为这是由于bcs何时向此String添加了某些内容而导致代码无法运行。

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

a lot of not important code....................................... 很多不重要的代码.......................................

FirebaseDatabase database5 = FirebaseDatabase.getInstance();
    DatabaseReference myRef5 = database5.getReference("userdata");

    myRef5.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            // This method is called once with the initial value and again
            // whenever data at this location is updated.

lot of not improtant code............................................. 很多非关键的代码....................................

mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
                    @Override
                    public boolean onMarkerClick(final Marker marker) {

a lot of not important code........................................... 很多不重要的代码...........................................

new CountDownTimer(2000, 1000) {

           public void onTick(long millisUntilFinished) {

           }
           public void onFinish() {

               progressBar.setVisibility(View.GONE);
               textViewPleaseWait.setVisibility(View.INVISIBLE);

               recipientEmail = marker.getTitle();
               Log.i("omg", recipientEmail);

               dialogBuilder.setMessage("Username: " + usernameAlert + "\n" + "Gender: " + genderAlert
                                       + "\n" + "Age: " + ageAlert + "\n" + marker.getSnippet() + "\n" + marker.getTitle());

               dialogBuilder.setPositiveButton("Send message", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface arg0, int arg1) {
                       Intent intent = new Intent(getApplicationContext(), SendMessage.class);
                       startActivity(intent);

                       recipientEmail = marker.getTitle();
                   }
               });

               dialogBuilder.setNegativeButton("Close", null);
               dialogBuilder.show();


           }
       }.start();

} }

And here it is.... I set value to recipientEmail when timer is done but I must run timer by clicking on marker on map. 这是...。我在计时器完成后将值设置为receiveEmail,但是我必须通过单击地图上的标记来运行计时器。 I can't set value recipientEmail outside of this timer bcs value wouldn't be same. 我无法在此计时器bcs值之外设置值receiveEmail。 So when I call it in another class, normally: 因此,当我在另一个类中调用它时,通常:

MapsActivity mapsActivity = new MapsActivity();

    recipientUsername2 = mapsActivity.getRecipientEmail();
    Log.i("values2", mapsActivity.recipientEmail);

And after running second activity app crashes. 在运行第二项活动后,应用崩溃。

08-28 21:34:25.943 4609-4609/com.samo.facedatefb E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.samo.facedatefb, PID: 4609
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.samo.facedatefb/com.samo.facedatefb.SendMessage}: java.lang.NullPointerException: println needs a message
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2464)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2526)
    at android.app.ActivityThread.access$800(ActivityThread.java:169)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1421)
    at android.os.Handler.dispatchMessage(Handler.java:111)
    at android.os.Looper.loop(Looper.java:194)
    at android.app.ActivityThread.main(ActivityThread.java:5549)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:964)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:759)
 Caused by: java.lang.NullPointerException: println needs a message
    at android.util.Log.println_native(Native Method)
    at android.util.Log.i(Log.java:160)
    at com.samo.facedatefb.SendMessage.onCreate(SendMessage.java:79)
    at android.app.Activity.performCreate(Activity.java:5975)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1111)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2417)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2526) 
    at android.app.ActivityThread.access$800(ActivityThread.java:169) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1421) 
    at android.os.Handler.dispatchMessage(Handler.java:111) 
    at android.os.Looper.loop(Looper.java:194) 
    at android.app.ActivityThread.main(ActivityThread.java:5549) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at java.lang.reflect.Method.invoke(Method.java:372) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:964) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:759) 

Could you help me please? 请问你能帮帮我吗?

Here you create a new , (presumably empty ) MapsActivity instance: 在这里,您将创建一个新的 MapsActivity实例(可能为 ):

MapsActivity mapsActivity = new MapsActivity();

And two lines below, you try to read from it: 在下面的两行中,您尝试阅读以下内容:

recipientUsername2 = mapsActivity.getRecipientEmail();

No wonder it is empty. 难怪它是空的。 This MapsActivity is not the MapsActivity you're looking for... (Just this time it is not a Jedi trick.) 这个MapsActivity不是您要寻找的MapsActivity ... (这只是绝地绝招)。

Try to grasp it this way: When you set the recipientEmail field in MapsActivity, you write it on a piece of paper. 尽量把握这样说:当您设置recipientEmail在MapsActivity场,你把它写在一张纸上。 With the new MapsActivity() constructor call, you get a new piece of paper from your drawer - a different one, and now you try to read something off that paper, which you wrote on the other one... 随着new MapsActivity()构造函数调用,你得到的文件从你的抽屉里一个新的作品-一个不同的,而现在你试着读的东西掉纸张,您对其他一书中写道...

To be able to have that information, you have to put it somewhere - set it to an instance of a class that you pass around, set it to a field in the class you plan to use next, etc... 为了获得该信息,您必须将其放置在某处-将其设置为您要传递的类的实例,将其设置为您计划在下一个使用的类中的字段,等等。

This time however, I think setting the recipientEmail String as an Extra to the SendMail activity would be the way to go: 然而,这一次,我想设置recipientEmail字符串作为额外的SendMail活动将是要走的路:

Intent intent = new Intent(getApplicationContext(), SendMessage.class);
intent.putExtra("RECIPIENT_EMAIL", marker.getTitle());
startActivity(intent); //this has to be after the putExtra call

And when you try to access it in the SendMail activity: 当您尝试在SendMail活动中访问它时:

String recipientEmail = null;
Bundle extras = getIntent().getExtras();
if(extras == null) {
    throw new IllegalStateException("No email address found at SendMail activity!");
} else {
    recipientEmail = extras.getString("RECIPIENT_EMAIL");
}

Also, read the answers to this question I usually turn to when having to deal with Extras. 另外,请阅读当我不得不处理Extras时通常会转向的这个问题的答案。

Another thing: the recommended way to access object members is to set them private vland add getter methods and where applicable, setter methods. 另一件事:访问对象成员的推荐方法是将其设置为私有vland add getter方法,并在适用时设置setter方法。 Just leaving the variables accessible is problematic. 仅使变量可访问是有问题的。

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

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