I’m learning android now, and i write some simple codes according to the book.
i create an android project named Chapter03_ResourceActivity, then create test.xml in res/xml/ folder, contents are as follows:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<customer name = "first_name" age = "1" email = "first_name@xml.com" />
<customer name = "second_name" age = "2" email = "second_name@xml.com" />
</resources>
and type codes in Chapter03_ResourceActivity.java(src/com.app.MainActivity/Chapter03_ResourceActivity.java) as follows:
package com.app.MainActivity;
import org.xmlpull.v1.XmlPullParserException;
import android.app.Activity;
import android.content.res.XmlResourceParser;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Chapter03_ResourceActivity extends Activity {
/** Called when the activity is first created. */
private Button myButton;
private TextView myTextView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button myButton = (Button)findViewById(R.id.btn_xml);
final TextView myTextView = (TextView)findViewById(R.id.text_xml);
myButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
StringBuilder sb = new StringBuilder();
XmlResourceParser xrp = getResources().getXml(R.xml.test);
int counter = 0;
try {
while(xrp.getEventType() != XmlResourceParser.END_DOCUMENT) {
if(xrp.getEventType() == XmlResourceParser.START_TAG) {
String name = xrp.getName();
if(name.equals("customer")) {
counter ++;
sb.append(counter + " Customer" + "\n");
sb.append(xrp.getAttributeValue(0) + "\n");
sb.append(xrp.getAttributeValue(1) + "\n");
sb.append(xrp.getAttributeValue(2) + "\n\n");
}
xrp.next();
}
}
myTextView.setText(sb.toString()); <<--Here Eclipse mark an error.
catch(XmlPullParserException e) {
e.printStackTrace();
}
}
}
}); <<--Here Eclipse mark another error.
}
}
Two errors have been marked in the code. i tried to solve it by myself, but forgive my dull, i cannot find it. i counted the number of “{” and “}” for many times, and just find they are right equal. Maybe i really miscounted? Or something i dont konw made this error? Any help appreciated.
should be:
It’s not the quantity that’s causing you grief, just the placement. Your
catchis actually inside thetryblock at the moment rather than immediately after it.