问题描述
- 在android上的XML文件,怎么样从远程服务器上获取
- 需要在远程服务器上读取XML文件,然后再修改本地android上的数据。我用
XmlPullParser
读取数据。XmlPullParser users; try { URL xmlUrl = new URL(""http://xx.xx.xx.xx/1.xml""); users = XmlPullParserFactory.newInstance().newPullParser(); users.setInput(xmlUrl.openStream() null); }
怎么样在安卓上修改?
解决方案
用下面的代码,他会覆盖你从网上下载的文件:
public static boolean downloadFile(String fileToDownload File newPath String newFileName) { try { URL url = new URL(fileToDownload); HttpURLConnection urlConnection = (HttpURLConnection) url .openConnection(); urlConnection.setRequestMethod(""GET""); urlConnection.setDoOutput(true); urlConnection.connect(); if (!newPath.isDirectory()) { CreateLog.createFolder(newPath.toString()); } File file = new File(newPath.toString() + ""/"" + newFileName); if (!file.isFile()) { CreateLog.writeLogToFile(newPath.toString() + newFileName%TEMP%""); } FileOutputStream fileOutput = new FileOutputStream(file); InputStream inputStream = urlConnection.getInputStream(); byte[] buffer = new byte[1024]; int bufferLength = 0; while ((bufferLength = inputStream.read(buffer)) > 0) { fileOutput.write(buffer 0 bufferLength); } fileOutput.close(); return true; } catch (MalformedURLException e) { CreateLog.addToLog(e.toString()); return false; } catch (IOException e) { CreateLog.addToLog(e.toString()); return false; } }public static void createFolder(String filePath) { File createFolder = new File(filePath); createFolder.mkdirs();}
更简单的方式是Asynctask,代码是在一个新线程里:
private class GetProblems extends AsyncTask<String Integer String> { @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected String doInBackground(String... params) { for (String myUrl : params) { try { URL url = new URL(myUrl); URLConnection ucon = url.openConnection(); ucon.setRequestProperty(""Accept""application/xml""); InputStream is = ucon.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); ByteArrayBuffer baf = new ByteArrayBuffer(50); int current = 0; while ((current = bis.read()) != -1) { baf.append((byte) current); } String str = new String(baf.toByteArray()UTF8""); return str; } catch (MalformedURLException e) { CreateLog.addToLog(""[GetProblems] "" + e.toString()); } catch (IOException e) { CreateLog.addToLog(""[GetProblems] "" + e.toString()); } } return ""error""; } @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); // updateProgressBar(values[0]); } @Override protected void onPostExecute(String result) { super.onPostExecute(result); ...write result to a file } }
运行AsyncTask:
new GetProblems().execute(""http://myurl.com/xmlfile.xml"");
解决方案二:
流程是:数据获取->数据解析->数据显示
你的问题是修改本地的数据?你不觉这是个泛型描述吗
本地数据千千万,要改数据库,要改一个textView或是来个动态布局等等
解析xml需要你对其Node了解(xml节点)
解决方案三:
1、访问服务器的xml文件
2、解析xml文件,获取解析的数据
3、通过解析的数据来修改本地数据(数据库 or 数据文件 or others)
思路很清晰,不知道楼主的迷茫在哪?
时间: 2024-12-24 00:13:33