这是我在 stackoverflow 上的第一篇文章,我是 Android 新手。我已经在论坛上搜索了一个类似的问题,发现了这个问题:SAX 解析器进度监控。但不幸的是,它对我没有帮助。我的应用程序必须在日历中注册事件。我实现的第一件事是推进 xml 文件的下载。您可以在附加的代码中看到这一点。之后,我希望progressDialog 重置并开始跟踪解析的进度。如果这可以通过新的 setMessage() 和百分比值来完成,那就太好了。解析后的数据用于在日历中注册事件,同样使用相同的 progressDialog。
但起初我想知道如何跟踪解析的进度。如果有一些想法会很棒。谢谢
public class AddCoursesToCalendar extends Activity {
public static final int progress_bar_type = 0;
ArrayList<String> selectedCourses;
public ProgressDialog progressDialog;
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_add_courses_to_calendar);
if (bundle != null) {
selectedCourses = bundle.getStringArrayList("selectedCourses");
}
new GetDataTask().execute();
}
private Boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni != null && ni.isConnected())
return true;
return false;
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type:
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Downloading file. Please wait...");
progressDialog.setIndeterminate(false);
progressDialog.setMax(100);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setCancelable(true);
progressDialog.show();
return progressDialog;
default:
return null;
}
}
public class GetDataTask extends AsyncTask<String, String, Integer> {
private static final String URL = "http://10.0.2.2/WIN2.xml";
private static final String KEY_ITEM = "Item";
private static final String KEY_DAUER = "Duration";
private static final String KEY_ENDE = "End";
private static final String KEY_SEMESTER_DOZENT = "Location";
private static final String KEY_RAUMMITSTOCKWERK = "Organizer";
private static final String KEY_START = "Start";
private static final String KEY_VERANSTALTUNGSNAME = "Subject";
@Override
protected void onPreExecute() {
super.onPreExecute();
onCreateDialog(progress_bar_type);
}
@Override
protected Integer doInBackground(String... params) {
if (isOnline()) {
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL, this);
long id = 0;
Document doc = parser.getDomElement(xml, this);
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
for (int i = 0; i < nl.getLength(); i++){
Element e = (Element) nl.item(i);
for (String s : selectedCourses) {
if (parser.getValue(e, KEY_VERANSTALTUNGSNAME)
.contains(s)) {
String dozent = null;
int spaceIndex = parser.getValue(e,
KEY_SEMESTER_DOZENT).indexOf(" ");
int lastIndex = parser.getValue(e,
KEY_SEMESTER_DOZENT).length();
if (spaceIndex != -1) {
dozent = parser
.getValue(e, KEY_SEMESTER_DOZENT)
.substring(spaceIndex, lastIndex);
}
addEvent(
parser.getValue(e, KEY_VERANSTALTUNGSNAME),
parser.getValue(e, KEY_START),
parser.getValue(e, KEY_ENDE),
parser.getValue(e, KEY_DAUER),
dozent,
parser.getValue(e, KEY_RAUMMITSTOCKWERK),
id);
} id++;
}
}
} else {
Toast.makeText(AddCoursesToCalendar.this, "No Connection..",
Toast.LENGTH_LONG).show();
}
return 1;
}
public void doProgress(String value){
publishProgress(value);
}
@Override
protected void onPostExecute(Integer result) {
progressDialog.dismiss();
super.onPostExecute(result);
}
protected void onProgressUpdate(String... progress) {
progressDialog.setProgress(Integer.parseInt(progress[0]));
}
protected void addEvent(String title, String start, String end,
String duration, String organizer, String location, long id) {
SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
long startInMillis = 0, endInMillis = 0;
Date startDate, endDate;
try {
startDate = format.parse(start);
endDate = format.parse(end);
startInMillis = startDate.getTime();
endInMillis = endDate.getTime();
} catch (ParseException e1) {
e1.printStackTrace();
}
TimeZone timeZone = TimeZone.getDefault();
ContentResolver cr = getContentResolver();
ContentValues values = new ContentValues();
values.put(CalendarContract.Events.EVENT_TIMEZONE, timeZone.getID());
values.put(CalendarContract.Events.DTSTART, startInMillis);
values.put(CalendarContract.Events.DTEND, endInMillis);
values.put(CalendarContract.Events.TITLE, title);
values.put(CalendarContract.Events.EVENT_LOCATION, "Location: " + location);
values.put(CalendarContract.Events.CALENDAR_ID, 1);
Uri uri = cr.insert(CalendarContract.Events.CONTENT_URI, values);
ContentUris.withAppendedId(uri, id);
}
}
}
这里是负责下载和解析的类:
public class XMLParser {
public String getXmlFromUrl(String url, AddCoursesToCalendar.GetDataTask task) {
String xml = null;
try {
int count;
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
long lenghtOfFile = httpEntity.getContentLength();
byte data[] = new byte[1024];
long total = 0;
while ((count = httpEntity.getContent().read(data)) != -1) {
total += count;
task.doProgress(""+(int)((total*100)/lenghtOfFile));
}
xml = EntityUtils.toString(httpEntity, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return xml;
}
public Document getDomElement(String xml, AddCoursesToCalendar.GetDataTask task) {
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
StringReader reader = new StringReader(xml);
is.setCharacterStream(reader);
doc = db.parse(is);
} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
return doc;
}
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
public final String getElementValue(Node elem) {
Node child;
if (elem != null) {
if (elem.hasChildNodes()) {
for (child = elem.getFirstChild(); child != null; child = child
.getNextSibling()) {
if (child.getNodeType() == Node.TEXT_NODE) {
return child.getNodeValue();
}
}
}
}
return "";
}
}
我希望我的第一篇文章的风格是好的,如果不是请告诉我。先感谢您