SlideShare a Scribd company logo
1 of 21
Assets, Files, and Data Parsing
Sk. Arman Ali
Software Engineer at
W3Engineers Ltd.
Assets, Files, and Data Parsing
● Android offers a few structured ways to store data, notably
SharedPreferences and local SQLite databases.
● And, of course, you are welcome to store your data “in the
cloud” by using an Internet-based service.
● Beyond that, though, Android allows you to work with plain old
ordinary files, either ones baked into your app (“assets”) or
ones on so-called internal or external storage.
Assets, Files, and Data Parsing
● To make those files work — and to consume data off of the
Internet — you will likely need to employ a parser. Android
ships with several choices for XML and JSON parsing, in
addition to third-party libraries you can attempt to use.
● This session focuses on Assets,Raw, and Files.
Packaging Files with Your App
● Let’s suppose you have some static data you want to ship
with the application, such as a list of words for a spell-
checker.
● Somehow, you need to bundle that data with the
application, in a way you can get at it from Java code
later on, or possibly in a way you can pass to another
component (e.g., WebView for bundled HTML files).
● There are three main options here: raw resources, XML
resources, and assets.
Raw Resources
● One way to deploy a file like a spell-check catalog is to put the
file in the res/raw directory, so it gets put in the Android
application .apk file as part of the packaging process as a raw
resource.
● To access this file, you need to get yourself a Resources object.
InputStream inputStream = getResources().openRawResource(R.raw.activity_main);
XML Resources
● If, however, your file is in an XML format, you are better served
not putting it in res/raw/, but rather in res/xml/.
● This is a directory for XML resources – resources known to be
in XML format.
● To access that XML, you once again get a Resources object by
calling getResources() on your Activity or other Context.
XmlResourceParser xmlResourceParser = getResources().getXml(R.xml.test);
Assets
● Your third option is to package the data in the form of an asset.
● You can create an assets/ directory in your source set (e.g.,
src/main/assets), then place whatever files you want in there.
● Those are accessible at runtime by calling getAssets() on your
Activity or other Context, then calling open() with the path to
the file (e.g., assets/foo/index.html would be retrieved via
open("foo/index.html")).
InputStream inputStream = getAssets().open("foo/index.html");
Files on device storage
● Android uses a file system that's similar to disk-based file
systems on other platforms.
● All Android devices have two file storage areas: "internal" and
"external" storage.
Files on device storage
Internal storage:
● It's always available.
● Files saved here are
accessible by only your
app.
● When the user uninstalls
your app, the system
removes all your app's files
from internal storage.
External storage:
● It's not always available, because the user
can mount the external storage as USB
storage and in some cases remove it from
the device.
● It's world-readable, so files saved here
may be read outside of your control.
● When the user uninstalls your app, the
system removes your app's files from here
only if you save them in the directory from
getExternalFilesDir().
Internal Storage
● Android can save files directly to the device internal storage.
● These files are private to the application and will be removed
if you uninstall the application.
● We can create a file using openFileOutput() with parameter as
file name and the operating mode.
Internal Storage Contd…
● Similarly, we can open the file using openFileInput() passing
the parameter as the filename with extension.
● File are use to store large amount of data Use I/O interfaces
provided by java.io.* libraries to read/write files.
File Operation(Read)
● Use context.openFileInput(string name) to open a private
input file stream related to a program.
● Throw FileNotFoundException when file does not exist.
● Syntax:-
fileinputStram.in=this.openfileinput(“xyz.txt”)
. . . . .
In.close()://Close input stream
File Operation (Write)
● Use context.openFileOutput(string name,int mode ) to open a
private output file stream related to a program.
● The file will be created if it does not exist.
● Passing MODE_PRIVATE makes it private to your app.
● Output stream can be opened in append mode, which means
new data will be appended to end of the file.
File Operation (write) Contd….
● Syntax:-
String filename = "myfile";
String fileContents = "Hello world!";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(fileContents.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
Write a cache file
● For cache some files, you should use createTempFile().
● Syntax:-
private File getTempFile(Context context, String url) {
File file;
try {
String fileName = Uri.parse(url).getLastPathSegment();
file = File.createTempFile(fileName, null, context.getCacheDir());
} catch (IOException e) {
// Error while creating file
}
return file;
}
Open a directory
● getFilesDir()
○ Returns a File representing the directory on the file system that's uniquely associated with your app.
● getDir(name, mode)
○ Creates a new directory (or opens an existing directory) within your app's unique file system directory.
● getCacheDir()
○ Returns a File representing the cache directory on the file system that's uniquely associated with your
app.
○ This directory is meant for temporary files, and it should be cleaned up regularly.
○ The system may delete files there if it runs low on disk space, so make sure you check for the
existence of your cache files before reading them.
External Storage
● Every Android-compatible device supports a shared “external
storage” that you can use to save files
○ Removable storage media (such as an SD card)
○ Internal (non-removable) storage
● File saved to the external storage are world readable and can
be modified by the user when they enable USB mass storage to
transfer files on computer.
● These files are private to the application and will be removed
when the application is uninstalled.
External Storage Contd...
● Must check whether external storage is available first by calling
getExternalStorageState()
○ Also check whether it allows read/write before reading/writing on it
● getExternalFilesDir() takes a parameter such as
DIRECTORY_MUSIC,DIRECTORY_RINGTONE etc,to open specific
type of subdirectories.
● For public shared directories,use
getExternalStoragePublicDirectory()
Query free space
● getFreeSpace()
○ provide the current available space
● getTotalSpace()
○ Provide the total space in the storage volume
Delete a file
● You should always delete files that your app Assets, Files,
and Data Parsing.
● The most straightforward way to delete a file is to call delete()
on the File object.
THANKS

More Related Content

What's hot

Chapter 10.1
Chapter 10.1Chapter 10.1
Chapter 10.1sotlsoc
 
Munching & crunching - Lucene index post-processing
Munching & crunching - Lucene index post-processingMunching & crunching - Lucene index post-processing
Munching & crunching - Lucene index post-processingabial
 
Persentation on c language
Persentation on c languagePersentation on c language
Persentation on c languageSudhanshuVijay3
 
Files & IO in Java
Files & IO in JavaFiles & IO in Java
Files & IO in JavaCIB Egypt
 
Java - File Input Output Concepts
Java - File Input Output ConceptsJava - File Input Output Concepts
Java - File Input Output ConceptsVicter Paul
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsAnton Keks
 
Information Retrieval - Data Science Bootcamp
Information Retrieval - Data Science BootcampInformation Retrieval - Data Science Bootcamp
Information Retrieval - Data Science BootcampKais Hassan, PhD
 
Ie Storage, Multimedia And File Organization
Ie   Storage, Multimedia And File OrganizationIe   Storage, Multimedia And File Organization
Ie Storage, Multimedia And File OrganizationMISY
 
Fileorganization AbnMagdy
Fileorganization AbnMagdyFileorganization AbnMagdy
Fileorganization AbnMagdyMohamed Magdy
 
File Handling
File HandlingFile Handling
File HandlingWaqar Ali
 

What's hot (20)

File organization
File organizationFile organization
File organization
 
File structures
File structuresFile structures
File structures
 
Java I/O
Java I/OJava I/O
Java I/O
 
Chapter 10.1
Chapter 10.1Chapter 10.1
Chapter 10.1
 
Munching & crunching - Lucene index post-processing
Munching & crunching - Lucene index post-processingMunching & crunching - Lucene index post-processing
Munching & crunching - Lucene index post-processing
 
File organization
File organizationFile organization
File organization
 
Persentation on c language
Persentation on c languagePersentation on c language
Persentation on c language
 
Files & IO in Java
Files & IO in JavaFiles & IO in Java
Files & IO in Java
 
Java - File Input Output Concepts
Java - File Input Output ConceptsJava - File Input Output Concepts
Java - File Input Output Concepts
 
Handling I/O in Java
Handling I/O in JavaHandling I/O in Java
Handling I/O in Java
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
 
Lucene basics
Lucene basicsLucene basics
Lucene basics
 
Registry Forensic
Registry ForensicRegistry Forensic
Registry Forensic
 
Information Retrieval - Data Science Bootcamp
Information Retrieval - Data Science BootcampInformation Retrieval - Data Science Bootcamp
Information Retrieval - Data Science Bootcamp
 
Java IO
Java IOJava IO
Java IO
 
File handling
File handlingFile handling
File handling
 
Ie Storage, Multimedia And File Organization
Ie   Storage, Multimedia And File OrganizationIe   Storage, Multimedia And File Organization
Ie Storage, Multimedia And File Organization
 
Input output streams
Input output streamsInput output streams
Input output streams
 
Fileorganization AbnMagdy
Fileorganization AbnMagdyFileorganization AbnMagdy
Fileorganization AbnMagdy
 
File Handling
File HandlingFile Handling
File Handling
 

Similar to Assets, files, and data parsing

03 programmation mobile - android - (stockage, multithreads, web services)
03 programmation mobile - android - (stockage, multithreads, web services)03 programmation mobile - android - (stockage, multithreads, web services)
03 programmation mobile - android - (stockage, multithreads, web services)TECOS
 
Data Storage In Android
Data Storage In Android Data Storage In Android
Data Storage In Android Aakash Ugale
 
Android datastorage
Android datastorageAndroid datastorage
Android datastorageKrazy Koder
 
Windows Phone 8 - 4 Files and Storage
Windows Phone 8 - 4 Files and StorageWindows Phone 8 - 4 Files and Storage
Windows Phone 8 - 4 Files and StorageOliver Scheer
 
Windows Phone 8 - 4 Files and Storage
Windows Phone 8 - 4 Files and StorageWindows Phone 8 - 4 Files and Storage
Windows Phone 8 - 4 Files and StorageOliver Scheer
 
Cs1123 10 file operations
Cs1123 10 file operationsCs1123 10 file operations
Cs1123 10 file operationsTAlha MAlik
 
File Management and manipulation in C++ Programming
File Management and manipulation in C++ ProgrammingFile Management and manipulation in C++ Programming
File Management and manipulation in C++ ProgrammingChereLemma2
 
1 cs xii_python_file_handling text n binary file
1 cs xii_python_file_handling text n binary file1 cs xii_python_file_handling text n binary file
1 cs xii_python_file_handling text n binary fileSanjayKumarMahto1
 
WP7 HUB_Creando aplicaciones de Windows Phone
WP7 HUB_Creando aplicaciones de Windows PhoneWP7 HUB_Creando aplicaciones de Windows Phone
WP7 HUB_Creando aplicaciones de Windows PhoneMICTT Palma
 
14 file handling
14 file handling14 file handling
14 file handlingAPU
 

Similar to Assets, files, and data parsing (20)

03 programmation mobile - android - (stockage, multithreads, web services)
03 programmation mobile - android - (stockage, multithreads, web services)03 programmation mobile - android - (stockage, multithreads, web services)
03 programmation mobile - android - (stockage, multithreads, web services)
 
Data Storage In Android
Data Storage In Android Data Storage In Android
Data Storage In Android
 
Android Data Storagefinal
Android Data StoragefinalAndroid Data Storagefinal
Android Data Storagefinal
 
Android datastorage
Android datastorageAndroid datastorage
Android datastorage
 
UNIT 5.pptx
UNIT 5.pptxUNIT 5.pptx
UNIT 5.pptx
 
Memory management
Memory managementMemory management
Memory management
 
File Handling
File HandlingFile Handling
File Handling
 
File Handling
File HandlingFile Handling
File Handling
 
Windows Phone 8 - 4 Files and Storage
Windows Phone 8 - 4 Files and StorageWindows Phone 8 - 4 Files and Storage
Windows Phone 8 - 4 Files and Storage
 
Windows Phone 8 - 4 Files and Storage
Windows Phone 8 - 4 Files and StorageWindows Phone 8 - 4 Files and Storage
Windows Phone 8 - 4 Files and Storage
 
Chapter4.pptx
Chapter4.pptxChapter4.pptx
Chapter4.pptx
 
Android-data storage in android-chapter21
Android-data storage in android-chapter21Android-data storage in android-chapter21
Android-data storage in android-chapter21
 
Cs1123 10 file operations
Cs1123 10 file operationsCs1123 10 file operations
Cs1123 10 file operations
 
File Management and manipulation in C++ Programming
File Management and manipulation in C++ ProgrammingFile Management and manipulation in C++ Programming
File Management and manipulation in C++ Programming
 
1 cs xii_python_file_handling text n binary file
1 cs xii_python_file_handling text n binary file1 cs xii_python_file_handling text n binary file
1 cs xii_python_file_handling text n binary file
 
Edubooktraining
EdubooktrainingEdubooktraining
Edubooktraining
 
WP7 HUB_Creando aplicaciones de Windows Phone
WP7 HUB_Creando aplicaciones de Windows PhoneWP7 HUB_Creando aplicaciones de Windows Phone
WP7 HUB_Creando aplicaciones de Windows Phone
 
Android Data Persistence
Android Data PersistenceAndroid Data Persistence
Android Data Persistence
 
14 file handling
14 file handling14 file handling
14 file handling
 
Chapter - 5.pptx
Chapter - 5.pptxChapter - 5.pptx
Chapter - 5.pptx
 

Recently uploaded

Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetEnjoy Anytime
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 

Recently uploaded (20)

Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 

Assets, files, and data parsing

  • 1. Assets, Files, and Data Parsing Sk. Arman Ali Software Engineer at W3Engineers Ltd.
  • 2. Assets, Files, and Data Parsing ● Android offers a few structured ways to store data, notably SharedPreferences and local SQLite databases. ● And, of course, you are welcome to store your data “in the cloud” by using an Internet-based service. ● Beyond that, though, Android allows you to work with plain old ordinary files, either ones baked into your app (“assets”) or ones on so-called internal or external storage.
  • 3. Assets, Files, and Data Parsing ● To make those files work — and to consume data off of the Internet — you will likely need to employ a parser. Android ships with several choices for XML and JSON parsing, in addition to third-party libraries you can attempt to use. ● This session focuses on Assets,Raw, and Files.
  • 4. Packaging Files with Your App ● Let’s suppose you have some static data you want to ship with the application, such as a list of words for a spell- checker. ● Somehow, you need to bundle that data with the application, in a way you can get at it from Java code later on, or possibly in a way you can pass to another component (e.g., WebView for bundled HTML files). ● There are three main options here: raw resources, XML resources, and assets.
  • 5. Raw Resources ● One way to deploy a file like a spell-check catalog is to put the file in the res/raw directory, so it gets put in the Android application .apk file as part of the packaging process as a raw resource. ● To access this file, you need to get yourself a Resources object. InputStream inputStream = getResources().openRawResource(R.raw.activity_main);
  • 6. XML Resources ● If, however, your file is in an XML format, you are better served not putting it in res/raw/, but rather in res/xml/. ● This is a directory for XML resources – resources known to be in XML format. ● To access that XML, you once again get a Resources object by calling getResources() on your Activity or other Context. XmlResourceParser xmlResourceParser = getResources().getXml(R.xml.test);
  • 7. Assets ● Your third option is to package the data in the form of an asset. ● You can create an assets/ directory in your source set (e.g., src/main/assets), then place whatever files you want in there. ● Those are accessible at runtime by calling getAssets() on your Activity or other Context, then calling open() with the path to the file (e.g., assets/foo/index.html would be retrieved via open("foo/index.html")). InputStream inputStream = getAssets().open("foo/index.html");
  • 8. Files on device storage ● Android uses a file system that's similar to disk-based file systems on other platforms. ● All Android devices have two file storage areas: "internal" and "external" storage.
  • 9. Files on device storage Internal storage: ● It's always available. ● Files saved here are accessible by only your app. ● When the user uninstalls your app, the system removes all your app's files from internal storage. External storage: ● It's not always available, because the user can mount the external storage as USB storage and in some cases remove it from the device. ● It's world-readable, so files saved here may be read outside of your control. ● When the user uninstalls your app, the system removes your app's files from here only if you save them in the directory from getExternalFilesDir().
  • 10. Internal Storage ● Android can save files directly to the device internal storage. ● These files are private to the application and will be removed if you uninstall the application. ● We can create a file using openFileOutput() with parameter as file name and the operating mode.
  • 11. Internal Storage Contd… ● Similarly, we can open the file using openFileInput() passing the parameter as the filename with extension. ● File are use to store large amount of data Use I/O interfaces provided by java.io.* libraries to read/write files.
  • 12. File Operation(Read) ● Use context.openFileInput(string name) to open a private input file stream related to a program. ● Throw FileNotFoundException when file does not exist. ● Syntax:- fileinputStram.in=this.openfileinput(“xyz.txt”) . . . . . In.close()://Close input stream
  • 13. File Operation (Write) ● Use context.openFileOutput(string name,int mode ) to open a private output file stream related to a program. ● The file will be created if it does not exist. ● Passing MODE_PRIVATE makes it private to your app. ● Output stream can be opened in append mode, which means new data will be appended to end of the file.
  • 14. File Operation (write) Contd…. ● Syntax:- String filename = "myfile"; String fileContents = "Hello world!"; FileOutputStream outputStream; try { outputStream = openFileOutput(filename, Context.MODE_PRIVATE); outputStream.write(fileContents.getBytes()); outputStream.close(); } catch (Exception e) { e.printStackTrace(); }
  • 15. Write a cache file ● For cache some files, you should use createTempFile(). ● Syntax:- private File getTempFile(Context context, String url) { File file; try { String fileName = Uri.parse(url).getLastPathSegment(); file = File.createTempFile(fileName, null, context.getCacheDir()); } catch (IOException e) { // Error while creating file } return file; }
  • 16. Open a directory ● getFilesDir() ○ Returns a File representing the directory on the file system that's uniquely associated with your app. ● getDir(name, mode) ○ Creates a new directory (or opens an existing directory) within your app's unique file system directory. ● getCacheDir() ○ Returns a File representing the cache directory on the file system that's uniquely associated with your app. ○ This directory is meant for temporary files, and it should be cleaned up regularly. ○ The system may delete files there if it runs low on disk space, so make sure you check for the existence of your cache files before reading them.
  • 17. External Storage ● Every Android-compatible device supports a shared “external storage” that you can use to save files ○ Removable storage media (such as an SD card) ○ Internal (non-removable) storage ● File saved to the external storage are world readable and can be modified by the user when they enable USB mass storage to transfer files on computer. ● These files are private to the application and will be removed when the application is uninstalled.
  • 18. External Storage Contd... ● Must check whether external storage is available first by calling getExternalStorageState() ○ Also check whether it allows read/write before reading/writing on it ● getExternalFilesDir() takes a parameter such as DIRECTORY_MUSIC,DIRECTORY_RINGTONE etc,to open specific type of subdirectories. ● For public shared directories,use getExternalStoragePublicDirectory()
  • 19. Query free space ● getFreeSpace() ○ provide the current available space ● getTotalSpace() ○ Provide the total space in the storage volume
  • 20. Delete a file ● You should always delete files that your app Assets, Files, and Data Parsing. ● The most straightforward way to delete a file is to call delete() on the File object.