Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling external methods without instantiating an object

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));

   }
  }
like image 373
Matthew Levene Avatar asked Mar 17 '23 07:03

Matthew Levene


1 Answers

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

like image 120
Dev Avatar answered Mar 23 '23 01:03

Dev