Call a method of an Activity from another Activity - java

I have two Activities A and B. B has a method searchDevices. I want to access that method from A 's onCreate method. How can I do it with Intent?
I tried this :
public void onCreate(Bundle savedInstanceState)
{
try{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MY_UUID= UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
//Function enbling Bluetooth
enableBluetooth();
///Function to initialize components
init();
//Calling AvailableDevices class's method searchDevice to get AvailableDevices
Intent intent=new Intent(this,AvailableDevices.class);
int x=10;
intent.putExtra("A", x);
}catch(Exception e){Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();}
}

You can also create a base activity that both ActivityA and ActivityB extends and put searchDevices() method in it.
For ex:
public class BaseActivity extends Activity{
public void searchDevices(){
}
}
public class ActivityB extends BaseActivity{
onCreate..
{
...
searchDevices();
}
}
public class ActivityA extends BaseActivity{
onCreate..
{
...
searchDevices();
}
}

if ActivityA is in a class called class1 make a method in class1 like this
public static void method1(){
}
then in activity 2 call the method by doing this ActivityA.method1()

Why don't use StartActivityForResult.
As per my understanding You can start AvailableDevices Activity for result with Intent having extra data and call searchDevice to get AvailableDevices and return the result to calling Activity.
[Edit]
In Class A
//Calling AvailableDevices class's method searchDevice to get AvailableDevices
Intent intent=new Intent(this,AvailableDevices.class);
int x=10;
intent.putExtra("A", x);
startActivityForResult(intent , searchDevicesRequestCode); //searchDevicesRequestCode = 100
Also override onActivityResult()
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == searchDevicesRequestCode) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// Manipulate searchDevicesResult from Intent data
}
}
}
In Class B
#override
onCreate()
{
//call searchDevices()
String result = searchDevices(); // save result to send in any form
// Create intent to deliver some kind of result data
Intent intentResult = new Intent("RESULT_ACTION");
intentResult.putExtra("key",result);
setResult(Activity.RESULT_OK, intentResult);
finish();
}

Related

Keep changes made by BroadcastReceiver

I'm stuck at this point:
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
String number = bundle.getString("Time");
GameTime.setText("" +number + " hours");
}
};
In another Activity, when a Button is pressed, the MainActivity get's an int.
Whenever I open the Activity, I cannot see the GameTime TextView with the number variable in it.
I know that the OnReceive method works, beacause I had put a toast in it, and I could see the toast after sending the int from the other Activity.
How can I keep the changes made to the TextView while changing Activities?
Thank you.
One way:
Define an interface in your activity & Implement the interface inside your activity and pass its reference to the other class and call that reference whenever you need.
Example:
a) Create an interface
public interface MyBroadcastListener{
public void doSomething(String result);
}
b) Initialize BroadCastReceiver
public class TestNotifAlarm extends BroadcastReceiver {
private MyBroadcastListener listener;
#Override
public void onReceive(Context context, Intent intent) {
listener = (MyBroadcastListener)context;
listener.doSomething("Some Result");
}
}
c) Implement the interface in Activity
public YourActivity extends AppCompatActivity implements MyBroadcastListener{
// Your Activity code
public void updateTheTextView(String t) {
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(t);
}
#Override
public void doSomething(String result){
updateTheTextView(result); // Calling method from Interface
}
}
Another Way :
a) Put a Receiver inside your Activity class
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
textView.setText(intent.getStringExtra("extra"));
}
};
b) Register BroadCastReceiver
registerReceiver(broadcastReceiver , new IntentFilter("trigger_broadcust"));
c) Call sendBroadcast
Intent intent = new Intent("trigger_broadcust");
intent.putStringExtra("extra", "data");
sendBroadcast(intent);

Call activity A method from Activity B Android

I'm a new to java and android. I was working on my own app but I'm having a problem in passing a method from Activity A to Activity B.
Here is what I did :
ActivityA has Demo() method.
public class ActivityA extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
protected void demo() {
// Do something
}
}
I created the below class to access the method of ActivityA to ActivityB:
public class External {
private ActivityA activitya;
private static External instance = null;
public External(ActivityA activitya) {
this.activitya = activitya;
}
static public External getInstance(ActivityA activitya) {
if (instance == null) {
instance = new MyntraExternal(activitya);
return instance;
} else {
return instance;
}
}
}
Now how can I proceed further? I'm having lots of problem in getting the method which is in ActivityA from ActivityB.
Please anybody help.
Edit :
ActivityB is my launcher class and I want some access from ActivityA's method in ActivityB. What to do ?
Since you are new to Android, I will tell you it's a bad practice call methods from Activity A to B or vice versa, you can pass parameters from one activity to another using intents and bundles and if you need to pass parameters from the second activity to the first you need to use the override method onActivityResults
Here are some usefull link about passing parameters from one activity to another:
https://www.dev2qa.com/passing-data-between-activities-android-tutorial/
In this link you can see a example of how things work.
Hope it helps.
--EDIT (if you need to call a function from B to A in case you want to change something in A upon creation this is the best and simplest way to do it):
In Activity B:
Intent intent = new Intent(this, ActivityA.class);
intent.putExtra("Work","doJump");
startActivity(intent);
In Activity A:
onCreate:
String extra = getIntent().getStringExtra("Work");
if(extra != null && extra.equals("doJump")){
jump();
}
make that method public and static and then access it using class name. e.g. In your 2nd activity, use ActivityB.demo()
Try using startActivityForResult
To start activity B from activity A
startActivityForResult(intent, SOME_CODE)
And to be called back on result you will need to add the following code the also in activity A
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when(code){
SOME_CODE -> if (resultCode == Activity.RESULT_OK) doSomething()
}
}
To tell Activity A to call the method, in activity B you can say:
setResult(Activity.RESULT_OK)
finish()
After B is finished, onActivityResult in A will be executed
To go back to A without executing the "doSomething()" method,
setResult(Activity.RESULT_CANCELED)
finish()
Please try this way
public class ActivityA extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void demo() {
// Do something
}
}
public class ActivityB extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityA activityA = new ActivityA(); // create object
activityA.demo(); //
}
}

Call method of new activity from MainActivity

There are two Activities..
1. Open SecondActivity from MainActivity
2. When event comes into MainActivity, call testMethod of SecondActivity
But how to do call this testMethod?
public class MainActivity extends Activity implements someListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Launch SecondActivity here!!
Intent intent = new Intent();
intent.setClass(MainActivity.this, SecondActivity.class);
startActivityForResult(intent, ID_PlayerActivity);
}
//trigger by JNI, it's in the other thread, not main thread.
void onEventCome() {
//How to call testMethod() in SecondActivity?
}
}
public class SecondActivity extends Activity {
void testMethod() {
//execute something...
}
}
If you open the SecondActivity, your MainActivity becomes inactive. I don't believe it is a good idea to call some activity method from other inactive/stopped activity.
I suggest to use observer pattern. Create a global long-lived object like EventProducer and register all activities as observer. So your EventProducer can inform all Activities about new event.
Example:
public class SecondActivity extends Activity implements MyEventListener {
#Override
public void onResume(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EventProducer.instance().register(this);
}
#Override
public void onPause(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EventProducer.instance().unregister(this);
}
void testMethod(){
//just doit
}
#Override
void onMyEventCome() {
testMethod();
}
}
First you need an event aware listener that will capture such an event happening. Your class seems ill equipped to do so.
Since you have a valid question, here goes:
void onEventCome() {
SecondActivity secondActivity = new SecondActivity();
secondActivity.testMethod();
}
There are many ways.
For eg:
Create the method as static and use class name and call it.
public static void onEventCome() {
}
In MainActivity:
MainActivity.onEventCome();
This is one method. Another method is create an object for MainActivity.
public void onEventCome() {
}
MainActivity main;
main = new MainActivity();
main.onEventCome();
You don't have a content view for your second activity. If you don't need to see the operation happen, you could remove your
Intent intent = new Intent();
intent.setClass(MainActivity.this, SecondActivity.class);
startActivityForResult(intent, ID_PlayerActivity);
remove extends Activity in SecondActivity and add a constructor public SecondActivity(Context context) and invoke the test method from your first activity like #Dragan example:
void onEventCome() {
SecondActivity secondActivity = new SecondActivity(MainActivity.this);
secondActivity.testMethod();
}

Refreshing parent activity from child?

guys, I'm pretty new to java android programming (that's the first app I'm making) and I have this question:
How can i refresh my Main Activity from another activity, which is called from the Main one?
I would also appreciate if you give me some examples, because I'm still not very orientated...
You can use startActivityForResult() for that purpose, instead of context.startActivity() call context.startActivityForResult() and then set result in launched activity before finishing it.
Here is the documentation for Context.startActivityForResult()
Sample code:
// Activity A
public class ActivityA extends Activity {
private static final int REQUEST_CODE_ACTIVITY_B_FOR_RESULT = 1; // or other int value
// sample code which starts Activity B
private void onSomeButtonClick() {
Intent intent = new Intent(this, ActivityB.class);
startActivityForResult(intent, REQUEST_CODE_ACTIVITY_B_FOR_RESULT);
}
// this method will be called when started activity finished
// and returned some result of its work
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent resultData) {
super.onActivityResult(requestCode, resultCode, resultData);
if (requestCode == REQUEST_CODE_ACTIVITY_B_FOR_RESULT) {
if (resultCode == RESULT_OK) {
// handle result ok and resultData here
} else {
// handle result canceled or other resultCode and its resultData here
}
}
}
}
// Activity B
public class ActivityB extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setResult(RESULT_CANCELED); // by default result of starting activity is negative
}
// some code which doing some action and setting result as ok
private void doSomething() {
Intent resultData = new Intent();
resultData.putExtra("SOME_EXTRA", "did it"); // or other result data
setResult(RESULT_OK, resultData);
finish(); // finishing this activity, result code and result data will be accessible in previous activity
}
}
How to call main activity from the sub activity. Use an interface.
1. Creata a public interface in the sub-activity
public class MapSettings extends DialogFragment implements
OnCheckedChangeListener {
public interface BestRidesSettingsDialogListener {
void onMapSettingsChange(int mapType);
}
2. Implement the interface in the main activity note right click on errors and select add imports add reference add unimplemented methods.
public class KmlReader extends ActionBarActivity implements
BestRidesSettingsDialogListener {
3. when the sub activity starts in the sub activity cast getActivity to the public interface
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// the activity may be null if this is called without implementing the
// BestRidesSettingsDialogListener (The settings object saves the
// setting so the
// call back may not be needed.
activity = (BestRidesSettingsDialogListener) getActivity();
4. Then in the sub activity when a button is clicked or some event happens call through to the interface method.
#Override
public void onCheckedChanged(RadioGroup rg, int checkId) {
// TODO Auto-generated method stub
int mapType = 0;
switch (checkId) {
case R.id.RDORoad:
mapType = GoogleMap.MAP_TYPE_NORMAL;
break;
case R.id.RDOHybrid:
mapType = GoogleMap.MAP_TYPE_HYBRID;
break;
case R.id.RDOSatelite:
mapType = GoogleMap.MAP_TYPE_SATELLITE;
break;
case R.id.RDOTerrain:
mapType = GoogleMap.MAP_TYPE_TERRAIN;
break;
}
// run the activity onchange
// if the activity is null there is no listener to take action on the
// settings
if (activity != null) {
activity.onMapSettingsChange(mapType);
}
5. if you've filled in the unimplemented methods stubs in your main activity your executing code directly in the main activity from the sub activity.
#Override
public void onMapSettingsChange(int mapType) {
if (mMap != null) {
mMap.setMapType(mapType);
}
}
sidebar for comments: The interface has always been my favorite part of java. You might call it a listener or a call back. Just right click on the errors and select add reference, add unimplemented methods there really are not too many keystrokes to do this. The interface is perhaps the easiest way to coordinate a team effort on making the next big thing.

Android - Navigate to previous screen

I have a problem as explained here. I have a Class A, ClassB. Both have Intents to navigate to Class C. Now, I want to know from Which class i have navigated to Class C so that i will navigate to previous screen either A or B. Calling finish() in Class C doesnt help me because i need to update the data in Class A and Class B differently. Can anybody please help me. How to use Intent here? Can i know from which class i have to navigated to Class C?
you should use startActivityForResult and override the onActivityResult callback. This way you can safetly update your data without know from wich activity you came from.
public class A extends Activity {
private final static int REQUEST_CODE= 1000;
public void onCreate(BUndle b) {
...
Intent intent = new Intent(this, C.class);
startActivityForResult(intent, REQUEST_CODE);
}
#override
void onActivityResult(int requestCode, int resultCode, Intent data) {
// here through data you will receive new data
}
}
public class C extends Activity {
public void onCreate(BUndle b) {
// modify same data
Intent intent = new Intent();
// pute data inside intent
setResult(Activity.RESULT_OK, intent);
finish();
}
}
in your intents in class A and B, put a parameter like a boolean "isclassA" and make tests on it to know.
in intent of classe A :
intent.putExtra("isfromclassA",true);
in intent of class B :
intent.putExtra("isfromclassA",false);
therefor in your class C :
boolean isfromclassA = intent.getBoolExtra("isfromclassA");

Categories