2015-08-08 19 views
0

我有一個顯示數據庫記錄列表的活動。 在這個活動中有一個自定義的ListView。 在自定義ListView中,有一個Button和一個TextView以及一個ProgressBar。 我調用AsyncTask的按鈕偵聽器位於CustomAdapter類中。在下載時更新ListView中的進度欄​​

DownloadTask downloadTask = new DownloadTask(getContext()); 
       downloadTask.execute(url[position].toString()); 

AsynkTask很好。 但我想在下載過程中更新進度欄。 我在互聯網上搜索了三天,但沒有成功。 我很抱歉,我的英語

public class listanimals extends ActionBarActivity { 
private MyDatabase MyDataBase; 
String[] listurl; 
ProgressBar progressBar; 
TextView url2; 
CustomList adapter; 
//////////////////////////////////////////////////////////////////////////////////////////////////////////////// 
/////////////////////////////////////////////////////////////////////////////////////////////////////////////// 

public class DownloadTask extends AsyncTask<String, Integer, String> { 
    private Context context; 
    int myProgress; 
    public DownloadTask(Context context) { 
     this.context = context; 
    } 

    @Override 
    protected String doInBackground(String... sUrl) { 

     InputStream input = null; 
     final GlobalClass caches = (GlobalClass) context.getApplicationContext(); 
     OutputStream output = null; 
     HttpURLConnection connection = null; 

     try { 
      URL url = new URL(sUrl[0]); 
      connection = (HttpURLConnection) url.openConnection(); 
      connection.connect(); 


      if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { 
       return "Server returned HTTP " + connection.getResponseCode() 
         + " " + connection.getResponseMessage(); 
      } 


      input = connection.getInputStream(); 
      output = new FileOutputStream("/sdcard/"+caches.getName_cach()+".mp3"); 

      byte data[] = new byte[4096]; 
      long total = 0; 
      int count; 

      while ((count = input.read(data)) != -1) { 
       total += count; 

       myProgress = (int)(total*100/connection.getContentLength()); 

       output.write(data, 0, count); 

      } 
     } catch (Exception e) { 
      return e.toString(); 
     } finally { 
      try { 
       if (output != null) 
        output.close(); 
       if (input != null) 
        input.close(); 
      } catch (IOException ignored) { 
      } 

      if (connection != null) 
       connection.disconnect(); 
     } 
     return null; 
    } 
    @Override 
    protected void onProgressUpdate(Integer... values) { 
    //MY PROBLEM MAY HERE 
     progressBar.setProgress(myProgress); 
    } 
    @Override 
    protected void onPostExecute(String result) { 
     final GlobalClass caches = (GlobalClass) context.getApplicationContext(); 

     if (result != null) 
      Toast.makeText(context,"Download error: "+result, Toast.LENGTH_LONG).show(); 

     else{ 
      Toast.makeText(context,"File downloaded"+ "" + caches.getName_cach(), Toast.LENGTH_SHORT).show(); 

     } 
    } 

} 
/////////////////////////////////////////////////////////////////////////////////////////////////////////////AsynkTask end 
/////////////////////////////////////////////////////////////////////////////////////// 
@Override 
protected void onCreate(Bundle savedInstanceState) { 


    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_listanimals); 
    MyDataBase = new MyDatabase(this); 
    final GlobalClass caches = (GlobalClass) getApplicationContext(); 
    final ListView listView=(ListView)findViewById(R.id.listView); 


    SQLiteDatabase mydb = MyDataBase.getReadableDatabase(); 

    Cursor cursor = mydb.rawQuery("select * from animals", null); 

    ArrayList<String> myList = new ArrayList<String>(); 
    final ArrayList<String> myListname = new ArrayList<String>(); 
    ArrayList<String> myListurl = new ArrayList<String>(); 

    try { 
     while(cursor.moveToNext()) { 

      myList.add(cursor.getString(cursor.getColumnIndex("_id"))); 
      myListname.add(cursor.getString(cursor.getColumnIndex("name")).trim()); 
      myListurl.add(cursor.getString(cursor.getColumnIndex("url"))); 

      String[] listname = new String[myListname.size()]; 
      listname = myListname.toArray(listname); 

      listurl = new String[myListurl.size()]; 
      listurl = myListurl.toArray(listurl); 

      String[] listid = new String[myList.size()]; 
      listid = myList.toArray(listid); 

      adapter = new 
        CustomList(listanimals.this, listname,listurl); 
      listView.setAdapter(adapter); 

    }} finally{ 
     mydb.close(); 
    }} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.menu_main, menu); 
    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    // Handle action bar item clicks here. The action bar will 
    // automatically handle clicks on the Home/Up button, so long 
    // as you specify a parent activity in AndroidManifest.xml. 
    int id = item.getItemId(); 

    //noinspection SimplifiableIfStatement 
    if (id == R.id.action_settings) { 
     return true; 
    } 

    return super.onOptionsItemSelected(item); 
} 

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 
/////////////////////////////////////////////////////////////////////////////////////////////////////////////// 

public class CustomList extends ArrayAdapter<String> { 

    private MyDatabase MyDataBase; 

    private final Activity context; 
    private final String[] web; 
    private final String[] url; 
    public CustomList(Activity context, 
         String[] web,String[] url) { 
     super(context, R.layout.list_file, web); 
     this.context = context; 
     this.web = web; 
     this.url = url; 
    } 



    @Override 
    public View getView(final int position, View view, final ViewGroup parent) { 
     final GlobalClass caches = (GlobalClass) context.getApplicationContext(); 

     MyDataBase = new MyDatabase(getContext()); 

     LayoutInflater inflater = context.getLayoutInflater(); 
     View rowView= inflater.inflate(R.layout.list_file, null, true); 
     Typeface kamran= Typeface.createFromAsset(context.getAssets(), "IranNastaliq.ttf"); 
     progressBar=(ProgressBar)rowView.findViewById(R.id.progressBar); 
     TextView txtTitle3 = (TextView) rowView.findViewById(R.id.textView); 
     txtTitle3.setTypeface(kamran); 
     url2=(TextView)rowView.findViewById(R.id.textView2); 
     url2.setText(url[position]); 
     txtTitle3.setText(web[position]); 
     Button download=(Button)rowView.findViewById(R.id.button); 



     download.setTag(position);// Any data associated with the button has to be added with   setTag() 

     download.setOnClickListener(new View.OnClickListener() {/////////call AsynkTask 
      @Override 
      public void onClick(View arg0) { 
      caches.setName_cach(web[position]); 
       DownloadTask downloadTask = new DownloadTask(getContext()); 
       downloadTask.execute(url[position].toString()); 


      } 
     }); 

     return rowView; 

    } 


} 

} 

回答

1

你需要調用publishProgress從doInBackground方法來更新進度:​​

這將調用onProgressUpdate(整數...值);

您不需要myProgress實例變量;

+0

如果它解決了您的問題,請標記爲正確的答案。 – airowe

+0

謝謝Bro.I嘗試過。但是,此方法在進度欄處於活動狀態時起作用。當進度欄處於自定義列表佈局時,這不起作用。解決辦法是什麼? –

+0

@AmirGheybi您的ProgressBar是類listAnimals的一個實例變量。它應該在該類的onCreate方法中實例化。 – airowe

0

退房此鏈接https://www.youtube.com/watch?v=5HDr9FdGIVg&list=PLonJJ3BVjZW6hmkEaYIvLLm5IEGM0kpwU&index=17

你需要調用 - publishProgress((int)的總* 100/connection.getContentLength());

在while循環中 更新您的progressbar.Hope它有幫助。

+0

謝謝Bro.Video非常好。我嘗試過這個 。但是,此方法在進度欄處於活動狀態時起作用。當進度欄處於自定義列表佈局時,這不起作用。解決辦法是什麼? –

0

當您在活動中保留單個實例時,您在列表的每個項目中都有一個進度欄。這意味着您的進度視圖將指向系統要求您繪製的最後一個列表項中的一個。這可能不是您按下按鈕的列表項中的一個。我建議你把課程分開(把它們從活動中拿出來),你會更好地看到你的問題。但這只是您的第一個問題 - 因爲您啓動了異步任務,同時您可以將該項目從屏幕上滾動下來。