簡體   English   中英

從另一個類調用arraylist方法

[英]Calling an arraylist method from another class

如何在另一個類中調用此方法?

我需要在稱為數據庫助手的類中使用此方法中的數組列表,以將變量的值與另一個類(主菜單)中的此數組列表進行比較。

其思想是,它獲取數據庫內部的所有值,並檢查類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());
        }

我不確定我是否理解您的問題。 我假設phoneArrayList是返回值,難道不能只保存返回值並使用它嗎? 至少包括完整方法(最好是完整類)會有所幫助。

您可以通過實例化類中的對象來調用它:

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

或將方法更改為static,例如:

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

然后,您只需使用以下命令調用它:

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

在此處輸入圖片說明

可以從另一個類訪問ArrayList,但是ArrayList應該是公共的和靜態的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM