user3306996
user3306996

Reputation: 421

Android: startActivityForResult & setResult for a view class and an activity class

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

        });
        }

Upvotes: 22

Views: 61674

Answers (3)

Kishan Solanki
Kishan Solanki

Reputation: 14636

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()
    

Upvotes: 4

donnadulcinea
donnadulcinea

Reputation: 1874

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

Upvotes: 54

J.Ajendra
J.Ajendra

Reputation: 345

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)

Upvotes: 1

Related Questions