我创建了一个包含三个活动的Android应用程序, MainActivity - > SongActivity - > DownloadActivity 即可。 MainActivity和SongActivity是ListViews,它从mysql数据库中获取项目列表。当我通过按后退按钮从SongActivity导航回MainAcitivty时,ListView再次获取数据,这使得应用程序导航变慢。有解决方案吗?
MainActivity.java
package com.example.telugump3;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity{
Activity context;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
ProgressDialog pd;
CustomAdapter adapter;
ListView listProduct;
ArrayList<String> records;
protected void onCreate(Bundle savedInstanceState) {
//TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context=this;
records=new ArrayList<String>();
listProduct=(ListView)findViewById(R.id.product_list);
adapter=new CustomAdapter(context, R.layout.list_item,R.id.pro_name, records);
listProduct.setAdapter(adapter);
listProduct.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long id){
String sText = ((TextView) v.findViewById(R.id.pro_name)).getText().toString();
Intent songIntent = new Intent(getApplicationContext(), SongActivity.class);
songIntent.putExtra("movie_name", sText );
startActivity(songIntent);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
//create a LayoutTransition object
return true;
}
public void onStart(){
super.onStart();
//execute background task
BackTask bt=new BackTask();
bt.execute();
}
//background process to make a request to server and list product information
private class BackTask extends AsyncTask<Void,Void,Void>{
protected void onPreExecute(){
super.onPreExecute();
pd = new ProgressDialog(context);
pd.setTitle("Retrieving data");
pd.setMessage("Please wait.");
pd.setCancelable(true);
pd.setIndeterminate(true);
pd.show();
}
protected Void doInBackground(Void...params){
InputStream is=null;
String result="";
try{
records.clear();
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://necrecords.16mb.com/getproducts.php");
response=httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
if(pd!=null)
pd.dismiss(); //close the dialog if error occurs
Log.e("ERROR",e.getMessage());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("ERROR", "Error converting result "+e.toString());
}
//parse json data
try{
JSONArray jArray =new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
String record=json_data.getString("pname")+"__"+json_data.getInt("uprice");
records.add(record);
}
}
catch(Exception e){
Log.e("ERROR", "Error pasting data "+e.toString());
}
return null;
}
protected void onPostExecute(Void result){
if(pd!=null) pd.dismiss(); //close dialog
adapter.notifyDataSetChanged(); //notify the ListView to get new records
}
}
}
SongActivity.java
package com.example.telugump3;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
public class SongActivity extends Activity{
Activity context;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
ProgressDialog pd;
CustomAdapter adapter;
ListView listProduct;
ArrayList<String> records;
String mname;
protected void onCreate(Bundle savedInstanceState) {
//TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.song_activity);
context=this;
records=new ArrayList<String>();
listProduct=(ListView)findViewById(R.id.product_list);
adapter=new CustomAdapter(context, R.layout.newlist_item,R.id.pro_name, records);
listProduct.setAdapter(adapter);
TextView songtitle = (TextView)findViewById(R.id.movietitle);
Intent iin= getIntent();
Bundle b = iin.getExtras();
if(b!=null)
{
mname =(String) b.getString("movie_name");
songtitle.setText(mname);
}
listProduct.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long id){
String sText = ((TextView) v.findViewById(R.id.pro_name)).getText().toString();
Intent songIntent = new Intent(getApplicationContext(), DownloadActivity.class);
songIntent.putExtra("song_name", sText );
startActivity(songIntent);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
//create a LayoutTransition object
return true;
}
public void onStart(){
super.onStart();
//execute background task
BackTask bt=new BackTask();
bt.execute();
}
//background process to make a request to server and list product information
private class BackTask extends AsyncTask<Void,Void,Void>{
protected void onPreExecute(){
super.onPreExecute();
pd = new ProgressDialog(context);
pd.setTitle("Retrieving data");
pd.setMessage("Please wait.");
pd.setCancelable(true);
pd.setIndeterminate(true);
pd.show();
}
protected Void doInBackground(Void...params){
InputStream is=null;
String result="";
try{
records.clear();
String query = URLEncoder.encode(mname, "utf-8");
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://necrecords.16mb.com/getsongslist.php?password="+query);
response=httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
if(pd!=null)
pd.dismiss(); //close the dialog if error occurs
Log.e("ERROR",e.getMessage());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("ERROR", "Error converting result "+e.toString());
}
//parse json data
try{
JSONArray jArray =new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
String record=json_data.getString("allsongs")+"__"+json_data.getString("test");
records.add(record);
}
}
catch(Exception e){
Log.e("ERROR", "Error pasting data "+e.toString());
}
return null;
}
protected void onPostExecute(Void result){
if(pd!=null) pd.dismiss(); //close dialog
adapter.notifyDataSetChanged(); //notify the ListView to get new records
}
}
}
答案 0 :(得分:2)
请添加你的 //执行后台任务
BackTask bt=new BackTask();
bt.execute();
<{1>} 代替 onCreate()
;
如需了解更多信息,请查看
http://developer.android.com/training/basics/activity-lifecycle/index.html
修改强>
onStart()
答案 1 :(得分:0)
当您远程检查数据时,让您的活动响应更好的一种方法是使用onSaveInstanceState()缓存数据,并将记录列表保存在您可以在活动的onCreate()期间读取的包中。
如果系统决定从堆栈中删除您的活动,那么它将尝试再次从远程主机加载数据(这可能需要一段时间)。
同样是的,您应该在onCreate()而不是onStart()中执行AsyncTask,并确保在从服务器获取数据时从记录列表中删除重复项。