Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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          });         } 
like image 949
user3306996 Avatar asked Mar 21 '14 08:03

user3306996


People also ask

What is the use of startActivityForResult in Android?

By the help of android startActivityForResult() method, we can send information from one activity to another and vice-versa. The android startActivityForResult method, requires a result from the second activity (activity to be invoked).

Can I still use startActivityForResult?

It has deprecated startActivityForResult in favour of registerForActivityResult . It was one of the first fundamentals that any Android developer has learned, and the backbone of Android's way of communicating between two components.

What is request code startActivityForResult?

The request code is any int value. The request code identifies the return result when the result arrives. ( You can call startActivityForResult more than once before you get any results. When results arrive, you use the request code to distinguish one result from another.

What is the purpose of startActivityForResult?

startActivityForResult() allows you to start activity and get some data back. Imagine that you have some file picker activity. You can start it and when user chooses the file, the result is given back to the original activity.


2 Answers

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

  • http://developer.android.com/training/basics/intents/result.html
  • How to manage `startActivityForResult` on Android?
  • http://steveliles.github.io/returning_a_result_from_an_android_activity.html
like image 112
donnadulcinea Avatar answered Oct 21 '22 10:10

donnadulcinea


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() 
like image 40
Kishan Solanki Avatar answered Oct 21 '22 10:10

Kishan Solanki