Get data from another activity

后端 未结 3 1805
没有蜡笔的小新
没有蜡笔的小新 2020-12-09 13:10

Still working on my skills in android.

My problem here is that i have a label from my database that contain a name that is in a spinner, when i click on the label, a

相关标签:
3条回答
  • 2020-12-09 13:31

    You have to pass the information as extras.

    Passing the Information

    Intent i = new Intent();
    i.setClassName("com.example", "com.example.activity");
    i.putExtra("identifier", VALUE);
    startActivity(i);
    

    Getting the Information

    Bundle extras = getIntent().getExtras();
    String exampleString = extras.getString("identifier");
    
    0 讨论(0)
  • 2020-12-09 13:33

    In your second activity, you can get the data from the first activity with the method getIntent() and then getStringExtra(), getIntExtra()...

    Then to return to your first activity you have to use the setResult() method with the intent data to return back as parameter.

    To get the returning data from your second activity in your first activity, just override the onActivityResult() method and use the intent to get the data.

    First Activity:

    //In the method that is called when click on "update"
    Intent intent = ... //Create the intent to go in the second activity
    intent.putExtra("oldValue", "valueYouWantToChange");
    startActivityForResult(intent, someIntValue); //I always put 0 for someIntValue
    
    //In your class
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //Retrieve data in the intent
        String editTextValue = intent.getStringExtra("valueId");
    }
    

    Second Activity:

    //When activity is created
    String value = intent.getStringExtra("oldValue");
    //Then change the editText value
    
    //After clicking on "save"
    Intent intent = new Intent();
    intent.putExtra("valueId", value); //value should be your string from the edittext
    setResult(somePositiveInt, intent); //The data you want to send back
    finish(); //That's when you onActivityResult() in the first activity will be called
    

    Don't forget to start your second activity with the startActivityForResult() method.

    0 讨论(0)
  • 2020-12-09 13:40

    When you want to start second activity, use startActivityForResult(your intent, request code); In your first activity use

    protected void onActivityResult(int requestCode, int resultCode,
                 Intent data) {
             if (requestCode == your_reques_code) {
                 if (resultCode == RESULT_OK) {
                     // do your stuff           
                 }
             }
    }
    

    Before finish second activity dont forget this,

    Intent data = new Intent();
    data.putExtra("text", edtText.getText());
    setResult(RESULT_OK, data); 
    
    0 讨论(0)
提交回复
热议问题