Android:片段加载速度太慢
Android: Fragment is too slow at loading
我已经尝试解决这个问题好几个星期了,但我无法解决,所以我真的希望能在这里找到帮助。
我正在创建一个与网络服务器协同工作的应用程序,因此有很多查询要做。在我名为 "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()".
提前致谢...:-)
我想我找到了自己的解决方案。我只是错误地使用了我的 asnyc 函数。如果我在 onPostExecute() 中执行所有操作,该应用程序运行良好。之前,我在doinbackground回调中做了主要部分,所以它莫名其妙地卡住了。
我已经尝试解决这个问题好几个星期了,但我无法解决,所以我真的希望能在这里找到帮助。
我正在创建一个与网络服务器协同工作的应用程序,因此有很多查询要做。在我名为 "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()".
提前致谢...:-)
我想我找到了自己的解决方案。我只是错误地使用了我的 asnyc 函数。如果我在 onPostExecute() 中执行所有操作,该应用程序运行良好。之前,我在doinbackground回调中做了主要部分,所以它莫名其妙地卡住了。