Calling an internal class method from outside

Asked

Viewed 156 times

2

I have a class B and in that class I need to call a method, getSomething(type, option), which is defined in a class A which is a class which extends AsyncTask and which is within Class C.

My Class C is defined as follows::

public class C extends BaseActivity{
(...)
 public class A extends AsyncTask<String, Void, String> {
 (...)
  public String doInBackground(String... params) {
  (...)
  }
  public String getSomething(String type, String option){
  (...)
  }
  protected void onPreExecute() {
  (...)
  }
  protected void onPostExecute(String result){
  (...)
  }
(...)
}

What I’m trying to do is within the B class, within a method put this call to the getSomething method():

String sentence = new C().new A().getSomething(type,option);

also tried to:

new C().new A().execute();

I can’t call the method because it makes me an exception

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference

whenever the call to the getSomething method is made(...).

Can anyone help, to know how I can call the procedure from another class?

2 answers

0


To instantiate an inner class outside the class where it was declared, you first need to create an external class instance and use the syntax objectoExterno.new ClasseInterna() to create the internal object.

ClasseExterna objectoExterno = new ClasseExterna();
ClasseExterna.ClasseInterna objectoInterno = objectoExterno.new ClasseInterna();

In your case, as the class C is a Activity, this cannot be done because a Activity shall not be instantiated through the new.

The solution is to transform the inner class into a normal class and to instantiate it in the usual way in each of the classes.

  • 1

    Thank you. I’m clear.

0

In class 'A', create the instance:

public static A a;

Now in your B class, call:

A.a.getSomething();

I didn’t test if it works, but it should work!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.