0
我在類ImageManager
中創建了一個方法addImage
,它創建Picture
類的實例並將其添加到ArrayList
。當你通過run
類使用imageManager.addImage("title,image,"Arizona","a;ldkjsf;kasjdf");
添加圖像時,它工作得很好。沒有存儲在我的數組列表中的實例
但是當你從Parser
類添加一個圖像中的ImageManager
類圖像ArrayList
失去調用addImage
方法和getImages
方法之間從Parser
類創建的圖片,但不會失去通過MainViewController
類創建的實例。爲什麼它這樣做,我該如何解決它?
public class Run {
public static void main(String[] args){
Parser parser = new Parser();
ImageManager imageManager = new ImageManager();
imageManager.addImage("title", "location","description");
parser.parsePictureData();
imageManager.getImages();
}
}
public class Parser {
ImageManager imageManager = new ImageManager();
Document document;
public void parsePictureData() {
try{
readXMLFile();
readImageFromDocument();
}catch(IOException e){
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
}
private void readXMLFile() throws IOException, SAXException, ParserConfigurationException {
File file = new File(System.getProperty("user.dir")+"/src/"+"test.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.parse(file);
}
private void readImageFromDocument() {
NodeList pictureNodes = document.getElementsByTagName("picture");
for(int i = 0; i<pictureNodes.getLength();i++){
Node pictureNode = pictureNodes.item(i);
if(pictureNode.getNodeType()==Node.ELEMENT_NODE){
Element pictureElement = (Element) pictureNode;
String location =pictureElement.getAttribute("location");
String imagePath = pictureElement.getElementsByTagName("path").item(0).getTextContent();
String title = pictureElement.getElementsByTagName("title").item(0).getTextContent();
String description = pictureElement.getElementsByTagName("description").item(0).getTextContent();
imageManager.addImage(title,location,description);
}
}
}
}
public class ImageManager {
ArrayList<Pictures> images = new ArrayList<>();
public void addImage(String title, String location, String description){
Pictures newImage = new Pictures(title, location, description);
images.add(newImage);
System.out.println("1"+images);
}
public ArrayList<Pictures> getImages(){
System.out.println("2"+images);
return images;
}
}
public class Pictures{
private String title;
private String location;
private String description;
public Pictures(String title, String location, String description){
this.title = title;
this.location = location;
this.description = description;
}
}
一個MVCE(最小可驗證的完整示例)會更好 – efekctive
@efekctive FYI你可以把[]放在mcve上以獲得[mcve];) – 2017-06-20 19:00:51
將其更改爲更多的MCVE – goobs14