public static final int downloadDone = 1; // 用户model数组 ArrayList<Loginer> loginers = new ArrayList<>(); // hander Handler downloadLoginerHandler = new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what){ case downloadDone: Toast.makeText(MyApplication.getApplication(), "同步用户数据成功", Toast.LENGTH_SHORT).show(); break; } super.handleMessage(msg); } }; // 从服务器更新loginer数据 public void downloadData() throws IOException, XmlPullParserException { new Thread(new Runnable() { @Override public void run() { String url = "http://222.169.11.226:7000/WebServiceAndroidcm.asmx/getloginerInfo"; MyHTTP myHTTP = new MyHTTP(); Map map = new HashMap(); map.put("pw", "0535deer"); try { String string = myHTTP.doPost(url, map); System.out.println("成功::::"+string); String newString = string.replace("<?xml version="1.0" encoding="utf-8"?><string xmlns="http://tempuri.org/">{"Result":"1","Value":", ""); String lastString = newString.replace("}</string>", ""); // 将字符串进行解析 JsonParser jsonParser = new JsonParser(); // 将jsonstring转换为jaonArray JsonArray jsonArray = jsonParser.parse(lastString).getAsJsonArray(); // gson Gson gson = new Gson(); // for 循环遍历josnarray for (JsonElement loginerElement : jsonArray) { Loginer loginer = gson.fromJson(loginerElement, Loginer.class); loginers.add(loginer); System.out.println("大小是"+loginers.size()); } // 获取dao对象 loginerDao = MyApplication.getApplication().getDaoSession().getLoginerDao(); // 新建一个Message对象 Message msg = new Message(); // 通过for循环插入数据到数据库 for (int i = 0; i < loginers.size(); i++) { System.out.println("终于找到你:"+loginers.get(i).getLoginer_code()); long result = loginerDao.insertOrReplace(loginers.get(i)); System.out.println("结果是:"+result); // 如果全部替换或插入成功, 则弹出更新用户数据成功 if (result == loginers.get(loginers.size() - 1).getLoginer_id()) { // 发送同步完成的消息到message msg.what = downloadDone; downloadLoginerHandler.sendMessage(msg); System.out.println("到最后一条了"); } } } catch (Exception e) { e.printStackTrace(); } } }).start(); }
调用:
// 开始更新loginers数据的数据 try { downloadData(); } catch (IOException e) { e.printStackTrace(); } catch (XmlPullParserException e) { e.printStackTrace(); }
截图: