2012-11-28 23 views
0

我的活動使用線程正常工作,但當有10個或更多圖像從Web服務器數據庫中獲取時,需要很長時間。從谷歌搜索,我已經看到,asynctask是一個更好的選擇,但我無法實現它。下面是我的線程類如何轉換爲asynctask?

public class Ongoing extends Activity implements OnItemClickListener{ 

InputStream is; 
ProgressDialog pd; 
public int limit=0; 
String F_NAME[]=new String[1000]; 
String F_ID[]=new String[1000]; 
String F_IMG[]=new String[1000]; 
String F_DESC[]=new String[1000]; 
String F_DOWN[]=new String[1000]; 
ListView lv1; 
ArrayList<ItemDetails> image_details; 

@Override 

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    int SDK_INT = android.os.Build.VERSION.SDK_INT; 

    if (SDK_INT>8) 
    { 

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 

    StrictMode.setThreadPolicy(policy); 

    } 

     setContentView(R.layout.submenu); 

    lv1 = (ListView) findViewById(R.id.listV_main); 


    lv1.setOnItemClickListener(this) ; 
    pd=new ProgressDialog(this); 
    pd.setTitle("Please wait"); 
    pd.setMessage("Loading...."); 
    pd.setCancelable(false); 
    pd.show(); 

    new Thread(new Runnable() 
    { 
     @Override 
     public void run() 
     { 

      GetSearchResults(); 


     // hanlder.sendEmptyMessage(1); 

      runOnUiThread(new Runnable() { 
       @Override 
       public void run() { 
        lv1 = (ListView) findViewById(R.id.listV_main); 
        adb=new ItemListBaseAdapter(Ongoing.this, results); 
        lv1.setAdapter(adb); 
        pd.cancel(); 
       } 
      }); 

     } 
    }).start(); 

} 
ItemListBaseAdapter adb; 
    private ArrayList<ItemDetails> results = new ArrayList<ItemDetails>(); 
private ArrayList<ItemDetails> GetSearchResults() 
{ 
try{ 
String result = ""; 
try{ 
    HttpClient httpclient = new DefaultHttpClient(); 
    HttpPost httppost = new HttpPost(D.url+"abc.php"); 
    //httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
    HttpResponse response = httpclient.execute(httppost); 
    HttpEntity entity = response.getEntity(); 
    is = entity.getContent(); 
    Log.e("log_tag", "connection success "); 

    }catch(Exception e){ 
    Log.e("log_tag", "Error in http connection "+e.toString()); 


    } 

try{ 
    BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso- 88591"),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("log_tag", "Error converting result "+e.toString()); 

    } 

    try{ 


    JSONArray jArray = new JSONArray(result); 
    int arrayLength=jArray.length(); 
    limit=arrayLength; 
    for(int i=0;i<arrayLength;i++){ 
      JSONObject json_data = jArray.getJSONObject(i); 

      F_NAME[i]=json_data.getString("F_NAME"); 
      F_DESC[i]=json_data.getString("F_DESC"); 
      F_ID[i]="ongopro"+json_data.getString("F_ID"); 
      F_IMG[i]=json_data.getString("F_IMG"); 
      F_DOWN[i]=json_data.getString("F_DOWNLOAD"); 
    } 
    } 
    catch(JSONException e){ 
     Log.e("log_tag", "Error parsing data "+e.toString()); 

    }     


    for(int j=0;j<limit;++j) 
    { 


     ItemDetails item_details = new ItemDetails(); 
     item_details.setName(F_NAME[j]); 
     item_details.setItemDescription(F_DESC[j]); 
     item_details.setImgUrl(F_IMG[j]); 
     item_details.setLoc(F_DOWN[j]); 
     results.add(item_details); 
    } 

} 
catch(Exception e){ 
    Log.e("log_tag", "no msg sent "+e.toString()); 
    hanlder.sendEmptyMessage(2); 

} 
return results; 

} 
@Override 
public void onItemClick(AdapterView<?> parent, View view, 
     int position, long id) { 
data.proj=F_DOWN[position]; 
data.table=F_ID[position]; 
data.flatname=F_NAME[position]; 

Intent newActivity = new Intent(view.getContext(),homescreen.class);  
    startActivity(newActivity); 
    }} 

下面是的AsyncTask代碼(但它不能正常工作,請編輯這個)

public class Ongoing extends Activity implements OnItemClickListener{ 

InputStream is; 
ProgressDialog pd; 
public int limit=0; 
String F_NAME[]=new String[1000]; 
String F_ID[]=new String[1000]; 
String F_IMG[]=new String[1000]; 
String F_DESC[]=new String[1000]; 
String F_DOWN[]=new String[1000]; 
ListView lv1; 
ArrayList<ItemDetails> image_details; 
ItemListBaseAdapter adb; 
@Override 

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    int SDK_INT = android.os.Build.VERSION.SDK_INT; 

    if (SDK_INT>8) 
    { 

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 

    StrictMode.setThreadPolicy(policy); 

    } 

     setContentView(R.layout.submenu); 

    lv1 = (ListView) findViewById(R.id.listV_main); 


    lv1.setOnItemClickListener(this) ; 
    pd=new ProgressDialog(this); 
    pd.setTitle("Please wait"); 
    pd.setMessage("Loading...."); 
    pd.setCancelable(false); 
    pd.show(); 

    load task=new load(); 
    task.execute(); 



} 


public class load extends AsyncTask<Void, Void , ArrayList<ItemDetails>> 
{ 
    public ArrayList<ItemDetails> results = new ArrayList<ItemDetails>(); 
    @Override 
    protected ArrayList<ItemDetails> doInBackground(Void... params) { 

     String result = ""; 
     try{ 
      HttpClient httpclient = new DefaultHttpClient(); 
      HttpPost httppost = new HttpPost(D.url+"abc.php"); 
      //httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
      HttpResponse response = httpclient.execute(httppost); 
      HttpEntity entity = response.getEntity(); 
      is = entity.getContent(); 
      Log.e("log_tag", "connection success "); 

    }catch(Exception e){ 
      Log.e("log_tag", "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(); 

      result=sb.toString(); 
    }catch(Exception e){ 
      Log.e("log_tag", "Error converting result "+e.toString()); 


    } 

    //parse json data 

    try{ 


      JSONArray jArray = new JSONArray(result); 
      int arrayLength=jArray.length(); 
      limit=arrayLength; 
      for(int i=0;i<arrayLength;i++){ 
        JSONObject json_data = jArray.getJSONObject(i); 

        F_NAME[i]=json_data.getString("F_NAME"); 
        F_DESC[i]=json_data.getString("F_DESC"); 
        F_ID[i]="ongopro"+json_data.getString("F_ID"); 
        F_IMG[i]=json_data.getString("F_IMG")+""; 
        F_DOWN[i]=json_data.getString("F_DOWNLOAD"); 
      } 
    } 
      catch(JSONException e){ 
       Log.e("log_tag", "Error parsing data "+e.toString()); 

     }     


      for(int j=0;j<limit;++j) 
      { 


       ItemDetails item_details = new ItemDetails(); 
       item_details.setName(F_NAME[j]); 
       item_details.setItemDescription(F_DESC[j]); 
       item_details.setImgUrl(F_IMG[j]); 
       item_details.setLoc(F_DOWN[j]); 
       results.add(item_details); 
      } 

     } 
     catch(Exception e){ 
      Log.e("log_tag", "no msg sent "+e.toString()); 
      hanlder.sendEmptyMessage(2); 

     return results; 

    } 
    protected void onPostExecute() { 


     adb=new ItemListBaseAdapter(Ongoing.this, results); 
     lv1.setAdapter(adb); 
     pd.dismiss(); 

} 
    @Override 
    protected void onPreExecute() { 
}} 
    @Override 
    public void onItemClick(AdapterView<?> parent, View view, 
     int position, long id) { 
data.proj=F_DOWN[position]; 
data.table=F_ID[position]; 
data.flatname=F_NAME[position]; 

Intent newActivity = new Intent(view.getContext(),homescreen.class);  
    startActivity(newActivity); 
}} 
+0

由於您在*中遇到問題,因此需要從Web服務器數據庫*中提取10個或更多圖像,建議您檢查此示例:[Android - ListView中的異步圖像加載](http://www.technotalkative .com/android-asynchronous-image-loading-in-listview /) –

+0

什麼是錯誤? – Nermeen

+0

使用asynctask方法時不顯示任何內容,但第一個使用線程的工作正常,但在提取 –

回答

1

檢查這個我編輯你的代碼的AsyncTask

public class Ongoing extends Activity implements OnItemClickListener{ 

InputStream is; 
ProgressDialog pd; 
public int limit=0; 
String F_NAME[]=new String[1000]; 
String F_ID[]=new String[1000]; 
String F_IMG[]=new String[1000]; 
String F_DESC[]=new String[1000]; 
String F_DOWN[]=new String[1000]; 
ListView lv1; 
ArrayList<ItemDetails> image_details; 

@Override 

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    int SDK_INT = android.os.Build.VERSION.SDK_INT; 

    if (SDK_INT>8) 
    { 

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 

    StrictMode.setThreadPolicy(policy); 

    } 

     setContentView(R.layout.submenu); 

    lv1 = (ListView) findViewById(R.id.listV_main); 


    lv1.setOnItemClickListener(this) ; 


    new Mytask.execute(null); 

} 
ItemListBaseAdapter adb; 
    private ArrayList<ItemDetails> results = new ArrayList<ItemDetails>(); 
private ArrayList<ItemDetails> GetSearchResults() 
{ 
try{ 
String result = ""; 
try{ 
    HttpClient httpclient = new DefaultHttpClient(); 
    HttpPost httppost = new HttpPost(D.url+"abc.php"); 
    //httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
    HttpResponse response = httpclient.execute(httppost); 
    HttpEntity entity = response.getEntity(); 
    is = entity.getContent(); 
    Log.e("log_tag", "connection success "); 

    }catch(Exception e){ 
    Log.e("log_tag", "Error in http connection "+e.toString()); 


    } 

try{ 
    BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso- 88591"),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("log_tag", "Error converting result "+e.toString()); 

    } 

    try{ 


    JSONArray jArray = new JSONArray(result); 
    int arrayLength=jArray.length(); 
    limit=arrayLength; 
    for(int i=0;i<arrayLength;i++){ 
      JSONObject json_data = jArray.getJSONObject(i); 

      F_NAME[i]=json_data.getString("F_NAME"); 
      F_DESC[i]=json_data.getString("F_DESC"); 
      F_ID[i]="ongopro"+json_data.getString("F_ID"); 
      F_IMG[i]=json_data.getString("F_IMG"); 
      F_DOWN[i]=json_data.getString("F_DOWNLOAD"); 
    } 
    } 
    catch(JSONException e){ 
     Log.e("log_tag", "Error parsing data "+e.toString()); 

    }     


    for(int j=0;j<limit;++j) 
    { 


     ItemDetails item_details = new ItemDetails(); 
     item_details.setName(F_NAME[j]); 
     item_details.setItemDescription(F_DESC[j]); 
     item_details.setImgUrl(F_IMG[j]); 
     item_details.setLoc(F_DOWN[j]); 
     results.add(item_details); 
    } 

} 
catch(Exception e){ 
    Log.e("log_tag", "no msg sent "+e.toString()); 
    hanlder.sendEmptyMessage(2); 

} 
return results; 

} 
@Override 
public void onItemClick(AdapterView<?> parent, View view, 
     int position, long id) { 
data.proj=F_DOWN[position]; 
data.table=F_ID[position]; 
data.flatname=F_NAME[position]; 

Intent newActivity = new Intent(view.getContext(),homescreen.class);  
    startActivity(newActivity); 
    } 


    private class MyTask extends AsyncTask 
{ 

     Dialog dialog; 

     @Override 
     protected void onPreExecute() { 
      // TODO Auto-generated method stub 
      super.onPreExecute(); 
      dialog = new Dialog(yourclass.this); 
      dialog.setTitle("Please wait"); 
      TextView tv = new TextView(yourclass.this.getApplicationContext()); 
      tv.setText("Loading..."); 
      dialog.setContentView(tv); 
      dialog.show(); 
     } 

     @Override 
     protected Object doInBackground(Object... params) 
     { 
        GetSearchResults(); 


     } 

     @Override 
     protected void onPostExecute(Object result) { 
      // TODO Auto-generated method stub 
      super.onPostExecute(result); 
      if(dialog.isShowing()) 
       dialog.cancel(); 
       lv1 = (ListView) findViewById(R.id.listV_main); 
        adb=new ItemListBaseAdapter(Ongoing.this, results); 
        lv1.setAdapter(adb); 
      Toast.makeText(getApplicationContext(), "Loaded Succesfully", Toast.LENGTH_LONG).show(); 


     } 

    } 


    } 
1

你只需要移動GetSearchResults();doInBackGround和UI部分onPostExecute ..

例如:

protected String doInBackground(String... params) { 
    GetSearchResults(); 
} 

protected void onPostExecute(final String result) { 
    lv1 = (ListView) findViewById(R.id.listV_main); 
       adb=new ItemListBaseAdapter(Ongoing.this, results); 
       lv1.setAdapter(adb); 
       pd.cancel(); 
} 
+0

時很慢,請參閱編輯的問題 –

0

首先使延伸的AsyncTask一個內部類,因爲我已經作出如下 - > DownloadWebPageTask

Public class ReadWebpageAsyncTask extends Activity { 
    private TextView textView; 


/** Called when the activity is first created. */ 


     @Override 
     public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     textView = (TextView) findViewById(R.id.TextView01); 
     } 

     private class DownloadWebPageTask extends AsyncTask<String, Void, String> { 
     @Override 
     protected String doInBackground(String... urls) { 
      String response = ""; 
      for (String url : urls) { 
      DefaultHttpClient client = new DefaultHttpClient(); 
      HttpGet httpGet = new HttpGet(url); 
      try { 
       HttpResponse execute = client.execute(httpGet); 
       InputStream content = execute.getEntity().getContent(); 

       BufferedReader buffer = new BufferedReader(new InputStreamReader(content)); 
       String s = ""; 
       while ((s = buffer.readLine()) != null) { 
       response += s; 
       } 

      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
      } 
      return response; 
     } 

     @Override 
     protected void onPostExecute(String result) { 
      textView.setText(result); 
     } 
     } 

     public void readWebpage(View view) { 
     DownloadWebPageTask task = new DownloadWebPageTask(); 
     task.execute(new String[] { "http://www.vogella.com" }); 

     } 
    } 


Than execute this class as below and 

1)doInBackground()將被調用在後臺執行操作

2)onPostExecute()將被調用來在用戶界面線程上寫入數據

DownloadWebPageTask task = new DownloadWebPageTask(); 
task.execute(new String[] { "http://example.com.com" });