This is my code. I don't know exactly why the program doesn't work. If I press the button, it should display the corresponding quote and its author. But nothing is displayed. After experimenting, I found out that the try clause of the exception DIDN'T REALLY work. I need help on this one. About the loop, I am just going to display 1 quote and author. :) Thank you DaniWeb
package com.example.xmlfinalproject;
import android.os.*;
import android.app.*;
import android.view.*;
import android.widget.*;
import java.net.URL;
//import java.util.Random;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
public class MainActivity extends Activity {
Button b1;
TextView tvAuthor, tvQuotes, tvProjectTitle;
EditText txtAuthor, txtQuotes;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Random get = new Random();
// int seed = get.nextInt(10-1 + 1) + 1;
b1 = (Button)findViewById(R.id.button1);
tvProjectTitle = (TextView)findViewById(R.id.lblProjectTitle);
tvAuthor = (TextView)findViewById(R.id.lblAuthor);
tvQuotes = (TextView)findViewById(R.id.lblQuote);
txtAuthor = (EditText)findViewById(R.id.txtAuthor);
txtQuotes = (EditText)findViewById(R.id.txtQuote);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
// Random get = new Random();
// int seed = get.nextInt(10-1 + 1) + 1;
URL url = new URL("http://ghettodoggs.bugs3.com/quotes.xml");
DocumentBuilderFactory x = DocumentBuilderFactory.newInstance();
DocumentBuilder y = x.newDocumentBuilder();
Document z = y.parse(new InputSource(url.openStream()));
NodeList quote = z.getElementsByTagName("quote");
NodeList author = z.getElementsByTagName("author");
for(int i = 0; i < 1; i++)
{
Element gatherQuotes = (Element) quote.item(3);
Element gatherAuthors = (Element) author.item(3);
String quotes = gatherQuotes.getFirstChild().getNodeValue();
String authors = gatherAuthors.getFirstChild().getNodeValue();
txtAuthor.setText(authors);
txtQuotes.setText(quotes);
}
}
catch (Exception e)
{
txtAuthor.setText("hello");
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}