How to send string from one activity to another?

后端 未结 8 2147
庸人自扰
庸人自扰 2020-11-22 14:36

I have a string in activity2

String message = String.format(
\"Current Location \\n Longitude: %1$s \\n Latitude: %2$s\", lat, lng); 

I wan

8条回答
  •  醉酒成梦
    2020-11-22 15:06

    In order to insert the text from activity2 to activity1, you first need to create a visit function in activity2.

    public void visitactivity1()
    {
        Intent i = new Intent(this, activity1.class);
        i.putExtra("key", message);
        startActivity(i);
    }
    

    After creating this function, you need to call it from your onCreate() function of activity2:

    visitactivity1();
    

    Next, go on to the activity1 Java file. In its onCreate() function, create a Bundle object, fetch the earlier message via its key through this object, and store it in a String.

        Bundle b = getIntent().getExtras();
        String message = b.getString("key", ""); // the blank String in the second parameter is the default value of this variable. In case the value from previous activity fails to be obtained, the app won't crash: instead, it'll go with the default value of an empty string
    

    Now put this element in a TextView or EditText, or whichever layout element you prefer using the setText() function.

提交回复
热议问题