Question

So the problem is the following:

I'm generating a contentView in code with multiple for and foreach loops and have all of the listeners for buttons generated dynamically. But if I want to make changes in some TextView or something, I start a new Activity, and I want to listen for on onActivityResult inside a listener. I'm wondering if that's even possible and I could really use some help.

Here's my code:

    Button goliButton = new Button(this);
        goliButton.setText("+");
        goliButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent i = new Intent(TekmaLive.this,DodajStrel.class);
                i.putExtra("MINUTA", currTime /1000 + cetrtina * 15 * 60);
                i.putExtra("TEKMA", tekmaId);
                i.putExtra("IGRALKA", Integer.parseInt(igralka[0]));
                i.putExtra("GOL", true);
                TekmaLive.this.startActivity(i);
                //Insted of startActivity I would use startActivityForResult...
            }
        });
Was it helpful?

Solution

You cannot have the method "wait" for the activity to return its result, if that's why you're asking, startActivity() is asynchronous. However, you can achieve the same by "remembering" which button fired the event, i.e. by having a variable (pressedButton) in your activity referencing it.

    final Button goliButton = new Button(this);  // <---
    goliButton.setText("+");
    goliButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent i = new Intent(TekmaLive.this,DodajStrel.class);
            i.putExtra("MINUTA", currTime /1000 + cetrtina * 15 * 60);
            i.putExtra("TEKMA", tekmaId);
            i.putExtra("IGRALKA", Integer.parseInt(igralka[0]));
            i.putExtra("GOL", true);
            TekmaLive.this.pressedButton = goliButton;  // <---
            TekmaLive.this.startActivityForResult(i, YOUR_REQUEST_CODE);  // <---
        }
    });

then just read pressedButton in onActivityResult().

Also, you should use startActivityForResult() instead of startActivity() so that onActivityResult() is called afterwards.

OTHER TIPS

I see that in your code you are using startActivity. You should use startActivityForResult if you want a result back.

onActivityResult is a method that belongs to an Activity or a Fragment. If you call startActivityForResult from an Activity the corresponding onActivityResult of that activity instance will be called, when your child activity calls the finish method.

What you can do in your case is to have your activity implement View.OnClickListener. This way your result will return in the listener.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top