2015-11-17 88 views
-3

我的Java列表看起來象下面這樣:如何從ArrayList中獲得價值

ArrayList<String> al = new ArrayList<String>(); 

City: Berlin, Document guid: 08c14773-db81-4c43-8b66-51e5d39a4b2d, Content: null 
City: Amsterdam, Document guid: 28c14773-db81-4c43-8b66-51e5d39a4b2d, Content: null 
City: Tokio, Document guid: 18c14773-db81-4c43-8b66-51e5d39a4b2d, Content: null 

我需要從內容中獲得價值。下面的代碼顯示所有的值,但我怎麼能從獲得字符串內容

for (int i=0;i < al.size();i++){ 
    Log.i("Value of element "+i, String.valueOf(al.get(i))); 
} 
+4

請問您可以重新制定信息......什麼是**「城市:柏林,文檔指南:08c14773-db81-4c43-8b66-51e5d39a4b2d,內容:null」**,一個對象?,一個json? ...? –

+0

這是一個對象 – user5523912

+0

你的對象是怎樣的? – Flown

回答

1

你可以這樣說:

String[] splitString = al.get(0).split(": "); 
System.out.println(splitString[splitString.length - 1]); 

話雖這麼說,你應該建立一個Object存儲,那麼所有這些數據放在ObjectArrayList ...

+0

這個的任何例子? – user5523912

+1

@ user5523912創建一個'Class'? – brso05

0
for (int i=0;i < al.size();i++){ 
    String currentValue = al.get(i); 
    String[] partsOfCurrentValue = currentValue.split(","); 

    for (String part : partsOfCurrentValue) { 
     If (part.trim().startsWith("Content")) { 
      String[] partsOfContent = part.split(":"); 
      String valueOfContent = partsOfContent[1]; 
      Log.i("Value of element "+i, valueOfContent); 
      break; 
     } 
    } 

} 
+0

在你的例子中If(part.startsWith(「Content」)){loop永遠不會進入 – user5523912

+0

可能是因爲在Content:...之前有一個空的空格。請參閱上面編輯的代碼。 – TR1

0

定義你自己的班級:

public class INfo { 

    private String city; 
    private String uuid; 
    private String content; 
    /** 
     * @param city 
     * @param uuid 
     * @param content 
     */ 
    public INfo(String city, String uuid, String content) { 
     this.city = city; 
     this.uuid = uuid; 
     this.content = content; 
    } 

    /** 
    * @return the city 
    */ 
    public String getCity() { 
     return city; 
    } 

    /** 
    * @param city the city to set 
    */ 
    public void setCity(String city) { 
     this.city = city; 
    } 

    /** 
    * @return the uuid 
    */ 
    public String getUuid() { 
     return uuid; 
    } 

    /** 
    * @param uuid the uuid to set 
    */ 
    public void setUuid(String uuid) { 
     this.uuid = uuid; 
    } 

    /** 
    * @return the content 
    */ 
    public String getContent() { 
     return content; 
    } 

    /** 
    * @param content the content to set 
    */ 
    public void setContent(String content) { 
     this.content = content; 
    } 

} 

然後定義列表

List<INfo> infList = new ArrayList<INfo>(); 

最後名單的每一個elemet實際上是信息類的一個實例,這樣你就可以通過調用吸氣......像獲取對象的屬性:

System.out.println(infList.get(0).getCity());