javaandroidandroid-intentandroid-activityonresume

How to get extra content in a running activity?


I want to send the text entered by the user from current activity (which is LIKE A DIALOG BUT NOT ONE). Activity 1 is in the background and running. I have attempted this as of now:

Second Activity Code:

 submitButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent();

            if(companyNameEditText.getText().toString()!=null) {
                intent.putExtra("companyName", companyNameEditText.getText().toString());
                 nameChanged=true;
                finish();
            }
            else{
                Toast.makeText(ChangeNameActivity.this,"Please enter a value",Toast.LENGTH_SHORT).show();
            }
        }
    });

onDestroy for second Activity:

 @Override
protected void onDestroy() {
    super.onDestroy();
    if(nameChanged)
    {
        activityFinishedWithChanges= true;
    }
}

First Activity's on Resume:

 @Override
protected void onResume() {
    super.onResume();
    if(ChangeNameActivity.activityFinishedWithChanges) {
        companyNameText = findViewById(R.id.companyNameText);
        if (getIntent().hasExtra("companyName")) {
            String companyName = getIntent().getStringExtra("companyName");
            if (companyName != null) {
                if (!companyName.equals("")) {
                    companyNameText.setText(companyName);
                    AppUtils.setNameSharedPreference(BrandSettingsActivity.this, AppConstants.organizationName, getIntent().getStringExtra("companyName"));
                }
            }
        }
    }
}

I'm getting a null value in my case.


Solution

  • Your current aproach doesn't work, because your created Intent which you are using to retrieve the company name isn't used in any way.

    You should use the ActivityResult functionality of the ActivityClass. The basic conecept works like this:

    First you start an activity with the request to return a result with Context.startActivitForResult(Intent,requestCode). The new activity is started and has the oppurtunity to do stuff. When the new activity has retrieved a result it sets its result with Context.setResult() and finish itself afterwards. When the new Activity is finished the function Activity.onActivityResult(requestCode,resultCode,data) is called with the same requestCode, defined in Context.startActivitForResult(Intent,requestCode) and the data and resultCode defined in Context.setResult().

    The official documentation recommends to use a more high level api: https://developer.android.com/training/basics/intents/result