Search code examples
javaandroidtoastonactivityresult

Show toast in onActivityResult


I am attempting to show a toast message when an activity returns with a result. However, I am using a custom inflated toast. Regular toast works fine, but my custom toast won't display. Code below.

Main Activity's onCreate():

@Override
    public void onCreate(Bundle savedInstance){
        super.onCreate(savedInstance);
        setContentView(R.layout.activity_login);

        emailTxt = (TextView)this.findViewById(R.id.email_field);
        passwordTxt = (TextView)this.findViewById(R.id.password_field);

        wgmService = ((MainApp)this.getApplication()).wegmannAdapter.create(WegmannService.class);

        spinner = (ProgressBar)this.findViewById(R.id.progress_bar);
        spinner.setVisibility(View.GONE);

        LayoutInflater inflater = getLayoutInflater();
        View layout = inflater.inflate(R.layout.toast, (ViewGroup)findViewById(R.id.toast_layout));
        toastText = (TextView)layout.findViewById(R.id.toast_text);
        toast = new Toast(getApplicationContext());
        toast.setGravity(Gravity.BOTTOM, 0, 0);
        toast.setDuration(Toast.LENGTH_LONG);
        toast.setView(layout);

        fadeIn = AnimationUtils.loadAnimation(this,  R.anim.fade_in);
        fadeOut = AnimationUtils.loadAnimation(this, R.anim.fade_out);
    }

Main Activity's onActivityResult:

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        switch(requestCode) {
            case SIGNUP_VIEW:
                if(resultCode == RESULT_OK){
                    toastText.setText(data.getExtras().getString("message"));
                    toast.show();
                }
                break;
        }
    }

With the above, I see no toast message. However, if I were to replace the lines in onActivityResult with Toast.makeText(getBaseContext(),"MESSAGE", Toast.LENGTH_LONG).show(), a message does appear. I need to be able to use my custom toast in this instance. Any help or direction appreciated.


Solution

  • Turns out the issue is the line in my other activity. I was setting my extra info with:

    Intent intent = new Intent();
                intent.putExtra("message", R.string.messages_signup_success);
                setResult(RESULT_OK, intent);
                finish();
    

    However, R.string.messages_signup_success returns an int, which when retrieved throws a non-critical warning and proceeds without displaying my toast but without crashing. Altering the code to the below fixes the issue:

    Intent intent = new Intent();
                intent.putExtra("message", getBaseContext().getString(R.string.messages_signup_success));
                setResult(RESULT_OK, intent);
                finish();