Android:Fragment加载速度太慢

时间:2015-07-27 00:28:01

标签: android performance user-interface networking fragment

我正试图解决这个问题好几个星期但是我无法解决它所以我真的希望在这里找到帮助。

我正在创建一个与网络服务器配合使用的应用,因此有很多查询要做。在我的Fragment中,命名为“tab_profile”,我调用2个API查询,还有许多其他人在我的自定义ListView上加载图像。

所以我的问题是这个片段在加载(井连接)时需要1-2秒,甚至在连接不良时崩溃,例如3G。

代码看起来像这样(当然是短版):

public class tab_profile extends Fragment implements AdapterView.OnItemClickListener {
private String imagepath = null;
private ImageView imageview = null;
View rootView = null;
private ArrayList<PollItem> arrayPolls;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    rootView = inflater.inflate(R.layout.tab_profile, container, false);

    final Button button_follower    = (Button) rootView.findViewById(R.id.button_follower);
    final Button button_following   = (Button) rootView.findViewById(R.id.button_following);
    final TextView text_username    = (TextView) rootView.findViewById(R.id.text_username);
    imageview                       = (ImageView) rootView.findViewById(R.id.img_own_pp);
    final Session session           = new Session(getActivity());
    final Network network           = new Network(getActivity());

    text_username.setText(session.getValue("username"));
    if(session.getValue("username").length() < 3) {
        getActivity().finish();
        return null;
    }

    JSONArray arr;
    String res = network.POST("{\"token\":\"" + session.getValue("token") + "\"}", "profile.php");
    try {
        JSONObject obj = new JSONObject(res);
        arr = obj.getJSONArray("data");

        if (!obj.get("status").equals("false")) {

            button_follower.setText("Follower\n" + arr.getJSONObject(0).getString("follower"));
            button_following.setText("Following\n" + arr.getJSONObject(0).getString("following"));

            if (arr.getJSONObject(0).getString("pp").equals("true")) {
                network.setImageViewImage(imageview, "usermedia/pp/" + session.getValue("id"));
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    arrayPolls = new ArrayList<>();
    getList();

    //listeners here

    return rootView;
}

然后是第二个主要函数,叫做“getList()”:

    public void getList() {
    Network netwok = new Network(getActivity());
    Session session = new Session(getActivity());

    String resp = netwok.POST("{\"token\":\""+session.getValue("token")+"\","+
            "\"get\":\"true\""+"}","mypoll.php");

    try {
        JSONObject obj = new JSONObject(resp);
        JSONArray arr = obj.getJSONArray("data");

        if(obj.get("status").equals("false")) {
            return;
        }

        arrayPolls.clear();

        for(int i=0; i<arr.length(); i++) {
            JSONObject ot = arr.getJSONObject(i);
            PollItem tmp = new PollItem(ot.getInt("ID"),ot.getInt("userid"),
                    ot.getString("description"),ot.getString("username"));
            arrayPolls.add(tmp);
        }
    }
    catch (JSONException e) {
        e.printStackTrace();
    }

    ListView list_poll_item = (ListView) rootView.findViewById(R.id.list_friend_poll);
    PollOverviewItemAdapter adapter = new PollOverviewItemAdapter(getActivity(), arrayPolls, tab_profile.this, imageview);
    list_poll_item.setAdapter(adapter);
    list_poll_item.setOnItemClickListener(this);
}

我的查询由此Async发送。功能:

    private class POST_REQUEST extends AsyncTask<String, Integer, String>{
    protected String doInBackground(String... params) {
        String line;
        try {  
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(params[0]);

            ArrayList<NameValuePair> postParameters;
            postParameters = new ArrayList<>();

            postParameters.add(new BasicNameValuePair("json", query));

            httpPost.setEntity(new UrlEncodedFormEntity(postParameters));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            line = EntityUtils.toString(httpEntity);

        } catch (UnsupportedEncodingException e) {
            line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
        } catch (MalformedURLException e) {
            line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
        } catch (IOException e) {
            line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
        }
        return line;
    }

    protected void onPostExecute(String result) {
        super.onPostExecute(result);
    }
}

和最后一个功能:

    public class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
      ImageView bmImage;

      public DownloadImageTask(ImageView bmImage) {
          this.bmImage = bmImage;
      }

      protected Bitmap doInBackground(String... urls) {
          String urldisplay = urls[0];
          Bitmap mIcon11 = null;
          try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
          } catch (Exception e) {
              Log.e("Error", e.getMessage());
              e.printStackTrace();
          }
          return mIcon11;
      }
      protected void onPostExecute(Bitmap result) {
          bmImage.setImageBitmap(result);
      }
}

所以我认为这些是我的代码的重要部分。我真的希望找到解决这个问题的方法。我已经多次尝试加载我的UI,然后加载来自服务器的数据,但它是相同的。我通过使用“onStart()”尝试了这个。

提前致谢......: - )

1 个答案:

答案 0 :(得分:1)

我想我找到了自己的解决方案。我只是使用了我的asnyc函数错误。如果我在onPostExecute()中执行所有操作,该应用程序运行良好。之前,我在doinbackground回调中做了主要部分,所以它不知何故被卡住了。