How do I access the method myMethod from another class?
public class controller extends Activity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
int myMethod() {int id = 0; return id;} //arbitrary example, may also be static?
}
You pass in your controller Activity to the other class, the way you would with any other object in Java. Just be careful not to hold onto an Activity in places that might cause garbage collection issues (e.g., a service, a static data member, a custom Application object).
Related
I need to call a method in fragment when a certain item is selected in navigation drawer activity.
For this, I've created one interface which I Will be initializing & calling a method from the activity, Also I'll implement this interface in Fragment and override this method.
Here is code snippet for declaring an interface.
public interface AlertForDiscardDefaultProfileChanges {
void alertForDiscardDefaultProfileChanges(int navigationItemID);
}
And this is how I'm initializing in activity.
private AlertForDiscardDefaultProfileChanges alertForDiscardDefaultProfileChanges;
#Override
public void onCreate(Bundle savedInstanceState) {
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
alertForDiscardDefaultProfileChanges = (AlertForDiscardDefaultProfileChanges) this;
}
Here I'm getting java.lang.ClassCastException for initializing it.
Not sure what I'm missing here or what's wrong.
you have to implements this interface to your activity/fragment for eg :
MainActivity :
public class MainActivity extends AppCompatActivity implements FragmentClassName.AlertForDiscardDefaultProfileChanges{
//override methods
#Override
public void alertForDiscardDefaultProfileChanges(String navigationItemID) {
// now use navigationItemID here...
}
}
Here is how I achieved it,
I called a method through an object of a fragment in which I wanted to implement a method.
Fragment Class -
public class DefaultProfileFragment extends Fragment implements
AlertForDiscardDefaultProfileChanges {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_default_profile, container,
false);
mContext = view.getContext();
return view;
}
#Override
public void alertForDiscardDefaultProfileChanges(int navigationItemID) {
showDismissWarning(navigationItemID);
}
Activity from which I need to call interface method.
A Just simple object of a fragment class and name of a method. Nothing fancy needs to be done. No need to initialize an interface.
(new DefaultProfileFragment()).alertForDiscardDefaultProfileChanges(id);
Step-1
public interface AlertForDiscardDefaultProfileChanges {
void alertForDiscardDefaultProfileChanges(int navigationItemID);
}
define this method from which activity and class you want transfer your data
Step 2 -
Define this method also in step 1 class.
private AlertForDiscardDefaultProfileChanges favListner;
public void setAlertOnDiscardListner(AlertForDiscardDefaultProfileChanges
favOnTouchListner) {
favListner = favOnTouchListner;
}
Step -3 .
pass value from Step 1 class like below
favListner.alertForDiscardDefaultProfileChanges(int navigationItemID);
Step-4
In which class you want data first implement that interface like.
Class A implements YourActivity_where_interface define.AlertForDiscardDefaultProfileChanges{
override Method.
}
Step 5.
You Should have to do one thing also in that class where you want data .
You should have to initialise interface from on Create method like below.
YourActivity_where_interface define.setAlertOnDiscardListner(this);
Done now you can play with it.
Is there any way in which I can move a bundle of data from one class to another without actually changing the layout?
For example:
I have 3 classes: class A, B and C.
Now class B has navigation drawer and bottom navigation menu implemented which can be seen on class A and C and also be used at the same time.
However, I have a button in the bottom navigation menu which takes me to class C but the data which I need to view in this is in class A.
Is there any way by which I can just send a bundle of data to class B but without using intents, then retrieve the data from class B and show it on class C?
** EDIT **
P.S : B is an AppCombatActivity extended class and A and C are Fragment extended classes.
Your question is very simple to implement but it can also become a headache. This is what you should do.
class A:
public class A extends Activity {
static A INSTANCE;
String data="A";
#Override
public void onCreate(Bundle savedInstanceState) {
INSTANCE=this;
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public static A getActivityInstance()
{
return INSTANCE;
}
public String getData()
{
return this.data;
}
}
class B:
public class B extends Activity {
String data;
#Override
public void onCreate(Bundle savedInstanceState) {
data=A.getActivityInstance().getData();
}
}
The trick is to create an Instance in class A and then using that instance to access all the public elements like methods, variables etc using that Instance.
Hope this helps :)
I would suggest using a SharedPreferences file to store the data in Class A. Then you can read from the SharedPreferences file wherever you want to show the data.
Refer this page -
https://developer.android.com/training/basics/data-storage/shared-preferences.html
You could use interface for passing data, this the reference
https://stackoverflow.com/a/9977370/2951976
I often have to deal with this kind an error when programming in Java on Android.
For example I have a class where I set a flag.
public class ViewActivity extends Activity {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
...
}
In another class I want to reset the FLAG_KEEP_SCREEN_ON
class DrawOnTop extends View {
...
if (condition) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
but this doesn't work, since I get "The method getWindow is undefined for the type DrawOnTop".
So I try to define a clearFlags method in ViewActivity class
void clearFlags() {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
and to call it from the DrawOnTop class:
if (condition) {
ViewActivity.clearFlags();
}
This doesn't work as well: I get "Cannot make a static reference to the non-static method clearFlags() from the type ViewActivity".
Well, let's make it static then.
static void clearFlags() {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
and then I get "Cannot make a static reference to the non-static method getWindow from the type Activity"
How could I execute such a statement?
If your DrawOnTop class is nested within the ViewActivity you can create a local Context variable and use it to call the getWindow(). If that's not the case then create a receiver in your activity class then from DawOnTop send an intent with your trigger to do whatever the job is. Do not instantiate your activity class, bad idea!
You can send getWindow() as parameter into clearFlags method.
Call clearFlags(Window window) from your activity: WindowHelper.getInstance().clearFlags(getWindow());
Helper class:
public class WindowHelper {
public static final WindowHelper instance = new WindowHelper();
public static WindowHelper getInstance() {
return instance;
}
public void clearFlags(Window window) {
window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
}
I tried to implement the solutions suggested by Aksaçlı and this turned out to be very simple:
In the ViewActivity class DrawonTop is called this way:
mDrawOnTop = new DrawOnTop(this);
The constructor of the second class contains this:
public DrawOnTop(Context context) {
super(context);
Therefore ViewActivity.clearFlags(); has simply to be rewritten as ((ViewActivity)getContext()).clearFlags();
Perhaps you should refer to an initialised object in your static method. So instead of:
void clearFlags() {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
you should create a static instance variable of your window:
private static staticWindowInstance;
void clearFlags() {
getStaticWindowInstance().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
For more information, you should check out the Singleton design pattern.
I have two classes - my main Android activity class, and my reflection class. I am using Android Studio.
In my main activity class I have one button. I want to make it so that when I press this button I should get the name of the button which is defined in strings.xml.
I don't want to use getText() so don't tell me to use it. I want to use reflection or any other good way.
In my reflection class I used reflection to get my field which I defined in my main activity class and put it into a string variable. When I show this value using a toast it's giving me a null value.
My Reflection Class
public class Reflection extends MyActivity
static public String Value;
public static void Cool() {
MyActivity myActivity=new MyActivity(); // Creating Android Main Activity Class Object
try {
Field field=myActivity.getClass().getField("btnFIRST"); //btnFirst Field Which i Defined In Android Main Activity Class
field.setAccessible(true);
Value=(String)field.get(myActivity);
}
catch (Exception E){
E.printStackTrace();
}
}
}
Android Main Activity Class
public class MyActivity extends Activity {
Reflection ref; // Here I Am Creating My Reflection Class Object
Button btnFIRST;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
btnFIRST = (Button) findViewById(R.id.btnFIRST);
ref=new Reflection(); // Reflection Class New Object
ref.Cool(); // Here I Am Calling My Cool Method Which Define In My Reflection Class
btnFIRST.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MyActivity.this, "Found Button Name="+ref.Value, Toast.LENGTH_LONG).show();
}
});
}
}
See here: +ref.Value I want to print my button value name, which is "(Click)" defined in strings.xml. But I am getting a null value instead.
I should be getting the output "Found Button Name=Click".
When you construct an instance of MainActivity, the value of btnFIRST for the instance is null. This is because btnFIRST is assigned only in the onCreate() method, which is never called on that instance.
You might think all you have to do is call onCreate() before trying to access the field, but that won't work either: you will get an exception. This is because the instance of MainActivity has not been properly set up (e.g., it doesn't have a proper Context, it does not have a Widnow, etc), so it won't be able to inflate the layout. The Android OS is responsible for doing this setup; it's not something you can do yourself. In general it is ALWAYS a bad idea to construct Activities yourself via their constructor.
That said, I can find absolutely no reason at all you would need to use reflection to obtain the text of this button. Unless you can give us a compelling reason why this would be necessary, you should just use getText().
Alternatively, if you know the string resource ID, you can call getString(...) in your Activity.
You'll have to bear with me here as I'm sure this is asked all the time, but I didn't manage to search it.
If I have a minimal android application and I seemingly have to declare all my controls in an event like onCreate, how do I then refer to these controls in functions given that these controls aren't initialized until the app is 'created'?
public class MyActivity extends ActionBarActivity {
public void myFunction(){
myButton.setText("Java is hard")
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
final button myButton = (Button) findViewById(R.id.designerbutton);
}
Do I have to pass the controls as arguments every single time I call the function? That seems a bit unwieldy.
Read up about Member variables:
There are several kinds of variables:
Member variables in a class—these are called fields.
Variables in a method or block of code—these are called local variables.
Variables in method declarations—these are called parameters.
The Bicycle class uses the following lines of code to define its fields:
public int cadence;
public int gear;
public int speed;
Field declarations are composed of three components, in order:
Zero or more modifiers, such as public or private.
The field's type.
The field's name.
The fields of Bicycle are named cadence, gear, and speed and are all of data type integer (int). The public keyword identifies these fields as public members, accessible by any object that can access the class.
You can store it as an attribute like any other Java object
public class MyActivity extends ActionBarActivity {
private Button myButton;
public void myFunction(){
myButton.setText("Java is hard")
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
myButton = (Button) findViewById(R.id.designerbutton);
}