簡體   English   中英

轉換清單 <?> 列出 <String> 在Android中

[英]Convert List<?> to List<String> in Android

public List<Contact> getContacts()
{
    SQLiteDatabase db;
    String cmd;
    List<Contact> name = new ArrayList<Contact>();
    db = myDb.getReadableDatabase();
    Cursor cursor = db.rawQuery("SELECT * FROM contact;" , null);
    while(cursor.moveToNext())
    {
        int contactID       = Integer.parseInt(cursor.getString(0));
        String familyName   = cursor.getString(1);
        String firstName    = cursor.getString(2);
        int houseNumber     = Integer.parseInt(cursor.getString(3));
        String street       = cursor.getString(4);
        String town         = cursor.getString(5);
        String country      = cursor.getString(6);
        String postcode     = cursor.getString(7);
        int telephoneNumber = Integer.parseInt(cursor.getString(8));
        Contact contact     = new Contact(contactID,familyName,firstName,houseNumber,street,town,country,postcode,telephoneNumber);
    }
    Intent intent = new Intent(Database.this,MainActivity.class);
    intent.putStringArrayListExtra("contacts", name);
    startActivity(intent);

    return name;
}

Intent類型的方法putStringArrayListExtra(String, ArrayList<String>)不適用於參數(String, List<Contact>)

為了使用putStringArrayListExtra(); 方法,我需要將List<contact>名稱轉換為List名稱,如何將其轉換? 謝謝

因為對象列表實際上不是字符串列表,所以據我所知,最好的方法是遍歷list並將每個項目轉換為新的字符串列表:

List<String> stringsList = new ArrayList<>(list.size());
for (Object object : list) {
    stringsList.add(Objects.toString(object, null));
}

似乎您正在嘗試通過IntentList<Contacts>傳遞給-

沒有必要使用putStringArrayListExtra()方法作為有putParcelableArrayList()使用其中可以傳遞方法ArrayList<Contact>直接。

只需使用,

putParcelableArrayList("KEY", your ArrayList<Contact>); // Make sure Contact implementes Parcelable 

您可以在Receiver Activity獲取ArrayList<Contact> -

Bundle b = getIntent().getExtras();
ArrayList<Contact> data = b.getParcelableArrayList("KEY");

但是,您可以使用Serializable代替Parcelable但是建議使用Parcelable ,因為它就像Flash。 這是為什么呢?

首先聲明一個新的字符串數組。

List<String> newList = new ArrayList<String>(list.size());
newList.addAll(list);

這會將所有元素添加到新的字符串列表中。 list是您以前的容器。

為了使用Parceble在組件之間傳遞對象,Android還使用Binder以高度優化的方式促進了此類通信。 活頁夾與作為消息容器的包裹進行通信。 活頁夾將要打包的包裹封送,發送和接收,然后在另一端解封以重建原始包裹的副本。請在此處繼續閱讀。

暫無
暫無

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

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