简体   繁体   English

从另一个类调用arraylist方法

[英]Calling an arraylist method from another class

How do i call this method in another class? 如何在另一个类中调用此方法?

I need to use the array list inside this method from a class called database helper to compare the value of a variable with this array list in another class(Main Menu). 我需要在称为数据库助手的类中使用此方法中的数组列表,以将变量的值与另一个类(主菜单)中的此数组列表进行比较。

The idea is that it gets all the values inside the database and checks if the variable from the class Main Menu value is anywhere inside the array list of the class database helper. 其思想是,它获取数据库内部的所有值,并检查类Main Menu值中的变量是否在类数据库帮助器的数组列表内的任何位置。

  public ArrayList<Phone> retrieveAllPhones() {
        ArrayList<Phone> phoneArrayList
                = new ArrayList<>();
// SELECT * FROM student;
        SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = db.query(Phone.TABLE,
                null,// columns
                null,// selection
                null,// selection args
                null,// group by
                null,// having
                null// order by
        );

        if (cursor.moveToFirst()) {
            do {
                Phone phone = new Phone();

                phone.setSenderNum(
                        cursor.getString(cursor.getColumnIndex(Phone.NUM))
                );
                // assign this name to Student

                phone.setMessage(
                        cursor.getString(cursor.getColumnIndex(Phone.MESSAGE))

                );
                phone.setGeo(
                        cursor.getString(cursor.getColumnIndex(Phone.GEO))
                );

                phoneArrayList.add(phone);
            } while (cursor.moveToNext());
        }

I'm not entirely sure I understand your question. 我不确定我是否理解您的问题。 I presume the phoneArrayList is the return value, can't you just save the return value and use that? 我假设phoneArrayList是返回值,难道不能只保存返回值并使用它吗? It would help to include the full method at least, preferably the full class. 至少包括完整方法(最好是完整类)会有所帮助。

you can call it by instantiating object from the class like: 您可以通过实例化类中的对象来调用它:

ArrayList<Phone> phones = new YourDatabaseHelperClass().retrieveAllPhones();

or change the method to static like: 或将方法更改为static,例如:

public static ArrayList<Phone> retrieveAllPhones() {
  ...
}

Then you only need to call it with: 然后,您只需使用以下命令调用它:

ArrayList<Phone> phones = YourDatabaseHelperClass.retrieveAllPhones();

在此处输入图片说明

Possible to access ArrayList from another Class but The ArrayList should be public and static. 可以从另一个类访问ArrayList,但是ArrayList应该是公共的和静态的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM