22

I am confused and have no idea on how to use the startActivityResults and setResults to get data from previous activity. I have a view class and a activity class.

Basically in my view class i have this dialog and it will actually start the activity class called the colorActivity class. When user selects yes also it will pass the name of the selected circle to the colorActivity class. At the colorActivity class, users are allowed to enter color code for a particular circle and i would like to pass the color code back to the view class. I have problems passing values from activity back to view using the startActivityForResult and setResult method. Adding on, how to make use of the fetched data afterthat?

my code are as follows

Ontouchevent code from my view class:

            @Override
            public boolean onTouchEvent(MotionEvent event) {

                x = event.getX();
                y = event.getY();


                switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:


                    for (int i = 0; i < circles.size(); i++) {


                        if (circles.get(i).contains(x, y)) {
                            circleID = i;

            Handler handler = new Handler();
                                handler.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        AlertDialog.Builder builder = new Builder(
                                                getContext());
                                        final EditText text = new EditText(getContext());

                                        builder.setTitle("Adding colors to circles").setMessage(
                                                "Proceed to Enter color");
                                        builder.setPositiveButton("Yes",
                                                new DialogInterface.OnClickListener() {

                                                    public void onClick(DialogInterface di,
                                                            int i) {

                                                        Intent intent = new Intent(
                                                                getContext(),
                                                                colorActivity.class);

                                                         intent.putExtra("circlename", circleNameList.get(circleID));


    startActivityForResults(intent, 1); // error incurred here : The method startActivityForResult(Intent, int) is undefined for the type new DialogInterface.OnClickListener(){}
                                                    }

                                                });
                                        builder.setNegativeButton("No",
                                                new DialogInterface.OnClickListener() {

                                                    public void onClick(DialogInterface di,
                                                            int i) {
                                                    }

                                                });

                                        builder.create().show();
                                    }
                                }, 3000);
    break;

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1) { // Please, use a final int instead of hardcoded
                                // int value
            if (resultCode == RESULT_OK) {
                 ccode = (String) data.getExtras().getString("colorcode");
        }

        }
    }

public static String getColorCode() {
        return ccode;
    }

In the colorActivity:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_ecolor);


        circlenametextview = (TextView)findViewById(R.id.circlenametextview);


        String circlename = super.getIntent().getStringExtra("circlename");
          circlenametextview.setText(circlename);//get the circle name


savebutton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                 Intent intent = new Intent(colorActivity.this, ?????);//how to return back to the view class?


               colorcode = colorEditText.getText().toString();// I am able to get value right up till this point
              Intent resultIntent = new Intent();
                   resultIntent.putExtra("colorcode", colorcode );

                   setResult(Activity.RESULT_OK, resultIntent);
                   finish();
            }// onclick

        });
        }
user3306996
  • 421
  • 2
  • 4
  • 15
  • Where you say: "error incurred here :"... in the OnTouchEvent, is still giving you that error? Or the Intent is launched correctly (the Activity colorActivity is opened)? – donnadulcinea Mar 21 '14 at 08:34
  • @donnadulcinea the error says The method startActivityForResult(Intent, int) is undefined for the type new DialogInterface.OnClickListener(){}... I couldnt run the program as there is this error.. – user3306996 Mar 21 '14 at 08:38
  • First, try replacing getContext() (which you don't report in your code) with getApplicationContext() in your call. Then if it work I'll help you to get your results back. – donnadulcinea Mar 21 '14 at 08:44
  • @donnadulcinea i have tried replacing the getContext() with getApplicationContext() but i got an error as well. The error says "The method getApplicationContext() is undefined for the type new DialogInterface.OnClickListener(){}" – user3306996 Mar 21 '14 at 08:46
  • @donnadulcinea if i make use of startActivity(intent, colorActivity can be launched successfully. – user3306996 Mar 21 '14 at 08:49
  • No, you need to call startActivityForResult(intent, int), because you will wait for some result. Take a look what J Ajendra said. You put one more s in the method. – donnadulcinea Mar 21 '14 at 08:58

3 Answers3

54

After correcting the other code so that you can run the program, you can retrieve parameters back from your activity colorActivity in this way:

Step1: return some value from colorActivity

Intent resultIntent = new Intent();
resultIntent.putExtra("NAME OF THE PARAMETER", valueOfParameter);
...
setResult(Activity.RESULT_OK, resultIntent);
finish();

Step 2: collect data from the Main Activity

Overriding @onActivityResult(...).

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) { // Please, use a final int instead of hardcoded int value
    if (resultCode == RESULT_OK) {
        String value = (String) data.getExtras().getString("NAME OF THE PARAMETER");

References

Community
  • 1
  • 1
donnadulcinea
  • 1,854
  • 2
  • 25
  • 37
  • I have tried out the codes in my colorActivity but it seems like the value didnt get passed through using setResult(Activity.RESULT_OK, resultIntent);. After debugging the value i got from onActivityResult is null. i have updated the codes above, – user3306996 Mar 21 '14 at 10:49
  • Take care this few things: (i) onActivityResult must be overridden in the MainActivity, (ii) requestCode must be the same in request and answer (in your case =1), (iii) replace "NAME OF THE PARAMETER" everywhere with your value, es. "circlename". Let me know. – donnadulcinea Mar 21 '14 at 11:03
  • i am still getting null value :( I can use a get method to get the value so that i can use it in my view class right? – user3306996 Mar 21 '14 at 11:32
  • I am trying the code I wrote for you and it works. Can you try with some of the example I linked, then substitute your code to pass shape information? At this point should be easier. – donnadulcinea Mar 21 '14 at 14:39
  • i find the second link useful and i tries to substitute and match to my project but it dont work. The code i used is somehow similar to what the second link has. I even tried shifting the onActivityResult into my view class it dont work either. – user3306996 Mar 21 '14 at 15:58
  • 1
    Well, this is weird. But I also have experience with something that seems to work for everybody and not for me (see my questions). If you want to share your full project pasting it somewhere I can give it a look and help you. – donnadulcinea Mar 22 '14 at 04:00
  • thanks you very much, this is works for me, see my complete gist here for future reader: https://gist.github.com/mochadwi/032bbc39e6341ecff1deb3a2545e7c0a – mochadwi Mar 20 '20 at 18:50
3

STARTACTIVITYFORRESULT IS NOW DEPRECATED

Alternative to it and recommended solution is to use Activity Result API

You can use this code, written in Kotlin language:

  1. Create ResultLauncher:

     private var resultLauncher =
     registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
         if (result.resultCode == Activity.RESULT_OK) {
             val data: Intent? = result.data
             if (null != data && data.getBooleanExtra("REFRESH_PAGE", false)) {
                 //do your code here
             }
         }
     }
    
  2. start Activity by using above result launcher:

         val intent = Intent(this, XYZActivity::class.java)
         resultLauncher.launch(intent)
    
  3. Return result from XYZActivity by

         val resultIntent = Intent()
         resultIntent.putExtra("REFRESH_PAGE", true)
         setResult(Activity.RESULT_OK, resultIntent)
         finish()
    
Kishan Solanki
  • 13,761
  • 4
  • 85
  • 82
1

try using

ActivityName.this.startActivityForResult(intent,int)

Oh, and 1 small thing, in your code you have used

startActivityForResults(intent,int) ..replace that with

startActivityForResult(intent,int)

J.Ajendra
  • 345
  • 1
  • 10