【问题标题】:Too much time consumed to retrieve data from server从服务器检索数据花费了太多时间
【发布时间】:2018-11-03 10:24:18
【问题描述】:

我正在开发一个从 php 服务器检索数据的应用程序。我从 php 服务器接收一个 json 数组。当我在 android 模拟器中运行 apk 时,它可以完美运行,但是当我在真正的 android 手机上运行这个 apk 时会出现问题。检索数据需要太多时间。我搜索了很多资源,但我无法解决这个问题。请任何人给我一些提示来解决这个问题。提前致谢。

CostForSecretCloseMem 类

public class CostForSecretCloseMem extends AppCompatActivity
{

        private ListView listView;
        private RelativeLayout emptyView;

        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.costs_layout);
                initComponent();
        }

        @SuppressLint("SetTextI18n")
        private void initComponent()
        {
                emptyView = findViewById(R.id.empty_view);
                SharedPreferenceData sharedPreferenceData = new SharedPreferenceData(this);
                CheckInternetIsOn internetIsOn = new CheckInternetIsOn(this);
                listView = findViewById(R.id.list);
                if(internetIsOn.isOnline())
                {
                        try {
                                String DATA = URLEncoder.encode("userName", "UTF-8") + "=" + URLEncoder.encode(sharedPreferenceData.getCurrentUserName(), "UTF-8");
                                //importantData.getAllShoppingCost(getResources().getString(R.string.shoppingCost), DATA,infoInterfaces);
                                TestBackground testBackground = new TestBackground(this);
                                testBackground.setOnResultListener(infoInterfaces);
                                testBackground.execute(getResources().getString(R.string.shoppingCost),DATA);
                        } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                        }

                }
        }

        //process shopping only_show_cost json data
        private void processJsonData(String result)
        {
                List<CostModel> costList = new ArrayList<>();
                int count=0;
                String name,taka,date,id;
                try {
                        JSONObject jsonObject = new JSONObject(result);
                        JSONArray jsonArray = jsonObject.optJSONArray("costList");

                        while (count<jsonArray.length())
                        {
                                JSONObject jObject = jsonArray.getJSONObject(count);
                                id = jObject.getString("id");
                                name = jObject.getString("name");
                                taka = jObject.getString("taka");
                                date = jObject.getString("date");

                                costList.add(new CostModel(id,name,taka,date,""));
                                count++;
                        }

                        if(costList.isEmpty())
                                listView.setEmptyView(emptyView);
                        else
                                emptyView.setVisibility(View.INVISIBLE);

                        CostAdapter adapter = new CostAdapter(this, costList);
                        listView.setAdapter(adapter);
                } catch (JSONException e) {
                        e.printStackTrace();
                }
        }

        //get all shopping list
        OnAsyncTask infoInterfaces = new OnAsyncTask() {
                @Override
                public void onSuccess(final String result) {
                        runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                        if(result!=null)
                                                processJsonData(result);
                                }
                        });
                }
        };
}

异步任务

public class TestBackground extends AsyncTask<String,Void,String>
{
     private Context context;
     private OnAsyncTask onAsyncTaskInterface;

     public TestBackground(Context context)
     {
          this.context = context;
     }


     //success result
     public void setOnResultListener(OnAsyncTask onAsyncResult) {
          if (onAsyncResult != null) {
               this.onAsyncTaskInterface = onAsyncResult;
          }
     }

     @Override
     public String doInBackground(String... params) {

          String result = "";
          String fileName = params[0];
          String postData = params[1];

          try {
               URL url = new URL(fileName);
               HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
               httpURLConnection.setRequestMethod("POST");
               OutputStream outputStream = httpURLConnection.getOutputStream();
               OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, "UTF-8");
               BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);

               bufferedWriter.write(postData);
               bufferedWriter.flush();
               bufferedWriter.close();
               outputStream.close();
               InputStream inputStream = httpURLConnection.getInputStream();
               BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));

               String line;

               while ((line= bufferedReader.readLine())!=null)
                    result = line;

               bufferedReader.close();
               inputStream.close();
               httpURLConnection.disconnect();
               onAsyncTaskInterface.onSuccess(result);

          } catch (MalformedURLException e) {
               e.printStackTrace();
          } catch (IOException e) {
               e.printStackTrace();
          }catch (Exception e)
          {
               e.printStackTrace();
          }
          return result.toString();
     }


      public interface OnAsyncTask {
                void onSuccess(String message);
        }
}

php代码

<?php

    require"connection.php";
    require"getSession.php";

    $userName = $_POST["userName"];
    $session = new Sessions();
    $month = $session->session($userName);

    $sql = "SELECT GroupID FROM member_info WHERE UserName LIKE '$userName';";
    $result = mysqli_query($conn,$sql);

    if($result->num_rows>0)
    {
        while($row=mysqli_fetch_array($result))
        {
            if($row["GroupID"]!="Null")
                getCostList($row["GroupID"],$month);
        }
    }

    function getCostList($value,$month)
    {
        require"connection.php";
        $sql = "SELECT * FROM cost WHERE groupName LIKE '$value' and cMonth LIKE '$month';";
        $result = mysqli_query($conn,$sql);

        $response = array();

        if($result->num_rows>0)
        {
            while($row=mysqli_fetch_array($result))
                array_push($response,array("id"=>$row[0],"name"=>$row[1],"taka"=>$row[4],"date"=>$row[5]));

            echo json_encode(array("costList"=>$response));
        }
    }

    $conn->close();
?>

【问题讨论】:

  • 使用 wifi 或移动连接?你的服务器在哪里运行?你可以给出数字!
  • onAsyncTaskInterface.onSuccess(result); 通常会在 onPostExecute() 中调用接口。然后你就可以摆脱 runOnUiThread()。
  • 我也这样做了,但出现同样的问题......
  • 我强烈建议使用 Volley 或 Retrofit,而不是直接使用 HttpUrlConnection,这样可以最小化代码并摆脱 AsyncTask,它会显着提高速度。我曾经和你做同样的事情,当我切换到 volley 时,http 请求变得更快了。
  • 是 PHP 脚本返回的时间过长还是连接速度慢?

标签: php android mysql json android-asynctask


【解决方案1】:

你在代码中犯了很多错误。

  1. 不建议使用 SELECT * 来获取数据,您知道所需的所有数据是什么,因此请具体选择哪些数据(id、name、taka、date))。
  2. 从查询中选择后使用 while 循环,您应该使用 fetch all 并按原样返回数据。
  3. 使用 JOIN 查询获取单个查询中的数据。

如果你使用上述方法,它会非常快。

 require"connection.php";

上面一行使用了两次是错误的,而是使用全局变量来获取函数内部的数据库连接。

【讨论】:

  • 他们的数据量大还是很正常?
猜你喜欢
  • 1970-01-01
  • 2017-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-15
  • 2020-07-23
  • 2013-07-11
相关资源
最近更新 更多