Volley和Asynctask响应都很慢

时间:2015-01-23 16:13:48

标签: android android-asynctask android-volley

问题

我即将完成一个大项目,我发现在从服务器下载数据并显示数据时,我的应用程序在3G上很慢。我上周读到了Volley,我很快就实现了它,看它是否比Asynctask更快。不完全是。这两种方法的响应在3G上都非常慢(WIFI很快),当我说非常慢时,我的意思是用户需要等待0.8-3.5秒,直到数据显示

所以我检查了代码,发现问题在于响应。在Android端收到响应后, ListView填充和数据显示在0.3秒下发生,但在收到响应之前,用户需要等待。

我正在使用带有HTTPS连接的VPS。

我尝试了什么

  1. 我尝试过设置

    HttpProtocolParams.setVersion(httpparams,HttpVersion.HTTP_1_1);

  2. httppost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
    

    基于this帖子。

    1. 我尝试删除整个数据库连接和查询,只是在php中发布响应意味着整个内容是脚本是这样的:
    2. echo" [[{...查询内容}]]

      在这种情况下,响应速度要快得多(但我不能说100%)!

      1. 我尝试将响应(尝试2号)放在HTTP共享服务器上(所以不是查询,因为我不想模拟数据库),我不知道这是否意味着除了响应在HTTP和HTTPS服务器上的响应大约是0.8秒。
      2. 这是我的代码 使用Asynctask

        public class DownloadBucket extends AsyncTask<String, Void, ArrayList<String>> {
        
        
        
            @Override
            protected void onPostExecute(ArrayList<String> result) {            
            myadapter = new MyAdapter(BucketUsers.this, arr_users_id, arr_users_username, arr_users_firstname, arr_users_lastname, arr_users_photo, arr_users_followed);
        
                lv.setAdapter(myadapter);
        }
            actionBar.show();
        
            @Override
            protected void onPreExecute() { 
                actionBar.hide();
        
        }
        
            @Override
            protected ArrayList<String> doInBackground(String... params) {
        
                try{
                    HttpParams httpparams = new BasicHttpParams();
                    //HttpProtocolParams.setVersion(httpparams, HttpVersion.HTTP_1_1);
                    HttpClient httpclient = new DefaultHttpClient();
        
                    HttpPost httppost = null;
                    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
                    Log.i("At bucketid", bucketid + "");
                    Log.i("At session_userid", session_userid + "");
                    nameValuePairs.add(new BasicNameValuePair("session_userid", session_userid));
                    nameValuePairs.add(new BasicNameValuePair("bucketid", bucketid));
                    nameValuePairs.add(new BasicNameValuePair("start", params[1]));
                    nameValuePairs.add(new BasicNameValuePair("finish", params[2]));
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        
                    httppost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
        
                    HttpResponse response = httpclient.execute(httppost);
                    HttpEntity entity = response.getEntity();
                    is = entity.getContent();
                    }catch(Exception e){
                            Log.e("error", "Error in http connection "+e.toString());
                    }
                    //convert response to string
                    try{
                            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                            StringBuilder sb = new StringBuilder();
                            String line = null;
                            while ((line = reader.readLine()) != null) {
                                    sb.append(line + "\n");
                            }
                            is.close();
                            Log.i("sb", sb + "");
                            Bresult=sb.toString();
                            Log.i("Bresult", Bresult + "");
                    }catch(Exception e){
                            Log.e("error", "Error converting result "+e.toString());
                    }
        
                    ArrayList<String> result = new ArrayList<String>();
        
                    try {
                        jArray = new JSONArray(Bresult);
                        for(int i=0;i<jArray.length();i++){
                            JSONArray innerJsonArray = jArray.getJSONArray(i);
                            for(int j=0;j<innerJsonArray.length();j++){  
                                JSONObject jsonObject = innerJsonArray.getJSONObject(j);
        
                                arr_users_id.add(jsonObject.getString("ID"));
                                arr_users_username.add(jsonObject.getString("USERNAME"));
                                arr_users_firstname.add(jsonObject.getString("NAME"));
                                arr_users_lastname.add(jsonObject.getString("NAME2"));
                                arr_users_photo.add(jsonObject.getString("PHOTO"));
                                arr_users_followed.add(jsonObject.getString("DO_I_FOLLOW_HIM"));
        
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
        
                return null;
            }
        }
        

        使用Volley

        private void makeJsonArrayRequest(final String list, final String start, final String finish) {
        
            StringRequest postReq = new StringRequest(Method.POST, loadusers, new Response.Listener<String>() {
        
                @Override
                public void onResponse(String response) {
        
                    Log.i("VOLLEY", response);
        
        //Here we are already at 0.8-3.5 seconds!
        //Everything after this happens very fast
        
                    if (response.length() > 10) {
                        try {
                            jArray = new JSONArray(response);
                            for(int i=0;i<jArray.length();i++){
                                JSONArray innerJsonArray = jArray.getJSONArray(i);
                                for(int j=0;j<innerJsonArray.length();j++){  
                                    JSONObject jsonObject = innerJsonArray.getJSONObject(j);
        
                                    arr_users_id.add(jsonObject.getString("ID"));
                                    arr_users_username.add(jsonObject.getString("USERNAME"));
                                    arr_users_firstname.add(jsonObject.getString("NAME"));
                                    arr_users_lastname.add(jsonObject.getString("NAME2"));
                                    arr_users_photo.add(jsonObject.getString("PHOTO"));
                                    arr_users_followed.add(jsonObject.getString("DO_I_FOLLOW_HIM"));
        
                                }
                            }
        
                            pb.setVisibility(View.GONE);
                            loading_ll.setVisibility(View.GONE);
                            llMain.setVisibility(View.VISIBLE);
        
                            if (arr_users_id.size() < 31) {
                                myadapter = new MyAdapter(BucketUsers.this, arr_users_id, arr_users_username, arr_users_firstname, arr_users_lastname, arr_users_photo, arr_users_followed);
                                lv.setAdapter(myadapter);
                            } else {
                                myadapter.notifyDataSetChanged();
                            }
                            actionBar.show();
        
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
        
            } else {
                        all_items_downloaded = true;
                        lv.removeFooterView(loadMoreView);
                    }
        
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                   // System.out.println("Error ["+error+"]");
                    Log.i("VOLLEY_ERROR", error.toString());
                }
            }) {
        
                @Override
                protected Map<String, String> getParams() {
                    Map<String, String> params = new HashMap<String, String>();
                    params.put("session_userid", session_userid);
                    params.put("bucketid", bucketid);
                    params.put("start", start);
                    params.put("finish", finish);
                    return params;
                }
        
            };
        
            postReq.setShouldCache(false);
            AppController.getInstance().addToRequestQueue(postReq);
        }
        

        PHP

        <?php
        require_once($_SERVER['SERVER_ROOT'].'mysecretdbdata.php');
        $response = array();
        
            try {
                $conn = new PDO("mysql:host=$host;dbname=$database", $dbusername, $dbpassword, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
                $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            } catch(PDOException $e) {
                echo 'ERROR: ' . $e->getMessage();
                $response = '0';
        
        [QUERY]
        
        print(json_encode($output));
        ?>
        

        这是正常的吗?有什么方法可以加快速度吗?我不知道它是如何工作的,但是例如单击对象时使用Pinterest,将立即显示图像和数据。用户根据热门应用程序进行预测,甚至在使用我自己的应用程序时也不喜欢。

0 个答案:

没有答案