CoreData Day-2 :: CoreData Components ?


cropped-mobile.jpg

1.NSIncrementalStore: NSIncrementalStore is an abstract superclass defining the API through which Core Data communicates with a store. This interface is designed to allow you to create persistent stores which load and save data incrementally, allowing for the management of large and/or shared datasets


2. NSIncrementalStoreNode : NSIncrementalStoreNode is a concrete class to represent basic nodes in a Core Data incremental store.

A node represents a single record in a persistent store.

You can subclass NSIncrementalStoreNode to provide custom behavior.


3. NSManagedObjectModel : The managed object model is the data model of the application. Even though Core Data isn’t a database, you can compare the managed object model to the schema of a database, that is, it contains information about the models or entities of the object graph, what attributes they have, and how they relate to one another.

The NSManagedObjectModel object knows about the data model by loading one or more data model files during its initialization. We’ll take a look at how this works in a few moments.

– (NSManagedObjectModel *)managedObjectModel

{

    if (_managedObjectModel != nil) {

        return _managedObjectModel;

}

    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@”Core_Data” withExtension:@”momd”];

    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];

    return _managedObjectModel;

}

Delete Rule in NSManagedObjectModel

The Delete Rule menu has four options, No ActionNullifyCascade, and Deny.

No Action

If you select No Action, Core Data doesn’t update or notify the source record of the relationship. This means that the source record of the relationship still thinks it has a relationship with the record that was deleted. Note that this is rarely what you want.

Nullify

This option sets the destination of the relationship to null when the destination record is deleted. This is the default delete rule of a relationship.

Cascade

If the relationship from Person to Address is set to Cascade, deleting a person record will also delete any address records that are associated with the person record. This is useful, for example, if a relationship is required and the record cannot or shouldn’t exist without the relationship. A user, for example, shouldn’t exist if it’s not associated with an account.

Deny

In a sense, Deny is the inverse of Cascade. For example, if we have an Accountentity that has a to-many relationship with a User entity with its delete rule set to Deny, an account record can only be deleted if it has no user records associated with it. This ensures that no user records exist without an account record. The result is similar to the Cascade delete rule, but the implementation differs.


4. NSPersistentStoreCoordinator : As its name indicates, the NSPersistentStoreCoordinator object persists data to disk and ensures the persistent store(s) and the data model are compatible. It mediates between the persistent store(s) and the managed object context(s) and also takes care of loading and caching data. That’s right. Core Data has caching built in.

The persistent store coordinator is the conductor of the Core Data orchestra. Despite its important role in the Core Data stack, we rarely interact with it directly.

– (NSPersistentStoreCoordinator *)persistentStoreCoordinator

{

    if (_persistentStoreCoordinator != nil) {

        return _persistentStoreCoordinator;

    }

    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@”Core_Data.sqlite”];

    NSError *error = nil;

    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];

    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {

        /*

         Replace this implementation with code to handle the error appropriately.

         abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

         Typical reasons for an error here include:

         * The persistent store is not accessible;

         * The schema for the persistent store is incompatible with current managed object model.

         Check the error message to determine what the actual problem was.

         If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application’s resources directory instead of a writeable directory.

         If you encounter schema incompatibility errors during development, you can reduce their frequency by:

         * Simply deleting the existing store:

         [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]

         * Performing automatic lightweight migration by passing the following dictionary as the options parameter:

         @{NSMigratePersistentStoresAutomaticallyOption:@YES, NSInferMappingModelAutomaticallyOption:@YES}

         Lightweight migration will only work for a limited set of schema changes; consult “Core Data Model Versioning and Data Migration Programming Guide” for details.

         */

        NSLog(@”Unresolved error %@, %@”, error, [error userInfo]);

        abort();

    }

    return _persistentStoreCoordinator;

}


5.NSManagedObjectContext : The NSManagedObjectContext object manages a collection of model objects, instances of the NSManagedObject class. It’s perfectly possible to have multiple managed object contexts. Each managed object context is backed by a persistent store coordinator.

You can see a managed object context as a workbench on which you work with your model objects. You load them, you manipulate them, and save them on that workbench. Loading and saving are mediated by the persistent store coordinator. You can have multiple workbenches, which is useful if your application is multithreaded, for example.

While a managed object model and persistent store coordinator can be shared across threads, managed object contexts should never be accessed from a thread different than the one they were created on. We’ll discuss multithreading in more detail later in this series.

– (NSManagedObjectContext *)managedObjectContext

{

    if (_managedObjectContext != nil) {

        return _managedObjectContext;

    }

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];

    if (coordinator != nil) {

        _managedObjectContext = [[NSManagedObjectContext alloc] init];

        [_managedObjectContext setPersistentStoreCoordinator:coordinator];

    }

    return _managedObjectContext;

}

Advertisements

Few moment with Android


1. Android Core Building Blocks                                                

An android component is simply a piece of code that has a well defined life cycle e.g. Activity, Receiver, Service etc.

(i) Activity : An activity is a class that represents a single screen. It is like a Frame in AWT.

(ii) View: A view is the UI element such as button, label, text field etc. Anything that you see is a view.

(iii) Intent ::

Intent is used to invoke components. It is mainly used to:

  • Start the service
  • Launch an activity
  • Display a web page
  • Display a list of contacts
  • Broadcast a message
  • Dial a phone call etc.

For example, you may write the following code to view the webpage.

// Implicit Intent by specifying a URI

Intent i = new Intent(Intent.ACTION_VIEW,

Uri.parse(http://www.example.com”));

// Starts Implicit Activity

startActivity(i);

// Explicit Intent

  1. Intent i = new Intent(getApplicationContext(), ActivityTwo.class);
  2.  startActivity(i);

(iv) Service: Service is a background process that can run for a long time.

There are two types of services local and remote. Local service is accessed from within the application whereas remote service is accessed remotely from other applications running on the same device.

(v) Content Provider : Content Providers are used to share data between the applications.

(vi) Fragment : Fragments are like parts of activity. An activity can display one or more fragments on the screen at the same time.

(vi) AndroidManifest.xml : The AndroidManifest.xml file contains information of your package, including components of the application such as activities, services, broadcast receivers, content providers etc.

It performs some other tasks also:

  • It is responsible to protect the application to access any protected parts by providing the permissions.
  • It also declares the android api that the application is going to use.
  • It lists the instrumentation classes. The instrumentation classes provides profiling and other informations. These informations are removed just before the application is published etc.

This is the required xml file for all the android application and located inside the root directory.

(vii) Android R.java file : Android R.java is an auto-generated file by aapt (Android Asset Packaging Tool) that contains resource IDs for all the resources of res/ directory.

If you create any component in the activity_main.xml file, id for the corresponding component is automatically created in this file. This id can be used in the activity source file to perform any action on the component.

(viii) Android Hide Title Bar Example : The requestWindowFeature(Window.FEATURE_NO_TITLE) method of Activity must be called to hide the title. But, it must be coded before the setContentView method.

  1.    @Override
  2.     protected void onCreate(Bundle savedInstanceState) {
  3.         super.onCreate(savedInstanceState);
  4.         requestWindowFeature(Window.FEATURE_NO_TITLE);//will hide the title not the title bar
  5.         setContentView(R.layout.activity_main);
  6.     }
  7. }

The setFlags() method of Window class is used to display content in full screen mode. You need to pass theWindowManager.LayoutParams.FLAG_FULLSCREEN constant in the setFlags method.

  1. @Override  
  2. protected void onCreate(Bundle savedInstanceState) {
  3.     super.onCreate(savedInstanceState);
  4.     requestWindowFeature(Window.FEATURE_NO_TITLE);
  5.     //code that displays the content in full screen mode  
  6.     this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
  7.                 WindowManager.LayoutParams.FLAG_FULLSCREEN);//int flag, int mask
  8.     setContentView(R.layout.activity_main);
  9. }

(ix) ArrayAdapter : A concrete BaseAdapter that is backed by an array of arbitrary objects. By default this class expects that the provided resource id references a single TextView. If you want to use a more complex layout, use the constructors that also takes a field id. That field id should reference a TextView in the larger layout resource.

However the TextView is referenced, it will be filled with the toString() of each object in the array. You can add lists or arrays of custom objects. Override the toString() method of your objects to determine what text will be displayed for the item in the list.

To use something other than TextViews for the array display, for instance, ImageViews, or to have some of data besides toString() results fill the views, override getView(int, View, ViewGroup) to return the type of view you want.

(x) Android Activity Lifecycle : Android Activity Lifecycle is controlled by 7 methods of android.app.Activity class. The android Activity is the subclass of ContextThemeWrapper class.

An activity is the single screen in android. It is like window or frame of Java.

By the help of activity, you can place all your UI components or widgets in a single screen.

The 7 lifecycle method of Activity describes how activity will behave at different states.

Let’s see the 7 lifecycle methods of android activity.

Method

Description

onCreate

called when activity is first created.

onStart

called when activity is becoming visible to the user.

onResume

called when activity will start interacting with the user.

onPause

called when activity is not visible to the user.

onStop

called when activity is no longer visible to the user.

onRestart

called after your activity is stopped, prior to start.

onDestroy

called before the activity is destroyed.

  1. package com.example.activitylifecycle;

  2. import android.os.Bundle;

  3. import android.app.Activity;

  4. import android.util.Log;

  5. import android.view.Menu;

  6. public class MainActivity extends Activity {

  7.     @Override

  8.     protected void onCreate(Bundle savedInstanceState) {

  9.         super.onCreate(savedInstanceState);

  10.         setContentView(R.layout.activity_main);

  11.         Log.d(“lifecycle”,“onCreate invoked”);  

  12.     }

  13.     @Override

  14.     protected void onStart() {

  15.         super.onStart();

  16.          Log.d(“lifecycle”,“onStart invoked”);  

  17.     }

  18.     @Override

  19.     protected void onResume() {

  20.         super.onResume();

  21.          Log.d(“lifecycle”,“onResume invoked”);  

  22.     }

  23.     @Override

  24.     protected void onPause() {

  25.         super.onPause();

  26.          Log.d(“lifecycle”,“onPause invoked”);  

  27.     }

  28.     @Override

  29.     protected void onStop() {

  30.         super.onStop();

  31.          Log.d(“lifecycle”,“onStop invoked”);  

  32.     }

  33.        @Override

  34.     protected void onRestart() {

  35.         super.onRestart();

  36.          Log.d(“lifecycle”,“onRestart invoked”);  

  37.     }

  38.     @Override

  39.     protected void onDestroy() {

  40.         super.onDestroy();

  41.          Log.d(“lifecycle”,“onDestroy invoked”);  

  42.     }

  43. }

2) Who is the founder of Android?

Andy Rubin.

3) What are the code names of android?

  1. Aestro
  2. Blender
  3. Cupcake
  4. Donut
  5. Eclair
  6. Froyo
  7. Gingerbread
  8. Honycomb
  9. Ice Cream Sandwitch
  10. Jelly Bean
  11. Kitkat

4) What are the advantages of android?

Open-source: It means no licence, distribution and development fee.

Platform-independent: It supports windows, mac and linux platforms.

Supports various technologies: It supports camera, bluetooth, wifi, speech, EDGE etc. technologies.

Highly optimized Virtual Machine: Android uses highly optimized virtual machine for mobile devices, called DVM (Dalvik Virtual Machine).

5) Does android support other language than java?

Yes, android app can be developed in C/C++ also using android NDK (Native Development Kit). It makes the performance faster. It should be used with android SDK.

6) What are the core building blocks of android?

The core building blocks of android are:

  • Activity
  • View
  • Intent
  • Service
  • Content Provider
  • Fragment etc.

7) What is the name of database used in android?

SQLite: An opensource and lightweight relational database for mobile devices.

8) What is AAPT?

AAPT is an acronym for android asset packaging tool. It handles the packaging process.

9) What is ADB?

ADB stands for Android Debug Bridge. It is a command line tool that is used to communicate with the emulator instance.

10) What is NDK?

NDK stands for Native Development Kit. By using NDK, you can develop a part of app using native language such as C/C++ to boost the performance.

Expert Level Question                                                                                                          

1. What is the relationship between the life cycle of an AsyncTask and an Activity? What problems can this result in? How can these problems be avoided?

Answer:: An AsyncTask is not tied to the life cycle of the Activity that contains it. So, for example, if you start an AsyncTask inside an Activity and the user rotates the device, the Activity will be destroyed (and a new Activity instance will be created) but the AsyncTask will not die but instead goes on living until it completes.

Then, when the AsyncTask does complete, rather than updating the UI of the new Activity, it updates the former instance of the Activity (i.e., the one in which it was created but that is not displayed anymore!). This can lead to an Exception (of the type java.lang.IllegalArgumentException: View not attached to window manager if you use, for instance, findViewById to retrieve a view inside the Activity).

There’s also the potential for this to result in a memory leak since the AsyncTask maintains a reference to the Activty, which prevents the Activity from being garbage collected as long as the AsyncTask remains alive.

For these reasons, using AsyncTasks for long-running background tasks is generally a bad idea . Rather, for long-runningbackground tasks, a different mechanism (such as a service) should be employed.

2. There are four Java classes related to the use of sensors on the Android platform. List them and explain the purpose of each.

Answer :: The four Java classes related to the use of sensors on the Android platform areL

  • Sensor: Provides methods to identify which capabilities are available for a specific sensor.
  • SensorManager: Provides methods for registering sensor event listeners and calibrating sensors.
  • SensorEvent: Provides raw sensor data, including information regarding accuracy.
  • SensorEventListener: Interface that defines callback methods that will receive sensor event notifications.

3.What is DDMS? Describe some of its capabilities.

Answer : DDMS is the Dalvik Debug Monitor Server that ships with Android. It provides a wide array of debugging features including:

  • port-forwarding services
  • screen capture
  • thread and heap information
  • network traffic tracking
  • incoming call and SMS spoofing
  • simulating network state, speed, and latency
  • location data spoofing

4. What is Dalvik Virtual Machine?

The name of Android’s virtual machine. The Dalvik VM is an interpreter-only virtual machine that executes files in the Dalvik Executable (.dex) format, a format that is optimized for efficient storage and memory-mappable execution. The virtual machine is register-based, and it can run classes compiled by a Java language compiler that have been transformed into its native format using the included “dx” tool. The VM runs on top of Posix-compliant operating systems, which it relies on for underlying functionality (such as threading and low level memory management). The Dalvik core class library is intended to provide a familiar development base for those used to programming with Java Standard Edition, but it is geared specifically to the needs of a small mobile device.

5. What is Android Runtime?

Android includes a set of core libraries that provides most of the functionality available in the core libraries of the Java programming language. Every Android application runs in its own process, with its own instance of the Dalvik virtual machine. Dalvik has been written so that a device can run multiple VMs efficiently. The Dalvik VM executes files in the Dalvik Executable (.dex) format which is optimized for minimal memory footprint. The VM is register-based, and runs classes compiled by a Java language compiler that have been transformed into the .dex format by the included “dx” tool.

6. What is the Open Handset Alliance?

The OHA is a consortium of 84 technology and mobile companies that have joined hands to accelerate innovation in mobile technology and at the same time offer the end users a better, cost-effective and richer mobile experience. Members of this include Google, HTC, Sony, Dell, Intel, Motorola, Qualcomm, Texas Instruments, Samsung, LG, T-Mobile, Nvidia. The OHA was started on 5 November 2007 by Google and 34 other companies. Android is the main software of the alliance.

7. What is the difference between Service and Thread?

Service is like an Activity but has no interface. Probably if you want to fetch the weather for example you won’t create a blank activity for it, for this you will use a Service. It is also known as Background Service because it performs tasks in background. A Thread is a concurrent unit of execution. You need to know that you cannot update UI from a Thread. You need to use a Handler for this.

8.What is the importance of XML-based layouts?

The use of XML-based layouts provides a consistent and somewhat standard means of setting GUI definition format. In common practice, layout details are placed in XML files while other items are placed in source files.

9. What are the steps in creating a bounded service through AIDL.

1. create the .aidl file, which defines the programming interface

2. implement the interface, which involves extending the inner abstract Stub class as well as implanting its methods.

3. expose the interface, which involves implementing the service to the clients.

10. What data types are supported by AIDL?

AIDL has support for the following data types:

string

charSequence

List

Map

all native Java data types like int, long, char and Boolean

11.What is the difference between a regular bitmap and a nine-patch image?

In general, a Nine-patch image allows resizing that can be used as background or other image size requirements for the target device. The Nine-patch refers to the way you can resize the image: 4 corners that are unscaled, 4 edges that are scaled in 1 axis, and the middle one that can be scaled into both axes.

Basic HTTP Authentication in iOS while calling webservice


– (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {

    if ([challenge previousFailureCount] == 0) {

        NSLog(@”received authentication challenge”);

        NSURLCredential *newCredential = [NSURLCredentialcredentialWithUser:@”tylerhorne”

                                                                    password:@”m2n1shlko”

                                                                 persistence:NSURLCredentialPersistenceForSession];

        NSLog(@”credential created”);

        [[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];

        NSLog(@”responded to authentication challenge”);

    }

    else {

        NSLog(@”previous authentication failure”);

    }

}