从MySQL下载Android App中数据的高效方法

时间:2013-01-09 11:45:38

标签: java android mysql json download

我只是想知道我的代码在下载方面是否合适。我的应用程序需要来自数据库的大量数据,因此快速下载时间至关重要。下载时间还可以,但我认为它可以更有效地编程。你能看看这个吗?这个类下载了许多不同的公司,当下载时,它们被放入与其类别相对应的HashMap中。下载完成后,返回一个包含多个Hashmaps(类别)的HashMap,并在这些Hashmaps中返回下载的数据。不介意实际的工作流程,但请专注于此类下载数据的方式。有没有办法更快地做到这一点?

public class CompanyDAO {

    private static Controller delegate;
    private static String companyUrl = "http:// URL HERE";

    private Map<Object, Object> companyMap = new HashMap<Object, Object>();
    private Map<String, Integer> pinMap = new HashMap<String, Integer>();


    public CompanyDAO (Controller _delegate, Map<String, Integer> map) {
        delegate = _delegate; //reference to controller
        pinMap = map;

    }

    public void getCompanyData(ArrayList<Object> categoriesArray) {
        for (int i = 0; i < categoriesArray.size(); i++) {
            Map<String, Object> categoriesInMap = new HashMap<String, Object>();
            //ArrayList<Object> categoriesInMapArray = new ArrayList<Object>();
            companyMap.put(categoriesArray.get(i), categoriesInMap);
        }
        this.downloadCompanyData();
    }

    private void downloadCompanyData() {

        companyUrl = companyUrl + delegate.ID;
       try {
           new DownloadCompanyData().execute(companyUrl).get(10000, TimeUnit.MILLISECONDS);
       } catch (InterruptedException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       } catch (ExecutionException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       } catch (TimeoutException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }
    }

   private class DownloadCompanyData extends AsyncTask<String, Void, String> {
       @Override
       protected String doInBackground(String... urls) {
           String response = "";
           for (String url : urls) {
               DefaultHttpClient client = new DefaultHttpClient();
               HttpGet httpGet = new HttpGet(url);
               try {
                   HttpResponse execute = client.execute(httpGet);
                   InputStream content = execute.getEntity().getContent();

                   BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
                   String s = "";
                   while ((s = buffer.readLine()) != null) {
                       response += s;
                   }

               } catch (Exception e) {
                   e.printStackTrace();
               }
           }
           return response;
       }

       @SuppressWarnings("unchecked")
       @Override
       protected void onPostExecute(String result) {



           JSONArray companyDataArray;

           try {
               companyDataArray = new JSONArray(result);

               for(int i=0;i<companyDataArray.length();i++){
                   JSONObject id = companyDataArray.getJSONObject(i);
                   String catName = id.getString(Controller.CAT_NAME);

                   if (companyMap.get(catName) != null) {
                       Markers marker = new Markers(new LatLng(id.getDouble("latitude"), id.getDouble("longitude")), id.getString(Controller.CAT_NAME), id.getString(Controller.ID), id.getString(Controller.SUBSCRIPTION), pinMap.get(catName), id.getString(Controller.TITLE), id.getString(Controller.COMPANY_NAME), id.getString(Controller.WWW), id.getString(Controller.STREET), id.getString(Controller.HOUSE_NUMBER), id.getString(Controller.HOUSE_ADD));

                       ((Map<String,Object>) companyMap.get(catName)).put(id.getString(Controller.TITLE), marker.markerInformationMap);

                   }

               }
               delegate.setCompanyHashMap(companyMap);

           } catch (JSONException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
           }

       }
   }
}

2 个答案:

答案 0 :(得分:1)

我猜你错过了AsyncTask

的观点

它应该在doInBackground()中完成所有工作,然后使用onPostExecute将其传递到用户界面。

但你正在做的是在doInBackground上进行网络操作并在onPostExecute上进行数据解析。

此外,JSON对象是需要进一步解析的原始数据。你应该在后台进行所有解析。例如,假设您的companyData是地址,电话号码,大小和名称。你可以有这样一个类(p.s.我在没有测试的情况下编写所有这些,这里会有一点错误,但你会得到这个想法):

 public class CompanyData{
     private String name, address, phone;
     private int size;
     public CompanyData(JsonObject jo){
         name = jo.getString("name");
         address = jo.getString("address");
         phone = jo.getString("phone");
         size = jo.getInt("size");
     }
     // put a bunch of get methods here...
     // getName(), getAddress(), etc.
 }

然后在你的'protected Map doInBackground(String ... urls)'你完成网络操作,创建JsonArray,创建一个Map<String,CompanyData>,遍历数组创建CompanyData对象并将它们放入Map中将地图返回到protected void onPostExecute(Map<String,CompanyData> result)并在帖子内执行,只需将此结果传递给用户界面。

快乐的编码。

答案 1 :(得分:0)

我总是这样做......

...
private ProgressDialog pDialog; 
ArrayList<HashMap<String, String>> CompanyList;
JSONParser jParser = new JSONParser();
JSONArray Company = null;
static String url_all_company = "http://your_site/files.php";
....

private class CompanyData extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Load data..");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected Void doInBackground(Void... params) {
        CompanyList = new ArrayList<HashMap<String, String>>();

        // Building Parameters if any.. to fetching all data, don't declare any param
        List<NameValuePair> param = new ArrayList<NameValuePair>();
        param.add(new BasicNameValuePair("uid", uid));

        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(url_all_company, "POST", param);

        // Check your log cat for JSON reponse
        Log.d("All Company: ", json.toString());

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // Company found
                // Getting Array of Company
                Company = json.getJSONArray(TAG_COMPANIES);

                // looping through All Company
                for (int i = 0; i < Company.length(); i++) {
                    JSONObject json = Company.getJSONObject(i);

                    // Storing each json item in variable
                    String id = json.getString(TAG_GID);
                    String name = json.getString(TAG_NAME);
                    String jml = json.getString(TAG_EMPLOYEE);
                    String deskripsi = json.getString(TAG_DESKRIPSI);
                    String logo = json.getString(TAG_LOGO);

                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    map.put(TAG_GID, id);
                    map.put(TAG_NAME, name);
                    map.put(TAG_EMPLOYEE, jml);
                    map.put(TAG_DESKRIPSI, deskripsi);
                    map.put(TAG_LOGO, logo);

                    // adding HashList to ArrayList
                    CompanyList.add(map);

                }
            } else {
                // no CompanyList found

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;    

    }   

    @Override
    protected void onPostExecute(Void args) {
         list=(ListView)findViewById(R.id.list);

         // Getting adapter by passing data ArrayList
         adapter=new LazyAdapter(MainActivity.this, CompanyList);        
         list.setAdapter(adapter);

         pDialog.dismiss();

    }

}