25

I'm developing an Android Application in which I have

I've two classes class A and Class B.

In class A, I tried the code Snippets like below,

How do I call a method in another Activity from Activity?

public class FirstActivity extends Activity {  

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main2);
    }      

    public void method() {
        // some code
    }  
}

public class SecondActivity extends Activity {  

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
         setContentView(R.layout.main2);
    
        FirstActivity fact = new FIrstActivity();
    
        fact.method();
    }
}
Zoe
  • 27,060
  • 21
  • 118
  • 148
user2932841
  • 351
  • 2
  • 4
  • 4
  • You definitely need to read this - http://developer.android.com/guide/components/fundamentals.html – Varun Oct 29 '13 at 18:43

6 Answers6

19

The startActivityForResult pattern is much better suited for what you're trying to achieve : http://developer.android.com/reference/android/app/Activity.html#StartingActivities

Try below code

public class MainActivity extends Activity {  

    Button button1;  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
        textView1=(TextView)findViewById(R.id.textView1);  
        button1=(Button)findViewById(R.id.button1);  
        button1.setOnClickListener(new OnClickListener() {  
            @Override  
            public void onClick(View arg0) {  
                Intent intent=new Intent(MainActivity.this,SecondActivity.class);  
                startActivityForResult(intent, 2);// Activity is started with requestCode 2  
            }  
        });  
    }  
 // Call Back method  to get the Message form other Activity  
    @Override  
       protected void onActivityResult(int requestCode, int resultCode, Intent data)  
       {  
                 super.onActivityResult(requestCode, resultCode, data);  
                  // check if the request code is same as what is passed  here it is 2  
                   if(requestCode==2)  
                         {  
                          //do the things u wanted 
                         }  
     }  

} 

SecondActivity.class

public class SecondActivity extends Activity {  

    Button button1;  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_second);  

            button1=(Button)findViewById(R.id.button1);  
            button1.setOnClickListener(new OnClickListener() {  
                @Override  
                public void onClick(View arg0) {  
                    String message="hello ";  
                    Intent intent=new Intent();  
                    intent.putExtra("MESSAGE",message);  
                    setResult(2,intent);  
                    finish();//finishing activity  
                }  
            });  
    }  

}  

Let me know if it helped...

Rissmon Suresh
  • 13,173
  • 5
  • 29
  • 38
13

You should not create an instance of the activity class. It is wrong. Activity has ui and lifecycle and activity is started by startActivity(intent)

You can use startActivityForResult or you can pass the values from one activity to another using intents and do what is required. But it depends on what you intend to do in the method.

Raghunandan
  • 132,755
  • 26
  • 225
  • 256
  • 15
    so how to call a method form another activity. – user2932841 Oct 29 '13 at 18:45
  • @user2932841 you can't what is that you are trying to do in that method? – Raghunandan Oct 29 '13 at 18:46
  • @user2932841 you seem to have asked this question again. seems like a duplicate. But still what do you want to do in the method can you specify that? – Raghunandan Oct 29 '13 at 18:55
  • You recommend, or at least mention, the use of Intents. On the other (duplicate) question the most popular answer recommends using a callback method in the Activity. I wonder if you'd be so kind as to explain what the advantages and disadvantages of using Intents vs. callbacks can be? – RenniePet Dec 28 '15 at 15:21
  • @RenniePet startActivityForResult can be used if you are waiting reults from one activity. If you see the other answer its a non activity class. I do admit i made a mistake by marking it a duplicate cause that is from a non-activity class. I have a re-opened the question. – Raghunandan Dec 28 '15 at 15:51
  • Thanks for reply. My comment was because I've become very unsure of whether a callback method is an acceptable way to call a method in an Activity. Using an Intent is obviously the "correct" way - Google describes how to do it. And using a callback somehow seems "too easy", like it's "cheating". But is is OK, or are there situations where the use of a callback will cause problems, for example due to there being something wrong with the Activity's context, or something? – RenniePet Dec 28 '15 at 22:45
  • 2
    Startactivity for result should be used if you need results from another activity. You can use callbacks when you wants results for asynctask or worker fragment – Raghunandan Dec 29 '15 at 04:04
  • `startActivityForResult` deprecated long long time ago – ekashking Dec 15 '21 at 16:48
6

If you need to call the same method from both Activities why not then use a third object?

public class FirstActivity extends Activity 
{  

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main2);

    }      

    // Utility.method() used somewhere in FirstActivity
}

public class Utility {

    public static void method()
    {

    }  

}

public class SecondActivity extends Activity 
{  

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main2);

        Utility.method();

    }
}

Of course making it static depends on the use case.

cYrixmorten
  • 7,110
  • 3
  • 25
  • 33
-1
public class ActivityB extends AppCompatActivity {

static Context mContext;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_b);

    try {

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            String texto = bundle.getString("message");
            if (texto != null) {
              //code....
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void launch(String message) {
        Intent intent = new Intent(mContext, ActivityB.class);
        intent.putExtra("message", message);
        mContext.startActivity(intent);
    }
}

In ActivityA or Service.

public class Service extends Service{

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {    

        String text = "Value to send";
        ActivityB.launch(text);
        Log.d(TAG, text);
    }
}
-1

Simple, use static.

In activity you have the method you want to call:

private static String name = "Robert";

...

public static String getData() {
    return name;
}

And in your activity where you make the call:

private static String name;

...

name = SplashActivity.getData();
Robert Pal
  • 714
  • 1
  • 7
  • 15
-3

Declare a SecondActivity variable in FirstActivity

Like this

public class FirstActivity extends Activity {  

SecondActivity secactivity;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main2);
  }      

  public void method() {
    // some code

  secactivity.call_method();// 'Method' is Name of the any one method in SecondActivity

  }  
}  

Using this format you can call any method from one activity to another.

  • 1
    Please this answer should be updated, this solution isn't correct, you should always instanciate the SecondActivity object and that will not work ! – Rodrigo Jun 11 '17 at 18:53