-1

I have a method name checkForUpdate() in UpdateActivity.java. It looks like this:

@NonNull
@SuppressWarnings("deprecation")
protected String checkForUpdate(int curVersionCode) {
  HttpClient httpclient = new DefaultHttpClient();
  ... 
}

I am trying to call it from anotherActivity. So I'm trying to use code like this:

private void callFromAnotherActivity() {
  UpdateActivity updateApp = new UpdateActivity();
  String result = updateApp.checkForUpdate(...);
}

so when I type updateApp. then a list of the methods of UpdateActivity.java appears but there is no checkForUpdate() method. Why?

ישו אוהב אותך
  • 28,609
  • 11
  • 78
  • 96
Fechang Fuchang
  • 131
  • 1
  • 1
  • 11

2 Answers2

1

so when I type updateApp. then a list of the methods of UpdateActivity.java appears but there is no checkForUpdate() method. Why?

This is because your method is not public and probably you haven't import the UpdateActivity.

Please be noted that you can't create an Activity by calling the following:

UpdateActivity updateApp = new UpdateActivity();

You need to use something like this:

// context is your activity context.
Intent updateApp = new Intent(context, UpdateActivity.class);
context.startActivity(updateApp);

My suggestion:

You need to move the checkForUpdate method from UpdateActivity and make it as an util. So, other activity using the method won't be dependent and coupled with UpdateActivity. Localize the method to an utility class something like this:

public class UpdateUtil {

  ...

  @NonNull
  @SuppressWarnings("deprecation")
  public static String checkForUpdate(int curVersionCode) {

    HttpClient httpclient = new DefaultHttpClient();
    ... 

  }
}

and then use the method with:

UpdateUtil.checkForUpdate(1);

If you can't move the code (e.g, you don't have ownership of the code), you can do these things:

  1. Make the checkForUpdate as static method
  2. Use EventBus to tell the UpdateActivity to do the update.
ישו אוהב אותך
  • 28,609
  • 11
  • 78
  • 96
0

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) Check here : call a method in another Activity

Quang Doan
  • 632
  • 4
  • 12