Calling external methods without instantiating an object - java

I was wondering if it was possible to call the methods of an external class without actually having to declare an object of that class. They way I've got it set up causes the ArrayList stored within the object empties every time the method the object is used in is called.
If I can call the method without an object, then I can fix my problem.
Thanks in advance.
calling class:
public class BookingScreen extends Activity {
GAClass sendApplication = new GAClass();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_booking_screen);
}
public void saveBookingInfo(View view) {
EditText applicantNameText = (EditText) findViewById(R.id.applicantNameTextField);
EditText itemToBurnText = (EditText) findViewById(R.id.itemToBurnTextField);
String appName = applicantNameText.getText().toString();
String appItemToBurn = itemToBurnText.getText().toString();
if (appItemToBurn.isEmpty() || appName.isEmpty()) {
Toast.makeText(BookingScreen.this, "Please fill in all fields.", Toast.LENGTH_SHORT).show();
}
else {
sendApplication.storeApplication(appName, appItemToBurn);
this.finish();
}
}
External method class:
public class GAClass {
ArrayList<Application> peopleAttending;
public void storeApplication(String name, String item){
peopleAttending = new ArrayList<>(10);
peopleAttending.add(new Application(name, item));
}
}

You can do something like below
public class GAClass {
public static ArrayList<Application> peopleAttending=null;
public static void storeApplication(String name, String item){
if(null==peopleAttending){
peopleAttending = new ArrayList();
}
peopleAttending.add(new Application(name, item));
}
}
You can invoke above method like below
GAClass.storeApplication(str_name,str_item);
when you make peopleAttending arraylist static it can be access in static method and
if(null==peopleAttending){
peopleAttending = new ArrayList();
}
Above code ensure first time initialization if peopleAttending 9s null

Use static methods. You can call a static method without creating object of enclosing class.
https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html

What exactly are you trying to achieve?
The static methods in a class would not need an instance of the class so you can make the methods you need (that do not require the state of the object - i.e. do not need a particular object to work on) static and call them like this:
ClassWithStaticMethods.staticMethod() ;

Related

Instantiate public object inside method

I'm trying to instantiate an object inside a method of a class so it can be used anywhere in the class. I come from a python background and it is quite easy, you can just pass the instantiated object to an instance of it's "self" like below.
self.camera = CameraInstance()
How do you do this in Java? I tried something like below but it doesn't like it.
private void init_camera_settings() {
public CameraInterface camera;
camera.TakePhoto()
}
private void someotherMethod() {
camera.TakePhoto()
}
Both methods are in the same class. The reason for this is because I only want to instantiate the camera object only in certain scenarios.
Thanks!
You can't declare a field inside a method. In Java, a type either has a field, or it doesn't. Every instance of the same class has the same set of fields.
But you can declare the field (not in a method) and decide to only assign a value to it in a method:
// Note: avoid public fields
public CameraInterface camera;
private void initCameraSettings() {
camera = new Camera();
}
private void someotherMethod() {
camera.takePhoto();
}
(The field will have a default value, in this case null, until you assign a different value to it.)
As an aside, I'd strongly advise against public fields. I make every field private, and add properties to allow access where necessary. This allows you to change implementation details later. The one exception to this is public static final fields of immutable types, basically for constants, but even there I'd be cautious.
To use the variable throughout the class in different methodsm the variables should have class scope. You usually use new to create a new Object
public MyClass {
public CameraInterface camera = new Camera ();
private void init_camera_settings() {
camera.TakePhoto()
}
private void someotherMethod() {
camera.TakePhoto()
}
}
self.camera = CameraInstance()
is equivalent to:
class Foo {
private CameraInstance camera;
public Foo() {
this.camera = new CameraInstance();
}
// use "this.camera" in methods.
}

Passing an object as an argument through an external method call

I have an object which I need to pass into an ArrayList. The ArrayList is contained within an external method, which is in another class.
I've debugged the program and know that the information being passed into the 'Application' Constructor is being put into the 'app' object. My problem is moving it from here to the 'GuestsAttending' Method.
Any help would be greatly appreciated.
Booking Screen Method:
public void saveBookingInfo(View view) {
GuestsAttending sendApplication = new GuestsAttending();
EditText applicantNameText = (EditText) findViewById(R.id.applicantNameTextField);
EditText itemToBurnText = (EditText) findViewById(R.id.itemToBurnTextField);
String appName = applicantNameText.getText().toString();
String appItemToBurn = itemToBurnText.getText().toString();
if (appItemToBurn.isEmpty() || appName.isEmpty()) {
Toast.makeText(BookingScreen.this, "Please fill in all fields.", Toast.LENGTH_SHORT).show();
}
else {
Application app = new Application(appItemToBurn, appName);
sendApplication.getGuestsAttending(app);
this.finish();
}
}
GuestsAttending Method:
public void getGuestsAttending(Application app){
peopleAttending.add(app);
}
Application Class:
public class Application {
private String name;
private String item;
public Application(String applicantName, String applicantItem) {
name = applicantName;
item = applicantItem;
}
}
For clarity, change "getGuestAttending" to "addGuestAttending". If "peopleAttending" is an array, your method won't work. Change "peopleAttending" to a List or Set, then it will work. If "peopleAttending" needs to be an array, you can't add items to it unless you declare it big enough to hold all your guests. Then you have to keep track of the number of guests, so you know where to insert new guests. In other words, don't use an array, use a List:
List attendingGuests = new LinkedList();
I found a different solution. Instead of creating the object in another class and passing it into the external method call as a parameter, I created the object within the external method, and passed a couple of strings to the method, which I passed into another classes' constructor to make the object within the method.

Permanent Objects passed from one Activity to another

I must pass an ArrayList from one Activity A to another Activity B.
I did it using getSerializableExtra and putExtra methods. I already know the meaning of these methods, but I don't know if stuff that I passed using them is stored permanently in the new activity or if it is necessary to reload activity A in order to retrieve my data in B.
So the question is: how can I load my data in a initial splash screen and then use it in all my others activity without reloading the splash screen?
Don't use Preference Class! Preferences are only used for settings values. For passing data to another Activity use Serializable or Parcelable. Remember that all the objects which will be passed to another activity have to implement Serializable or Parcelable. So you extend the ArrayList to a custom Class which implements Parcelable or Serializable.
You do this like this:
Intent intent = new Intent(getContext(), SomeClass.class);
intent.putSerializableExtra("value", <your serializable object>);
startActivity(intent);
and receive them like
YourObject yourObject = getIntent().getSerializableExtra("value")
or look here for Parcelable
Help with passing ArrayList and parcelable Activity
Data processed in Activity A does not need to process again in Activity B. If the data is computed in A and you send it to B computed, B receives it computed already.
Here are some ways to do it right: http://developer.android.com/guide/topics/data/data-storage.html
You can use Preference class, in which you can define its static instance. Than create variable according your desire datatype (even ArrayList). Make property for get and set of this variable.
Set the value on splash screen and get anywhere in application where you need.
Try this, if you need , I will upload code also.
I have written some code regarding that, it would help other activities to fetch data easily, use this when the data is not confidential,
public class HelperShared {
public static final String score = "Score";
public static final String tag_User_Machine = "tag_User_Machine",
tag_Machine_Machine = "tag_Machine_Machine",
tag_Draw_Machine = "tag_Draw_Machine",
tag_Total_Machine = "tag_Total_Machine";
public static SharedPreferences preferences;
public static Editor editor;
public HelperShared(Context context) {
this.preferences = context.getSharedPreferences(score,
Activity.MODE_PRIVATE);
this.editor = preferences.edit();
}
/*
* Getter and Setter methods for Machine
*/
public void setUserMachine(int UserMachine) {
editor.putInt(tag_User_Machine, UserMachine);
editor.commit();
}
public void setMachineMachine(int MachineMachine) {
editor.putInt(tag_Machine_Machine, MachineMachine);
editor.commit();
}
public void setDrawMachine(int DrawMachine) {
editor.putInt(tag_Draw_Machine, DrawMachine);
editor.commit();
}
public void setTotalMachine(int TotalMachine) {
editor.putInt(tag_Total_Machine, TotalMachine);
editor.commit();
}
public int getUserMachine() {
return preferences.getInt(tag_User_Machine, 0);
}
public int getMachineMachine() {
return preferences.getInt(tag_Machine_Machine, 0);
}
public int getDrawMachine() {
return preferences.getInt(tag_Draw_Machine, 0);
}
public int getTotalMachine() {
return preferences.getInt(tag_Total_Machine, 0);
}
}
if your question is "how can I load my data in a initial splash screen and then use it in all my others activity without reloading the splash screen?" Than I have better solutions for you.
Create a Class Memdata.java
public class Memdata{
private static Memdata instance = null;
private String userobject;
public static Memdata getInstance(){
if ( instance == null){
instance = new Memdata();
}
return instance;
}
public String getuserobject() {
return userobject;
}
public void setuserobject(String userobject) {
this.userobject= userobject;
}
}
on You Splash Screen' onCreate method, set the value
Memdata obj = Memdata.getInstance();
obj.setuserobject("hello");
Than in any activity, where you want to access this variable, just make its object and get value.
Like in MyActivity class
Memdata obj = Memdata.getInstance();
String str = obj.getuserobject()
You can define any type of variable according your requirement.
You can extend the base Application class and add member variables to it:
public class MyApp extends Application {
private String appLevelString;
public String getAppLevelString() {
return this.appLevelString;
}
public void setAppLevelString(String val) {
this.appLevelString= val;
}
}
You will have to update the manifest file as follows:
<application android:icon="#drawable/icon"
android:label="#string/app_name"
android:name="MyApp">
You can get and set data like this:
//For setting
((MyApp) this.getApplication()).setAppLevelString("Test string");
//For getting
String str = ((MyApp) this.getApplication()).getAppLevelString();

Copy ResolveInfo item from ArrayList a to ArrayList b?

Aasically I'm trying to add an item from ArrayList a (allApps) to ArrayList b (myApps) but I'm getting an error.
This is what I'm trying:
public ArrayList myApps = new ArrayList();
#Override
public void onCreate(Bundle savedInstanceState) {
...
for(final ResolveInfo app : allApps) {
addApp(app);
}
}
public void addApp(ResolveInfo app) {
ArrayList.add(app); // ERROR: Cannot make a static reference to the non-static method add(Object) from the type ArrayList
}
What does this error mean and how can I get I copy an item from one array to the other?
add method of ArrayList is not static method so you can not call outside an instance of ArrayList. Declare instance first then call add
it should be myApps.add(app);
You need to call add on an instance of ArrayList, not on the class itself, given your description, what you're looking for is
public void addApp(ResolveInfo app) {
myApps.add(app);
}
Change you method like this:
public void addApp(ResolveInfo app) {
myApps.add(app);
}

Is it possible to use this class instance in the constructor?

It's just something that puzzles me. Is it possible to use the current instance of the class within the constructor?
I've created a BroadcastReceiver that registers itself with the context within the constructor of the BroadcastReceiver. In addition it will unregister again. Is this good style?
Here's my example:
public class MyBroadcastReceiver extends BroadcastReceiver {
protected Context context;
protected MyOnBroadcastReceivedListener listener;
protected int receiverId;
protected String receiverTag;
public MyBroadcastReceiver(int receiverId, Context context, MyOnBroadcastReceivedListener listener, String receiverTag) {
super();
this.context = context;
this.listener = listener;
this.receiverId = receiverId;
this.receiverTag = receiverTag;
IntentFilter intentFilter = new IntentFilter(receiverTag);
context.registerReceiver(this, intentFilter); // <--- Look at the use of this here
}
public void detach() {
if (context != null) {
context.unregisterReceiver(this); // <--- Look at the use of this
}
}
#Override
public void onReceive(Context context, Intent intent) {
// ...
if (listener != null) {
listener.onBroadcastReceived(receiverId, "Bla", "Blub");
}
}
}
Yes, no trouble at all.
Inside the constructor, the object has been created but still no reference has been returned to the rest of the java code. You can use this without worries.
Anyway, in some frameworks where some attributes may be initialized automatic (Context Dependent Injection, CDI), it is not possible to fully initialize the class in the constructor (because such attributes are still not available and may be needed). These frameworks rely in that you mark a method as #PostConstruct; after all attributes are set that method will be called (just so you know what it means when you find it).
If you refer to using this in constructor code, then yes - it is perfectly valid, otherwise constructor would not be really able to construct to much within own instance. I'd however suggest following common practice and prefix your class members (most commonly used prefix is 'm') which helps avoid problems which are sometimes hard to debug. So instead of:
protected Context context;
protected MyOnBroadcastReceivedListener listener;
you would have:
protected Context mContext;
protected MyOnBroadcastReceivedListener mListener;
You can do this, but is not a good style. Passing this from inside a class constructor is dangerous as the current, still constructing object might not be fully intialized.
For example, you might one day add a new int field to the MyBroadcastReceiver, but overlook that you have the statement context.registerReceiver(this, intentFilter); and add the intialization of the new field at the end of the constructor:
public MyBroadcastReceiver(int receiverId, Context context, MyOnBroadcastReceivedListener listener, String receiverTag) {
super();
this.context = context;
this.listener = listener;
this.receiverId = receiverId;
this.receiverTag = receiverTag;
IntentFilter intentFilter = new IntentFilter(receiverTag);
context.registerReceiver(this, intentFilter); // <--- Look at the use of this here
this.newField = 1;
}
Now, you might expect that in the Context.registerReceiver method the newField to be 1 as it initialized in the MyBroadcastReceiver constructor. But you will get the value 0.
See also the following SO question for more information and more potential problems that could appear: Passing "this" in java constructor
Yes it works. I tried a simple test case. and it works. :
public class Test {
private int variable;
private Test2 test2;
public Test(int variable, Test2 test2) {
this.variable = variable;
this.test2 = test2;
test2.printTest(this);
}
public int getVariable() {
return variable;
}
public static void main(String[] args) {
Test test = new Test(111111,new Test2());
}
}
class Test2{
Test2() {
}
public void printTest(Test test){
System.out.println(test.getVariable());
}
}
And it works like a charm

Categories

Resources