Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
Programmation Mobile
Android
Rabie JABALLAH: jaballahrabie@gmail.com
Slim BENHAMMOUDA: slim.benhammouda@gmail.com
Files and storage
● Android can read/write files from two locations:
- internal and external storage
- both are persistent...
Files and storage (2)
Android provides 3 ways to store data:
- preferences files
- Files
- databases
Preferences
● SharePreferences object can store permanent settings
and data for your app
- stores key/value pairs similar ...
sharedprefences example
● Saving preferences for the activity (in onPause, onStop):
SharedPreferences prefs = getPreferenc...
Multiple preferences files
● you can call getSharedPreferences and
supply a file name if you want to have
multiple pref. f...
File and Streams
● java.io.File - Objects that represent a file or
directory
- methods: canRead, canWrite, create, delete,...
File and Streams (2)
● jave.io.InputStream, outputStream - Stream objects
represent flows of data bytes from/to a source o...
Using internal storage
● An activity has methods you can call to read/write files
- getFilesDir() - returns internal direc...
External storage
● external storage : Card that is inserted into
the device (such as a MicroSD card)
- can be much larger ...
External storage permission
● if your app needs to read/write the device’s external
storage, you must explicitly request p...
Using external storage
● Methods to read/write external storage :
- getExternalFilesDir(“name”) - returns “private” extern...
Using external storage (2)
● You can use to read/write files on the
external storage
- the above methods return standard j...
External storage example
// write short data to app-specific external storage
File outDir = getExternalFilesDir(null); // ...
checking if storage is available
/* Checks if external storage is available
* for reading and writing */
public boolean is...
Multithreads
● Each app has a single foreground thread
● All visual elements are on the main thread (also
known for UI thr...
Multithreads (2)
● Standard Java concurrent programming: Thread,
Runnable, java.concurrent
● Android-specific background t...
Accessing web service
● To read data from the web, first request the
INTERNETpermission in your AndroidManifest.
XML
<uses...
Accessing web service (2)
HttpURLConnection con = null;
InputStream is = null;
try {
String wsUrl = "http://my.web.service...
Accessing web service (3)
...
// read the response
StringBuffer buffer = new StringBuffer();
is = con.getInputStream();
Bu...
Accessing web service (4)
...
while ((line = br.readLine()) != null) {
buffer.append(line + "rn");
}
is.close();
con.disco...
Upcoming SlideShare
Loading in …5
×

3

Share

Download to read offline

03 programmation mobile - android - (stockage, multithreads, web services)

Download to read offline

Related Audiobooks

Free with a 30 day trial from Scribd

See all

03 programmation mobile - android - (stockage, multithreads, web services)

  1. 1. Programmation Mobile Android Rabie JABALLAH: jaballahrabie@gmail.com Slim BENHAMMOUDA: slim.benhammouda@gmail.com
  2. 2. Files and storage ● Android can read/write files from two locations: - internal and external storage - both are persistent storage; data remains after power- off/rebot ● internal storage : Built into device - guaranteed to be present - typically smaller (~1-4 gb) - can’t be expanded or removed - specific and private to each app - wiped out when the app is uninstalled
  3. 3. Files and storage (2) Android provides 3 ways to store data: - preferences files - Files - databases
  4. 4. Preferences ● SharePreferences object can store permanent settings and data for your app - stores key/value pairs similar to a bundle or Intent - pairs added to SharePreferences persist after shutdown/reboot (unlike savedInstanceState bundles ● Two ways to use it: - per-activity: getPreferences - per-app: getSharedPreferences - most common use
  5. 5. sharedprefences example ● Saving preferences for the activity (in onPause, onStop): SharedPreferences prefs = getPreferences(MODE_PRIVATE); SharedPreferences.Editor prefsEditor = prefs.edit(); prefsEditor.putInt("name", value); prefsEditor.putString("name", value); ... prefsEditor.apply(); // or commit(); ● Loading preferences later (e.g. in onCreate): SharedPreferences prefs = getPreferences(MODE_PRIVATE); int i = prefs.getInt("name", defaultValue); String s = prefs.getString("name", "defaultValue"); ...
  6. 6. Multiple preferences files ● you can call getSharedPreferences and supply a file name if you want to have multiple pref. files for the same activity: SharedPreferences prefs = getPreferences(MODE_PRIVATE); SharedPreferences prefs = getSharedPreferences ( "filename", MODE_PRIVATE); SharedPreferences.Editor prefsEditor = prefs.edit(); prefsEditor.putInt("name", value); prefsEditor.putString("name", value); ... prefsEditor.commit();
  7. 7. File and Streams ● java.io.File - Objects that represent a file or directory - methods: canRead, canWrite, create, delete, exists, getName, getParent, getPath, isFile, isDirectory, lastModified, lenght, listFiles, mkdir, mkdirs, renameTo
  8. 8. File and Streams (2) ● jave.io.InputStream, outputStream - Stream objects represent flows of data bytes from/to a source or destination - could come from a file, network, database, memory,... - Normally not directly used; they only include low-level methods for reading/writing a byte (character) at a time from the input - instead, a stream is often passed as parameter to other objects like java.util.Scanner, java.io.BufferedReader, java.io. PrintStream to do the actual reading /writing
  9. 9. Using internal storage ● An activity has methods you can call to read/write files - getFilesDir() - returns internal directory for your app - getCacheDir() - returns a “temp” directory for scrap files - getResources().openRawResource(R.raw.id) - read an input file from res/raw/ - openFileInput(“name”, mode) - opens a file for reading - openFileOutput(“name”, mode) - opens a file for writing ● You can use these to read/write files on the device - many methods return standard java.io.File objects - some return java.io.InputStream or OutputStream objects, which can be used with standard classes like scanner, BufferedReader, and PrintStream to read/write files (see java API)
  10. 10. External storage ● external storage : Card that is inserted into the device (such as a MicroSD card) - can be much larger than internal storage (~8-32 gb) - can be removed or transferred to another device if needed - may not be present, depending on the device - read/writable by other apps and users; not private to your app - not wiped when the app is uninstalled, except in certain cases
  11. 11. External storage permission ● if your app needs to read/write the device’s external storage, you must explicitly request permission to do so in your app’s AndroidManifest.XML file - On install, the user will be prompted to confirm your app permissions - No longer needed since Kitkat (Android 4.4) <manifest ...> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> ... </manifest>
  12. 12. Using external storage ● Methods to read/write external storage : - getExternalFilesDir(“name”) - returns “private” external directory for your app with the given name - Environment.getExternalStoragePublicDirectory(name) - returns public directory for common files like photos, music, etc. *pass constants for name such as Environment.DIRECTORY_ALARMS, DIRECTORY_DCIM, DIRECTORY_DOWNLOADS, DIRECTORY_MOVIES, DIRECTORY_MUSIC, DIRECTORY_NOTIFICATIONS, DIRECTORY_PICTURES, DIRECTORY_PODCASTS, DIRECTORY_RINGTONES
  13. 13. Using external storage (2) ● You can use to read/write files on the external storage - the above methods return standard java.io.File objects - these can be used with standard classes like scanner, BufferedReader, and PrintStream to read/write files (see java API)
  14. 14. External storage example // write short data to app-specific external storage File outDir = getExternalFilesDir(null); // root dir File outFile = new File(outDir, "example.txt"); PrintStream output = new PrintStream(outFile); output.println("Hello, world!"); output.close(); // read list of pictures in external storage File picsDir = Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES); for (File file : picsDir.listFiles()) { ... }
  15. 15. checking if storage is available /* Checks if external storage is available * for reading and writing */ public boolean isExternalStorageWritable() { return Environment.MEDIA_MOUNTED.equals( Environment.getExternalStorageState()); } /* Checks if external storage is available * for reading */ public boolean isExternalStorageReadable() { return isExternalStorageWritable() || Environment.MEDIA_MOUNTED_READ_ONLY.equals( Environment.getExternalStorageState()); }
  16. 16. Multithreads ● Each app has a single foreground thread ● All visual elements are on the main thread (also known for UI thread) ● Don’t block the main thread ! ● Don’t access the user interface from other threads ! ● We should use threads to access files since the operation can be heavy
  17. 17. Multithreads (2) ● Standard Java concurrent programming: Thread, Runnable, java.concurrent ● Android-specific background threads: AsyncTask
  18. 18. Accessing web service ● To read data from the web, first request the INTERNETpermission in your AndroidManifest. XML <uses-permission android:name=”android.permission.INTERNET” />
  19. 19. Accessing web service (2) HttpURLConnection con = null; InputStream is = null; try { String wsUrl = "http://my.web.service.url"; con = (HttpURLConnection) (new URL(wsUrl)).openConnection(); con.setRequestMethod("GET"); //it can be POST or PUT... con.setDoInput(true); con.setDoOutput(true); con.connect(); ...
  20. 20. Accessing web service (3) ... // read the response StringBuffer buffer = new StringBuffer(); is = con.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader (is)); String line = null;
  21. 21. Accessing web service (4) ... while ((line = br.readLine()) != null) { buffer.append(line + "rn"); } is.close(); con.disconnect(); result = buffer.toString(); } catch (MalformedURLException e) { e.printStackTrace();} catch (IOException e) { e.printStackTrace();}
  • SoufianeHmimssa

    Mar. 28, 2021
  • OusmaneTanouDiallo

    Dec. 11, 2017
  • allopallo

    Oct. 23, 2016

Views

Total views

649

On Slideshare

0

From embeds

0

Number of embeds

3

Actions

Downloads

31

Shares

0

Comments

0

Likes

3

×