2013-09-17 3 views
0

У меня возникают проблемы с AsyncTask для работы с моим приложением. Я последовал за частью этого урока: http://samir-mangroliya.blogspot.in/p/android-asynctask-example.html. Однако мой список никогда не загружается.Задача Async с массивом ListView

Мой исходный код:

public class MainActivity extends ListActivity { 

private File file; 
private List<String> myList; 

String dirNameSlash = "/Videos"; 
String path = Environment.getExternalStorageDirectory() + dirNameSlash; 
public static final String PREFS_NAME = "MyApp"; 

public void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 

    ListView lv = getListView(); 

    lv.setOnItemLongClickListener(new OnItemLongClickListener() { 
     @Override 
     public boolean onItemLongClick(AdapterView<?> arg0, View arg1,int row, long arg3) { 

      try { 
       String root_sd = Environment.getExternalStorageDirectory().toString(); 
       String theFile = root_sd + "/Videos/" + (String) getListAdapter().getItem(row); 
       File file = new File(theFile); 
       FileInputStream source= new FileInputStream(file); 
       String targetDirectory = Environment.getExternalStorageDirectory().toString(); 
       FileOutputStream destination = new FileOutputStream(targetDirectory + "/Saved/" + file.getName() + ".mp4"); 
       FileChannel sourceFileChannel = source.getChannel(); 
       FileChannel destinationFileChannel = destination.getChannel(); 
       long size = sourceFileChannel.size(); 

       sourceFileChannel.transferTo(0, size, destinationFileChannel); 

       source.close(); 
       destination.close(); 

       Toast.makeText(getApplicationContext(), "Video was copied successfully to '/sdcard/Saved'", Toast.LENGTH_LONG).show(); 

      } catch (Exception ex) { 
       Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex); 
       Toast.makeText(getApplicationContext(), "Error when copying", Toast.LENGTH_LONG).show(); 
      } 

      return true; 
     } 
    }); 

    if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ 
     Log.d("MyApp", "No SDCARD"); 
    } else { 
     File directory = new File(Environment.getExternalStorageDirectory()+File.separator+"Saved"); 
     directory.mkdirs(); 

    } 

    myList = new ArrayList<String>(); 

    String root_sd = Environment.getExternalStorageDirectory().toString(); 
    file = new File(root_sd + "/Videos") ;  
    File list[] = file.listFiles(); 

    for(int i=0; i< list.length; i++) 
    { 
     myList.add(list[i].getName()); 
    } 

    setListAdapter(new ArrayAdapter<String>(this, 
      R.layout.row, myList)); 


protected void onListItemClick(ListView l, View v, int position, long id) 
{ 
    super.onListItemClick(l, v, position, id); 
    String item = (String) getListAdapter().getItem(position); 
    Intent intentToPlayVideo = new Intent(Intent.ACTION_VIEW); 
    intentToPlayVideo.setDataAndType(Uri.parse(path + item), "video/*"); 
    startActivity(intentToPlayVideo); 
} 



}   

Мой код с AsyncTask:

public class MainActivity extends ListActivity { 

private File file; 
private List<String> myList; 
Load objMyTask; 

String dirNameSlash = "/Videos"; 
String path = Environment.getExternalStorageDirectory() + dirNameSlash; 
public static final String PREFS_NAME = "MyPref"; 

public void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 

    ListView lv = getListView(); 

    lv.setOnItemLongClickListener(new OnItemLongClickListener() { 
     @Override 
     public boolean onItemLongClick(AdapterView<?> arg0, View arg1,int row, long arg3) { 

      try { 
       String root_sd = Environment.getExternalStorageDirectory().toString(); 
       String theFile = root_sd + "/Videos" + (String) getListAdapter().getItem(row); 
       File file = new File(theFile); 
       FileInputStream source= new FileInputStream(file); 
       String targetDirectory = Environment.getExternalStorageDirectory().toString(); 
       FileOutputStream destination = new FileOutputStream(targetDirectory + "/Saved" + file.getName() + ".mp4"); 
       FileChannel sourceFileChannel = source.getChannel(); 
       FileChannel destinationFileChannel = destination.getChannel(); 
       long size = sourceFileChannel.size(); 

       sourceFileChannel.transferTo(0, size, destinationFileChannel); 

       source.close(); 
       destination.close(); 

       Toast.makeText(getApplicationContext(), "Video was copied successfully to '/sdcard/Saved'", Toast.LENGTH_LONG).show(); 

      } catch (Exception ex) { 
       Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex); 
       Toast.makeText(getApplicationContext(), "Error when copying", Toast.LENGTH_LONG).show(); 
      } 

      return true; 
     } 
    }); 

    if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ 
     Log.d("MyApp", "No SDCARD"); 
    } else { 
     File directory = new File(Environment.getExternalStorageDirectory()+File.separator+"Saved"); 
     directory.mkdirs(); 


    } 


     setListAdapter(new ArrayAdapter<String>(this, 
       R.layout.row, myList)); 


    objMyTask = new Load(); 

    objMyTask.execute(); 

} 

protected void onListItemClick(ListView l, View v, int position, long id) 
{ 
    super.onListItemClick(l, v, position, id); 
    String item = (String) getListAdapter().getItem(position); 
    Intent intentToPlayVideo = new Intent(Intent.ACTION_VIEW); 
    intentToPlayVideo.setDataAndType(Uri.parse(path + item), "video/*"); 
    startActivity(intentToPlayVideo); 
} 



} 


private class Load extends AsyncTask<String, Integer, String> { 

    @Override 
    protected String doInBackground(String... params) { 
    myList = new ArrayList<String>(); 

    String root_sd = Environment.getExternalStorageDirectory().toString(); 
    file = new File(root_sd + "/Videos") ;  
    File list[] = file.listFiles(); 

    for(int i=0; i< list.length; i++) 
    { 
     myList.add(list[i].getName()); 
    } 

     return null; 
    } 

} 

Любая помощь будет принята с благодарностью. Благодаря!

ответ

1

вы не звоните notifyDatasetChanged на адаптере после того, как вы получите список из AsyncTask

вам нужно использовать метод onPostExecute() и называют его там

не делают это

setListAdapter(new ArrayAdapter<String>(this, 
      R.layout.row, myList)); 

вынимают адаптер и удерживать экземпляр его для использования позднее, когда у вас есть список

ArrayAdapter adapter = new ArrayAdapter<String>(this,R.layout.row, myList) 
setListAdapter(adapter); 

then just do adapter.notifyDatasetChanged()

+0

Спасибо за ваш ответ. Где я могу поставить: ArrayAdapter adapter = new ArrayAdapter (это, R.layout.row, myList) setListAdapter (адаптер); ? Я поместил adapter.notifyDatasetChanged() в onPostExecute(), но я понял, что «адаптер не может быть разрешен». – user2420837

+0

вам нужно сделать переменную переменной шириной широким – tyczj

+0

Приложение принудительно закрывается. Думаю, я помещаю ваш предложенный код в неправильное место. Я буду экспериментировать больше и отчитываться. – user2420837

Смежные вопросы