How to Call a Function from Other Activity Android

how to call a function from other activity android

If MapsActivity is expecting a result from OtherActivity, you're better off with Getting Result From an Activity. Simply call OtherActivity via startActivityForResult() (instead of startActivity()):

static final int MAP_REQUEST = 1;  // your request code
...
private void callOtherActivity() {
Intent intent = new Intent(this, OtherActivity.class)
startActivityForResult(intent, MAP_REQUEST);
}

Then in your MapsActivity, do this:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MAP_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
updateMap();
}
}
}

Calling function from another activity

Add the static keyword to your shared methods

public static void createTable()

Then use:

Data.createTable();

somewhere in another Class / Fragment / Activity.

I do so and it works.

Well, my "Data" is a normal Class, not an Activity, but I also have an Activity with shared methods in the very same way.

This is my dbTableCreate method:

// Create the database table if it doesn't exist
protected final static void dbTableCreate(final Context ctx)
{
SQLiteDatabase db = null;
try
{
db = ctx.openOrCreateDatabase(DB_NAME, Context.MODE_PRIVATE, null);
db.execSQL
(
"CREATE TABLE IF NOT EXISTS " + DB_TABLE +
" (date DATETIME PRIMARY KEY NOT NULL DEFAULT (CURRENT_DATE), " +
"score INTEGER DEFAULT (null));"
);
}
catch (final SQLiteException se)
{
System.out.println
(
ctx.getClass().getSimpleName() + "\n" +
"Could not create the database"
);
se.printStackTrace();
}
finally
{
db.close();
}
}

And I call it like:

Context ctx = getApplicationContext();
CLS_DB.dbTableCreate(ctx);

The main difference between my class and yours is that mine is declared as

public final class CLS_DB
{
/* ----------------------------- Constants ------------------------------ */

private final static String DB_NAME = "pat.db";
private final static String DB_TABLE = "tests";

/* ------------------------------ Methods ------------------------------- */

And not as an Activity.

I'm not initializing the Class, and it has no constructor.

It's just a bin of shared (and not, for doing operations not seen anywhere else in my code) methods.

Android Kotlin call a function in other activity

I would rather extract all logic to a different helper or utility class. It's a big mistake to have it within an activity if you're gonna reuse it. A pretty neat solution could be to have a ConnectivityUtils utility class like the famous iosched project has, just passing the application context to it:

/**
* Utility methods for dealing with connectivity
*/
object ConnectivityUtils {
fun isConnected(context: Context): Boolean {
val connectivityManager = context.applicationContext.getSystemService(
Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val activeNetworkInfo = connectivityManager.activeNetworkInfo
return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting
}
}

Then, you just need to invoke it within any activity like this:

ConnectivityUtils.isConnected(this)

Call function from different activity

Don't use a link to the activity inside another activity. It can lead to memory leak.

Regarding your question, you can use Broadcast receivers to communicate between activities or use a Service which will communicate with your BLE device

Simple usage of Broadcast Receiver:

class YourActivity extends Activity {
private BroadcastReceiver mMyReceiver;

protected void onCreate(Bundle data) {
...
mMyReceiver = new MyReceiver();
}

public void onStart() {
registerReceiver(mMyReceiver, new IntentFilter("your action"));
}

public void onStop() {
unregisterReceiver(mMyReceiver);
}

public void onDestroy() {
mMyReceiver = null;
}

// Inner class has a link to YourActivity instance
private class MyReceiver extends BroadcastReceiver {
public void onReceive(Intent intent) {
// procces messages here
}
}
}

// Calling:
context.sendBroadcast(new Intent("your action"));

How can i call a function in activity from another activity in android?

Make the method as public static which you are going to access from another activity. then
call it as activity1.sendsms();

This is the way . if you post the code will advice you better way... hope this will help you .

Hi use the below code. the thing is you need to use Context.

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.widget.Toast;

public class SendingSms extends Activity {

static Context context;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
context=this;

}

public static void sendSMS(String telNo, String mesaj)
{
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";

PendingIntent sentPI = PendingIntent.getBroadcast(context, 0, new Intent(SENT), 0);

PendingIntent deliveredPI = PendingIntent.getBroadcast(context, 0, new Intent(DELIVERED), 0);

context.registerReceiver(new BroadcastReceiver() {

@Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
switch(getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(context, "SMS Gönderildi",Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(context, "Generic failure",Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(context, "No service",Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(context, "Null PDU",Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(context, "Radio off",Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SENT));


context. registerReceiver(new BroadcastReceiver(){
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(context, "SMS iletildi",
Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(context, "SMS iletilemedi",
Toast.LENGTH_SHORT).show();
break;
}
}

}, new IntentFilter(DELIVERED));

SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(telNo, null, mesaj, sentPI, deliveredPI);

Toast.makeText(context, telNo.toString() + " - " + mesaj.toString(), Toast.LENGTH_LONG).show();
}

}

How to call a non-static method from one Activity to another activity

class A extends Activity{
static A instance;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
instance = this;
}

public static A getInstance() {
return instance;
}
....
public void clear(){}

}

and in class B:

class B extends Activity {
public void clearData(){
A a = A.getInstance();
a.clear();
}
}


Related Topics



Leave a reply



Submit