Reputation: 141
For example I have an activity class. In this class I have some variables and I'd 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);
}
}
Last line gives me a NullPointerException
. I know I need to initialize it but how can I initialize an activity?
Upvotes: 5
Views: 351
Reputation: 172
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 it will help you. let me know once you are done.
Upvotes: 1
Reputation: 2657
You have a different options...
Create a getter to get values from classes:
public MenuActivity getMenuActivityVar(){
return this.MenuActivity;
}
From other activity using this method like this:
//Other activity or class
//Declare a new var as your class
SearchView sView = new SearchView();
MenuActivity nMenu = sView.getMenuActivityVar();
In this case is a static method means that all static vars have a static value you don't need declare a new class from this one because is static.
public static class SearchView {{
public static MenuActivity menuActivity;
.
.
}
With this change you can call this var using:
//This call it's do it from other activity
MyNewVar = SearchView.MenuActivity;
public class SearchView {
public MenuActivity menuActivity;
}
From the other activity when you create a class like this:
SearchView sView = new SearchView();
//In this moment your var are null.
After if you modify this var in your class from methods for example then you can get var using like this:
MenuActivity MyNewMenu = sView.menuActivity;
I think the best option is first, it's the best important part of classes getters and setters from classes. Tell me if I helped you and good programming!
Upvotes: 2
Reputation: 4421
If you want the value of the variable pass it to next activity using intents. if it is a static value make it in separate constant file and use it with the class name. If it is a view make use of the view again in the next activity.
Upvotes: 0