简体   繁体   中英

Get value from another class

I want to get value from another class, but when I get it in second class it is null. I think it is caused bcs when is something added to this String that code does not run.

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. I can't set value recipientEmail outside of this timer bcs value wouldn't be same. 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 = 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.)

Try to grasp it this way: When you set the recipientEmail field in MapsActivity, you write it on a piece of paper. 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...

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:

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:

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.

Another thing: the recommended way to access object members is to set them private vland add getter methods and where applicable, setter methods. Just leaving the variables accessible is problematic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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