1

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

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();
           }

       }
   }
}
4

2 回答 2

1

我猜你错过了重点AsyncTask

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

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

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

 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.
 }

然后在您的“受保护地图 doInBackground(String... urls)”上完成网络操作,创建 JsonArray,创建一个Map<String,CompanyData>,循环遍历数组,创建 CompanyData 对象并将它们放入 Map 并将地图返回到您的protected void onPostExecute(Map<String,CompanyData> result)内部和内部执行后它只是将此结果传递给 UI。

快乐编码。

于 2013-01-09T12:05:35.457 回答
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();

    }

}
于 2013-09-23T01:39:08.123 回答