Java how to use activity methods in another class

For example, I have an activity class. In this class, I have some variables, and I would like to use them in another class. This is the code:

public class SearchView {
    private MenuActivity menuActivity;

    public SearchView() {
        menuActivity = new MenuActivity();
        menuActivity.searchButton = (ImageView) menuActivity.findViewById(R.id.searchButton);
    }
}

The last line gives me NullPointerException. I know that I need to initialize it, but how can I initialize an activity?

+4
source share
3 answers
public class SearchView {
    private MenuActivity menuActivity;

    public SearchView(Activity activityRef) {
        MenuActivity.searchButton = (ImageView) activityRef.findViewById(R.id.searchButton);
    }
}

And declare searchButton as public static in activity.

public class MenuActivity extends Activity {
    public static Button searchButton;

    @Override
    protected void onCreate() {
        SearchView searchView = new SearchView(this);
    }
}

Hope this helps you. let me know as soon as you are done.

+1
source

You have other options ...

The first:

Create a getter to get the values ​​from the classes:

public MenuActivity getMenuActivityVar(){
    return this.MenuActivity;
}

From another action, using this method, do the following:

//Other activity or class
//Declare a new var as your class
SearchView sView = new SearchView();

MenuActivity nMenu = sView.getMenuActivityVar();

Second:

, vars , , .

public static class SearchView {{
    public static MenuActivity menuActivity;
    .
    .

}

var, :

//This call it do it from other activity
MyNewVar = SearchView.MenuActivity;

:

public class SearchView {
    public MenuActivity menuActivity;
}

, :

SearchView sView = new SearchView();
//In this moment your var are null.

, var , , var, :

MenuActivity MyNewMenu = sView.menuActivity;

, - , -, getters seters . , !

+1

,    , .    , .    .

0

Source: https://habr.com/ru/post/1599476/


All Articles