2016-12-06 2 views
0

У меня было несколько проблем с этим изначально из-за того, что я не запрашивал разрешения на запись во время выполнения, но я решил эту проблему по-видимому. Код захватывает файл PDF с веб-сайта и должен хранить это в каталоге приложения, я поставил пост выполнить, чтобы установить TextView предполагаемого каталог для созданного файла file.No создаются и никаких исключений не пострадало, так что я довольно озадачен здесьAndroid не сохранит файл на хранение

public class MainActivity extends AppCompatActivity implements ActivityCompat.OnRequestPermissionsResultCallback { 

private static final int REQUEST_WRITE_PERMISSION = 786; 

@Override 
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { 
    if (requestCode == REQUEST_WRITE_PERMISSION && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 
     new FetchWebsiteData(this).execute(); 
    } 
} 
private void requestPermission() { 
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
     requestPermissions(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_PERMISSION); 
    } else { 
     //do something 
     //new FetchWebsiteData().execute(); 
    } 
} 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    Button btnFetchData = (Button) findViewById(R.id.buttonTest); 
    btnFetchData.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 

      requestPermission(); 


     } 
    }); 

} 



private class FetchWebsiteData extends AsyncTask<Void, Void, Void> { 

    private String pdfLink = "didnt work"; 
    private Link foundLink = new Link(""); 
    String fileLocation= ""; 
    Context context; 
    public FetchWebsiteData(Context context1){ 
     context = context1; 
    } 
    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 


    } 

    @Override 
    protected Void doInBackground(Void... params) { 
     int count; 
     try { 

      Document doc = Jsoup.connect("http://www.dunnesstores.com/offer20/food-wine/fcp-category/home").userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:5.0) Gecko/20100101 Firefox/5.0").get(); 
      //Elements links = doc.select("a[title=\"Download offers in store\"]"); 
      Element links = doc.select("a[title=\"Download offers in store\"]").first(); 
      foundLink = new Link(links.attr("href")); 

      URL url = new URL(foundLink.getUrlWithDomain()); 


      //create the new connection 
      HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); 

      //set up some things on the connection 
      urlConnection.setRequestMethod("GET"); 
      urlConnection.setDoOutput(true); 

      //and connect! 
      urlConnection.connect(); 


      File file = new File(context.getFilesDir(),foundLink.getFileNameOnly()); 
      fileLocation = file.toString(); 
      //this will be used to write the downloaded data into the file we created 
      FileOutputStream fileOutput = new FileOutputStream(file); 

      //this will be used in reading the data from the internet 
      InputStream inputStream = urlConnection.getInputStream(); 

      //this is the total size of the file 
      int totalSize = urlConnection.getContentLength(); 
      //variable to store total downloaded bytes 
      int downloadedSize = 0; 

      //create a buffer... 
      byte[] buffer = new byte[1024]; 
      int bufferLength = 0; //used to store a temporary size of the buffer 

      //now, read through the input buffer and write the contents to the file 
      while ((bufferLength = inputStream.read(buffer)) > 0) { 
       //add the data in the buffer to the file in the file output stream (the file on the sd card 
       fileOutput.write(buffer, 0, bufferLength); 
       //add up the size so we know how much is downloaded 
       downloadedSize += bufferLength; 
       //this is where you would do something to report the prgress, like this maybe 


      } 
      //close the output stream when done 
      fileOutput.close(); 





     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     return null; 
    } 

    @Override 
    protected void onPostExecute(Void result) { 
     TextView txttitle = (TextView) findViewById(R.id.resultTextView); 
     //testing the file location 
     txttitle.setText(fileLocation); 

    } 

} 
+0

«Файл не создан» - как ** точно ** вы определили это? 'adb ​​shell ls'? Диспетчер файлов на устройстве? Android Debug Monitor? Диспетчер файлов ОС Windows? Что-то другое? – CommonsWare

+0

Извините, я запускаю его на своем собственном устройстве Android и просто использую Windows Explorer на своем рабочем столе через USB. – Daniel

ответ

0

Вы пишете до internal storage. Это не может быть просмотрено пользователем, используя диспетчер файлов ОС Windows или многое другое.

+0

Отличная благодарность, я думаю, я неправильно понял смысл внутреннего хранилища. Будет ли способ написать его так, чтобы его можно было просмотреть файловый менеджер рабочего стола? – Daniel

+0

@ Даниэль: Не на внутренней памяти. Для этого вы должны использовать [внешнее хранилище] (https://commonsware.com/blog/2014/04/08/storage-situation-external-storage.html). И вам нужно будет добавить немного кода для [упорядочения быстрого доступа этих файлов к MediaStore] (http://stackoverflow.com/questions/32789157/how-to-write-files-to- внешний-общедоступный-хранилище-в-андроид-так-то-они-есть-visibl), чтобы они были видны из Windows сразу. – CommonsWare

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