user1225844
user1225844

Reputation:

how to call a function in an activity from main activity

public class Activity1 extends Activity {

billreminder br;//billreminder is a function in activity2

public void onCreate(Bundle savedInstanceState);



setContentView(R.layout.main);

br.read(c);//c is a string

}

how do we call read function.

Upvotes: 0

Views: 472

Answers (3)

Dhruv Gairola
Dhruv Gairola

Reputation: 9182

There are a couple of ways you can do this. You can make the function in activity2 a static function. You can then call it like so: Activity2.read(c)

Another way, is to pass an intent from Activity1 to Activity2 as follows:

in activity1:

Intent intent = new Intent(Activity1.this, Activity2.class);
intent.putExtra("c", c);
//this will put a callback in the onActivityResult method for the Activity1 class
startActivityForResult(intent, requestCode);//requestCode is an int

in activity2 inside its onCreate method:

Bundle extras = getIntent().getExtras();

if(extras != null) {
    c = extras.getString("c");
    if(c != null && !"".equals(c)) {
        read(c);
    }
    setResult(resultCode);//resultCode is an int
}

in activity1 again1:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   super.onActivityResult(requestCode, resultCode, data);
   //detect resultCode or requestCode, and do whatever you want
   ....
}

Avoid subclassing the Application class. From the android docs:

There is normally no need to subclass Application. In most situation, static singletons can provide the same functionality in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), the function to retrieve it can be given a Context which internally uses Context.getApplicationContext() when first constructing the singleton.

Also, I think you are confused. You need to call a method on an object.

billreminder br;//billreminder is a function in activity2

is wrong. I think you meant that br is an object.

Upvotes: 0

Dharmendra
Dharmendra

Reputation: 33996

Make a function static so that you can use it from any activity.

If your method uses a context then pass the context as a parameter.

But if you want to use the elements of second activity in which you have write a method then you should create a Application class and you have to move this method to application class.

Upvotes: 0

abbas.aniefa
abbas.aniefa

Reputation: 2905

Create a Class and Extend Application , move your read method to Application class.

Form your Activity call getApplicationContext() to get the Application object to call read method.

Example:

ApplicationCalssName bmodel = (ApplicationCalssName) getApplicationContext();
bmodel.read(c);

Upvotes: 1

Related Questions