2013-12-16 2 views
0

Я новичок в программировании на Java, но проделал определенную работу с C#. Я потянул некоторый XML и успешно проанализировал его. Я также могу успешно отображать eiter Первый узел или последний узел, но мне нужно итерации через узлы XML при нажатии кнопки.Итерация через узлы XML при нажатии кнопки

Я на стенде все еще пытается найти способ выполнить итерации в моей функции, которая находится ниже:

public void buttonPressed(View view) 
    { 
     // All static variables 
     final String URL = "http://info4420w.ad.uvu.edu/it4420/10540595/Final_Project/Final_Project/quoterestservice.aspx"; 
     // XML node keys 
     final String KEY_TABLE1 = "Table1"; // parent node 
     final String KEY_QUOTE_ID = "QuoteID"; 
     final String KEY_CUST_NAME = "custName"; 
     final String KEY_CUST_PHONE = "custPhone"; 
     final String KEY_CUST_YEAR = "custYear"; 
     final String KEY_CUST_MAKE = "custMake"; 
     final String KEY_CUST_MODEL = "custModel"; 
     final String KEY_CUST_ISSUE = "custIssue"; 
     final String KEY_CUST_LOCLAT = "custLocLat"; 
     final String KEY_CUST_LOCLNG = "custLocLng"; 
     final String KEY_CUST_DESTLAT = "custDestLat"; 
     final String KEY_CUSTDESTLNG = "custDestLng"; 



     String quoteID = new String(); 
     String cName = new String(); 
     String cPhone = new String(); 
     String cYear = new String(); 
     String cMake = new String(); 
     String cModel = new String(); 
     String cIssue = new String(); 
     String cLocLat = new String(); 
     String cLocLng = new String(); 
     String cDestLat = new String(); 
     String cDestLng = new String(); 
     try { 
      XMLParser parser = new XMLParser(); 
      String xml = parser.getXmlFromUrl(URL); // getting XML 
      Document doc = parser.getDomElement(xml); // getting DOM element 
      NodeList nl = doc.getElementsByTagName(KEY_TABLE1); 

      quoteID = ""; 
      cName = ""; 
      cPhone = ""; 
      cYear = ""; 
      cMake = ""; 
      cModel = ""; 
      cIssue = ""; 
      cLocLat = ""; 
      cLocLng = ""; 
      cDestLat = ""; 
      cDestLng = ""; 

      // looping through all Table1 nodes <Table1> 
//   for (int i = 0; i < nl.getLength(); i++) { 
       int i = 0; 

       Element e = (Element) nl.item(i); 
       quoteID = parser.getValue(e, KEY_QUOTE_ID); // name child value 
       cName = parser.getValue(e, KEY_CUST_NAME); // cost child value 
       cPhone = parser.getValue(e, KEY_CUST_PHONE); // description child value 
       cYear = parser.getValue(e, KEY_CUST_YEAR); 
       cMake = parser.getValue(e, KEY_CUST_MAKE); 
       cModel = parser.getValue(e, KEY_CUST_MODEL); 
       cIssue = parser.getValue(e, KEY_CUST_ISSUE); 
       cLocLat = parser.getValue(e, KEY_CUST_LOCLAT); 
       cLocLng = parser.getValue(e, KEY_CUST_LOCLNG); 
       cDestLat = parser.getValue(e, KEY_CUST_DESTLAT); 
       cDestLng = parser.getValue(e, KEY_CUSTDESTLNG); 
       i++; 
//   } 
     } catch (Exception e) { 
      cName = e.getMessage() + e.getStackTrace(); 
     } 
     TextView tQuote = (TextView)findViewById(R.id.textView1); 
     TextView tCust = (TextView)findViewById(R.id.textViewCust); 
     TextView tIssue = (TextView)findViewById(R.id.textViewIssue); 
     TextView tCar = (TextView)findViewById(R.id.textViewCar); 
     TextView tLoc = (TextView)findViewById(R.id.textViewLoc); 
     TextView tButton = (TextView)findViewById(R.id.button1); 
     tButton.setText("Next Quote"); 
     tQuote.setText("Quote ID: " + quoteID); 
     tCust.setText("Name: " + cName + " Cell: " + cPhone); 
     tIssue.setText("Issue: " + cIssue); 
     tCar.setText("Make: " + cMake + " Model: " + cModel + " Year: " + cYear); 
     tLoc.setText("Loc: " + cLocLat + ", " + cLocLng); 

    } 

Моя кнопка:

<Button 
    android:id="@+id/button1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_below="@+id/textViewLoc" 
    android:layout_centerHorizontal="true" 
    android:layout_marginTop="28dp" 
    android:onClick="buttonPressed" 
    android:text="Get Quote" /> 

Спасибо заранее за ваш время.

+0

Используйте SAX-парсер. – vzamanillo

ответ

0

Как указано в другом ответе, хранить каждый элемент в ArrayList и получить какой индекс вы хотите на кнопку мыши. Попробуйте что-то вроде этого (набрав с мобильного телефона, надеюсь, что это помогает):

MyObject класс:

public class MyObject { 

public String quoteID; 
public String name; 
public String phone; 
public int year; 

//...the rest of any information you want stored in this object 


} 

Тогда в вашей для цикла:

// Create a new ArrayList of MyObject 
ArrayList<MyObject> elements = new ArrayList<MyObject>(); 
try { 
     XMLParser parser = new XMLParser(); 
     String xml = parser.getXmlFromUrl(URL); // getting XML 
     Document doc = parser.getDomElement(xml); // getting DOM element 
     NodeList nl = doc.getElementsByTagName(KEY_TABLE1); 

     quoteID = ""; 
     cName = ""; 
     cPhone = ""; 
     cYear = ""; 
     cMake = ""; 
     cModel = ""; 
     cIssue = ""; 
     cLocLat = ""; 
     cLocLng = ""; 
     cDestLat = ""; 
     cDestLng = ""; 

     // looping through all Table1 nodes <Table1> 
    for (int i = 0; i < nl.getLength(); i++) { 
    // in your for-loop, create a new MyObject 
    MyObject myObject = new MyObject(); 

      Element e = (Element) nl.item(i); 
      quoteID = parser.getValue(e, KEY_QUOTE_ID); // name child value 

      // set String objects of MyObject instance myObject 
      myObject.quoteID = quoteID; 

      cName = parser.getValue(e, KEY_CUST_NAME); // cost child value 

      myObject.name = cName; 
      // pass rest of info to myObject with below values from parser... 
      cPhone = parser.getValue(e, KEY_CUST_PHONE); // description child value 
      cYear = parser.getValue(e, KEY_CUST_YEAR); 
      cMake = parser.getValue(e, KEY_CUST_MAKE); 
      cModel = parser.getValue(e, KEY_CUST_MODEL); 
      cIssue = parser.getValue(e, KEY_CUST_ISSUE); 
      cLocLat = parser.getValue(e, KEY_CUST_LOCLAT); 
      cLocLng = parser.getValue(e, KEY_CUST_LOCLNG); 
      cDestLat = parser.getValue(e, KEY_CUST_DESTLAT); 
      cDestLng = parser.getValue(e, KEY_CUSTDESTLNG); 

      //then finally, add myObject to ArrayList 
      elements.add(myObject); 
      i++; 
//   } 
    } catch (Exception e) { 
     cName = e.getMessage() + e.getStackTrace(); 
    } 
    TextView tQuote = (TextView)findViewById(R.id.textView1); 
    TextView tCust = (TextView)findViewById(R.id.textViewCust); 
    TextView tIssue = (TextView)findViewById(R.id.textViewIssue); 
    TextView tCar = (TextView)findViewById(R.id.textViewCar); 
    TextView tLoc = (TextView)findViewById(R.id.textViewLoc); 
    TextView tButton = (TextView)findViewById(R.id.button1); 
    tButton.setText("Next Quote"); 
    tQuote.setText("Quote ID: " + quoteID); 
    tCust.setText("Name: " + cName + " Cell: " + cPhone); 
    tIssue.setText("Issue: " + cIssue); 
    tCar.setText("Make: " + cMake + " Model: " + cModel + " Year: " + cYear); 
    tLoc.setText("Loc: " + cLocLat + ", " + cLocLng); 

} 

Наконец, могут быть получены по значению индекса:

MyObject myObject = elements.get(index): 

Надеюсь, это поможет, счастливое кодирование!

0

Почему вы не создать ArrayList, который содержит всю информацию о XML (скажем, ArrayList<MyObject> где MyObject является POJO), то при нажатии на кнопку просто установить TextView S к следующему пункту в списке?

+0

Когда ArrayList не был покрыт, я не мог этого сделать. –

0

Может быть проблемой с этой линией:

TextView tButton = (TextView)findViewById(R.id.button1);

Вы закидывающая кнопкой на TextView или кнопка на самом деле TextView?

попробовать это:

Button tButton = (Button)findViewById(R.id.button1);

Смежные вопросы