Search code examples
androidandroid-intentandroid-activityonactivityresult

how to Managing activites for result


I just have 2 activites.

I want to go from activity1 to activity2 , do some jobs , then return result from activty2 to activity1

here is my code in activity1 :

Button otherkey = (Button) findViewById(R.id.button2);
        otherkey.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                Intent intent3 = new Intent(EncryptionActivity.this , FileExplore.class);
                startActivityForResult(intent3, 123);
                onActivityResult(123, Activity.RESULT_OK , intent3) ;//i think heres my problem.
            }});

and in the class of activity1 i have this method :

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        System.out.println("req" + requestCode + "\nres code :"+resultCode);
        if (requestCode == 123) {
            if(resultCode == 0){
                String result=data.getStringExtra("mydata");
                System.out.println(result);
            }
            if (resultCode == RESULT_CANCELED) {
                //Write your code if there's no result
                System.out.println("ddd");
            }
        }
    }//onActivityResult

and the code in activity2 is :

                        activity2.this.finish();
                        Intent enca = new Intent();
                        enca.putExtra("mydata", "hello");
                        setResult(RESULT_OK,enca);

how can i fix this ?


Solution

  • You have no need to call onActivityResult method but just simply override it. And will be called automatically when back to your activity. Check out this link to understand more

    public class TestActtiviy extends Activity{
    
        Button width, height, calc;
        TextView area;
    
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
    
         //your code
        }
    
    
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            // TODO Auto-generated method stub
            super.onActivityResult(requestCode, resultCode, data);
            //your code here
             if (resultCode == 0) {}
    
        }
    
    }