ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Mobile Application Development 1
    COMP4124
    Progress0 / 33 topics
    Topics
    1. Mobiles Application Development Platform2. HTML5 for Mobiles3. Android OS: Architecture, Framework and Application Development4. iOS: Architecture, Framework5. Application Development with Windows Mobile6. Eclipse7. Fragments8. Calling Built-in Applications using Intents9. Displaying Notifications10. Components of a Screen11. Adapting to Display Orientation12. Managing Changes to Screen Orientation13. Utilizing the Action Bar14. Creating the User Interface15. Listening for UI Notifications16. Views17. User Preferences18. Persisting & Sharing Data19. Sending SMS Messages20. Getting Feedback21. Sending E-mail22. Displaying Maps23. Consuming Web Services Using HTTP24. Web Services: Accessing and Creating25. Threading26. Publishing Android Applications27. Deployment on App Stores28. Mobile Programming Languages29. Challenges with Mobility and Wireless Communication30. Location-aware Applications31. Performance/Power Tradeoffs32. Mobile Platform Constraints33. Emerging Technologies
    COMP4124›Persisting & Sharing Data
    Mobile Application Development 1Topic 18 of 33

    Persisting & Sharing Data

    7 minread
    1,192words
    Intermediatelevel

    Persisting and Sharing Data in Mobile Applications

    In mobile app development, handling data is a crucial task. This includes persisting data (saving it locally on the device) for future use and sharing data between apps or with external services. Both are important for creating efficient and user-friendly apps.

    Let’s break down the key concepts and methods for persisting and sharing data in mobile apps.


    1. Persisting Data in Mobile Applications

    Persisting data means saving data in such a way that it can be accessed later, even after the app is closed or the device is restarted. Mobile platforms provide several ways to store data locally.

    a. SharedPreferences (Android)

    For simple key-value pairs (e.g., settings or user preferences), Android provides SharedPreferences. This is ideal for storing small amounts of data like user preferences, app settings, or simple flags.

    • Saving Data:

      SharedPreferences sharedPreferences = getSharedPreferences("AppPrefs", MODE_PRIVATE);
      SharedPreferences.Editor editor = sharedPreferences.edit();
      editor.putString("username", "JohnDoe");
      editor.putBoolean("isLoggedIn", true);
      editor.apply();  // Apply changes asynchronously
      
    • Retrieving Data:

      SharedPreferences sharedPreferences = getSharedPreferences("AppPrefs", MODE_PRIVATE);
      String username = sharedPreferences.getString("username", "defaultName");
      boolean isLoggedIn = sharedPreferences.getBoolean("isLoggedIn", false);
      

    Use Case: SharedPreferences is suitable for storing small, non-sensitive data (e.g., user settings, preferences, and flags).

    b. SQLite Database (Android)

    For more complex or structured data (e.g., records or lists), Android provides SQLite, a lightweight relational database. You can use it to store larger amounts of data locally.

    • Creating a Database and Table:

      SQLiteDatabase db = openOrCreateDatabase("app_database", MODE_PRIVATE, null);
      db.execSQL("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER);");
      
    • Inserting Data:

      ContentValues contentValues = new ContentValues();
      contentValues.put("name", "John Doe");
      contentValues.put("age", 30);
      db.insert("users", null, contentValues);
      
    • Retrieving Data:

      Cursor cursor = db.query("users", new String[] {"id", "name", "age"}, null, null, null, null, null);
      if (cursor.moveToFirst()) {
          String name = cursor.getString(cursor.getColumnIndex("name"));
          int age = cursor.getInt(cursor.getColumnIndex("age"));
      }
      cursor.close();
      

    Use Case: SQLite is ideal for storing structured, relational data such as user records, product lists, or transactions.

    c. Files (Android and iOS)

    Both Android and iOS allow you to save data as files (text files, JSON, etc.). This is useful for larger datasets or for specific file types.

    • Writing to a File (Android):

      FileOutputStream fos = openFileOutput("user_data.txt", MODE_PRIVATE);
      fos.write("User data example".getBytes());
      fos.close();
      
    • Reading from a File (Android):

      FileInputStream fis = openFileInput("user_data.txt");
      int character;
      StringBuilder stringBuilder = new StringBuilder();
      while ((character = fis.read()) != -1) {
          stringBuilder.append((char) character);
      }
      fis.close();
      

    Use Case: This is suitable when you need to store larger chunks of data, like user-generated content or log files.

    d. Core Data (iOS)

    For iOS, Core Data is a powerful framework for data persistence. It provides a high-level object graph management and persistence framework, which is ideal for storing complex data models.

    • Creating a Managed Object Context:

      let appDelegate = UIApplication.shared.delegate as! AppDelegate
      let context = appDelegate.persistentContainer.viewContext
      
    • Saving Data:

      let newUser = User(context: context)
      newUser.name = "John Doe"
      newUser.age = 30
      try? context.save()
      
    • Fetching Data:

      let fetchRequest: NSFetchRequest<User> = User.fetchRequest()
      let users = try? context.fetch(fetchRequest)
      

    Use Case: Core Data is best for complex data models, relationships between objects, and when you need features like undo/redo, versioning, and data migrations.


    2. Sharing Data in Mobile Applications

    Sharing data allows your app to interact with other apps or services, or to share data between different parts of your own app. There are several ways to share data on both Android and iOS.

    a. Sharing Data Between Apps

    Both Android and iOS provide ways to share data with other apps.

    • Android (Using Intents to Share Data)

      Android uses Intents to share data between applications. Intents can send data like text, images, or files to other apps. For example, sharing a text message via email:

      Intent sendIntent = new Intent(Intent.ACTION_SEND);
      sendIntent.setType("text/plain");
      sendIntent.putExtra(Intent.EXTRA_TEXT, "Check out this message!");
      startActivity(Intent.createChooser(sendIntent, "Share via"));
      

      This will trigger an intent that allows the user to share the message via compatible apps, like email or social media.

    • iOS (Using UIActivityViewController to Share Data)

      On iOS, UIActivityViewController is used for sharing content. It provides a standard interface for sharing data with other apps or services.

      let textToShare = "Check out this cool message!"
      let activityViewController = UIActivityViewController(activityItems: [textToShare], applicationActivities: nil)
      present(activityViewController, animated: true, completion: nil)
      

      This opens a share sheet allowing users to share the content via supported apps.

    b. Sharing Data with External Services (APIs, Cloud Storage)

    You can also share data by integrating with external services like cloud storage (e.g., Google Drive, iCloud, Dropbox) or APIs.

    • Android (Using Retrofit or Volley for HTTP Requests)

      Retrofit or Volley libraries allow Android apps to make HTTP requests to remote servers or APIs, where they can share or retrieve data.

      Retrofit retrofit = new Retrofit.Builder()
          .baseUrl("https://example.com/api/")
          .addConverterFactory(GsonConverterFactory.create())
          .build();
      
      ApiService apiService = retrofit.create(ApiService.class);
      Call<Response> call = apiService.sendData(data);
      call.enqueue(new Callback<Response>() {
          @Override
          public void onResponse(Call<Response> call, Response<Response> response) {
              // Handle the response
          }
      
          @Override
          public void onFailure(Call<Response> call, Throwable t) {
              // Handle failure
          }
      });
      
    • iOS (Using URLSession for API Calls)

      In iOS, you can use URLSession to send data to external services.

      let url = URL(string: "https://example.com/api/")!
      var request = URLRequest(url: url)
      request.httpMethod = "POST"
      request.httpBody = try? JSONEncoder().encode(data)
      
      let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
          if let error = error {
              print("Error: $$error)")
          } else {
              // Handle response data
          }
      }
      task.resume()
      

    c. Using Content Providers (Android)

    Android provides Content Providers for sharing structured data between apps. A content provider acts as an interface for data sharing, enabling apps to access shared data in different formats.

    For example, reading contacts from the Contacts Provider:

    Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
    if (cursor != null && cursor.moveToFirst()) {
        String contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
        cursor.close();
    }
    

    d. Using Cloud Storage (Firebase, iCloud, etc.)

    Cloud storage services allow apps to store and sync data across multiple devices or users.

    • Firebase (Android/iOS): Firebase provides real-time database and cloud storage solutions that allow you to persist and share data across devices and platforms. Firebase Authentication also helps share data by providing user-specific data syncing.

    Conclusion

    Persisting Data and Sharing Data are fundamental aspects of mobile app development, ensuring that user data is stored safely and can be shared seamlessly across apps and platforms. Here’s a quick recap:

    • Persisting Data:

      • Use SharedPreferences (Android) or UserDefaults (iOS) for simple key-value storage.
      • Use SQLite (Android) or Core Data (iOS) for structured data.
      • Save data to files for larger datasets or specific formats.
    • Sharing Data:

      • Use Intents (Android) or UIActivityViewController (iOS) for sharing content between apps.
      • Use APIs or cloud services to share data with external services.

    Effective data management helps make apps more functional, interactive, and useful to the user, allowing them to store and share information across devices and services.

    Previous topic 17
    User Preferences
    Next topic 19
    Sending SMS Messages

    Past Papers

    Open this section to load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time7 min
      Word count1,192
      Code examples0
      DifficultyIntermediate