Rest API Call for GET and POST

@RestResource(urlMapping=’/Account/*’)
global with sharing class MyRestResource {

@HttpGet
global static Account doGet() {
RestRequest req = RestContext.request;
RestResponse res = RestContext.response;
String accountId = req.requestURI.substring(req.requestURI.lastIndexOf(‘/’)+1);
Account result = [SELECT Id, Name, Phone, Website FROM Account WHERE Id = :accountId];
return result;
}

@HttpPost
global static String doPost(String name,
String phone, String website) {
Account account = new Account();
account.Name = name;
account.phone = phone;
account.website = website;
insert account;
return account.Id;
}
}

OUTPUT->

  1. GET – call following URL in workbench rest explorer 

    “https://instance.salesforce.com/services/apexrest/Account/accountId”

  2. POST – 

    “https://instance.salesforce.com/services/apexrest/Account/”

    JSON Format-

{
“name” : “Wingo Ducks”,
“phone” : “707-555-1234”,
“website” : “www.wingo.ca.us”
}

 

 

What are Salesforce ID’s composed of?

The Id Field Type is a base-62 encoded string.

Each character can be one of 62 possible values:

  • a lowercase letter (a-z) – 26 values
  • an uppercase letter (A-Z) – 26 values
  • a numeric digit (0-9) – 10 values

As there is a combination of lower and upper case letters the casing of the 15 character Id has significance. E.g. 50130000000014 c is a different ID from 50130000000014C.

Within a 15 character Id the breakdown is:

  • First 3 characters – Key Prefix As per Jon’s answer, the first 3 characters are the key prefix that identify the object type. There are a few exceptions to this where multiple objects all share the same key prefix! There are a number of fixed key prefixes that are common across all of Salesforce. Custom objects get a unique key prefix per Org. Custom objects in managed packages can have a different key prefix in each installed org.
  • The 4th Character – instance/pod identifier
  • 5th Character – instance/pod identifier – extended
  • 6th character – Reserved. Will be 0 until such time that Salesforce has a need for it.
  • Remaining 9 characters – basically a really big number. Like 62^9 big or 238,328! That’s a lot of servers!

To this you can add an optional 3 character suffix that will make the Id unique case-insensitive. This is useful when working with programs that can’t maintain the case of the ID (E.g. Excel VLookup).

What is REST API in PHP?

Before explaining what is ‘REST API‘ we should know what is ‘REST’ and ‘API’.

REST stands for ‘Representational State Transfer’. REST is web standards-based architecture and uses HTTP Protocol for exchanging data between applications or systems. It is a simple way to interact with independent systems.

API stands for ‘Application Programming Interface’. Basically, these are small functions which allow two different systems to talk/interact with each other.

In many applications REST API’s are used because it’s a simple and lightest way to Create, Read, Update, Delete (CRUD) data between different applications over the internet. To develop Android, IOS mobile apps REST APIs are being used.

When you hit an API your request is being sent to the remote server, then it performs some required functions and returns its response in JSON or in XML format.

In REST API following HTTP methods are used,

GET – Use to retrieve data.
POST – It is used to add or insert data into a database.
PUT/PATCH – It is used to update any existing records.
DELETE – To delete any existing records DELETE method is used.

Uploading image to Google Drive from Android

Below code will help to upload image directly to your google drive

private void saveFileToDrive() {

    final Bitmap image = mBitmapToSave;
    Drive.DriveApi.newDriveContents(getGoogleApiClient())
            .setResultCallback(new ResultCallback<DriveApi.DriveContentsResult>() {

                @Override
                public void onResult(DriveApi.DriveContentsResult result) {

                    if (!result.getStatus().isSuccess()) {
                        Log.i("ERROR", "Failed to create new contents.");
                        return;
                    }

                    final DriveContents driveContents = result.getDriveContents();

                    new Thread() {
                        @Override
                        public void run() {
                            // write content to DriveContents
                            OutputStream outputStream = driveContents.getOutputStream();
                            // Write the bitmap data from it.
                            ByteArrayOutputStream bitmapStream = new ByteArrayOutputStream();
                            image.compress(Bitmap.CompressFormat.PNG, 100, bitmapStream);
                            try {
                                outputStream.write(bitmapStream.toByteArray());
                            } catch (IOException e1) {
                                Log.i("ERROR", "Unable to write file contents.");
                            }
                            // Create the initial metadata - MIME type and title.
                            // Note that the user will be able to change the title later.
                            MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
                                    .setMimeType("image/jpeg").setTitle("Android Photo.png").build();
                            // Create an intent for the file chooser, and start it.
                            IntentSender intentSender = Drive.DriveApi
                                    .newCreateFileActivityBuilder()
                                    .setInitialMetadata(metadataChangeSet)
                                    .setInitialDriveContents(driveContents)
                                    .build(getGoogleApiClient());
                            try {
                                startIntentSenderForResult(
                                        intentSender, REQUEST_CODE_CREATOR, null, 0, 0, 0);
                            } catch (IntentSender.SendIntentException e) {
                                Log.i("ERROR", "Failed to launch file chooser.");
                            }
                        }
                    }.start();


                }
            });
}

Maintain cookie session in Android(Retrofit)

A session is a sequence of requests made by a single end-user during a visit to a particular site. A session or query session may be all queries made by a user in a particular time period or it may also be a series of queries or navigation with a consistent underlying user need.

In Android, if we use the retrofit for web services call it internally uses OkHttp and OkHttp does not keep the track of session automatically. Generally, the session is maintained using the cookie value that we get in each response we receive.

So, we need to keep the cookie from one call to another. this can be down using CookieManager as follows:

HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

CookieHandler cookieHandler = new CookieManager();
OkHttpClient client = new OkHttpClient.Builder().addNetworkInterceptor(interceptor)
.cookieJar(new JavaNetCookieJar(cookieHandler))
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build();

Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();

for this following dependencies are required:

compile ‘com.squareup.okhttp3:logging-interceptor:3.4.1’
compile ‘com.squareup.okhttp3:okhttp:3.4.1’
compile ‘com.squareup.okhttp3:okhttp-urlconnection:3.6.0’

Get CrashLogs with Fabric Crashlytics

Crashlytics provides deep and actionable insights, even the exact line of code your app crashed on. While Crashlytics gives you powerful crash reporting, with one additional click you can enable real-time analytics that help you understand what’s happening in your app.

Installation:

1. Add kit to your Podfile.

use_frameworks!
pod ‘Fabric’
pod ‘Crashlytics’

Then run following command in your terminal

pod install

2. In Project Navigator select your project from targets -> go to Build Phase -> click on plus button and add “New Run Script Phase” and paste following code

“${PODS_ROOT}/Fabric/run” ba500759ec59e71c692c2e3e003edd73e25207c2 13fd4768392c1fb440b9bb7447dab03757c569a498a25c7e667fdbdefd52f57b

3. Add API in Info.plist file

<key>Fabric</key>
<dict>
<key>APIKey</key>
<string>ba500759ec59e71c692c2e3e003edd73e25207c2</string>
<key>Kits</key>
<array>
<dict>
<key>KitInfo</key>
<dict/>
<key>KitName</key>
<string>Crashlytics</string>
</dict>
</array>
</dict>

 

Initialize Your Kit

In AppDelegate. swift file

import Fabric
import Crashlytics

Then in application DidFinishLaunch method

Fabric.with([Crashlytics.self])

 

To get User Information

  • Add following method in your appDelegate file and call this method after  Fabric.with([Crashlytics.self]) this
  • line of code.
  • func logUser() {
    // TODO: Use the current user’s information
    // You can call any combination of these three methods
    Crashlytics.sharedInstance().setUserEmail(“user@fabric.io”)
    Crashlytics.sharedInstance().setUserIdentifier(“12345”)
    Crashlytics.sharedInstance().setUserName(“Test User”)
    }

 

 

 

Reduce friction with the new Location APIs

The new APIs do not require your app to manually manage a connection to Google Play services through a GoogleApiClient. This reduces boilerplate and common pitfalls in your app.

 

A better developer experience

The new LocationServices APIs are much simpler and will make your code less error prone. The connection logic is handled automatically, and you only need to attach a single completion listener:

 

public class MainActivity extends AppCompatActivity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    FusedLocationProviderClient client =
            LocationServices.getFusedLocationProviderClient(this);

    client.requestLocationUpdates(LocationRequest.create(), pendingIntent)
        .addOnCompleteListener(new OnCompleteListener() {
          @Override
          public void onComplete(@NonNull Task task) {
            Log.d("MainActivity", "Result: " + task.getResult());
          }
        });
  }
}

The new API immediately improves the code in a few ways:

  • The API calls automatically wait for the service connection to be established, which removes the need to wait for onConnected before making requests.
  • It uses the Task API which makes it easier to compose asynchronous operations.
  • The code is self-contained and could easily be moved into a shared utility class or similar.
  • You don’t need to understand the underlying connection process to start coding.

What happened to all of the callbacks?

The new API will automatically resolve certain connection failures for you, so you don’t need to write code that for things like prompting the user to update Google Play services. Rather than exposing connection failures globally in the onConnectionFailed method, connection problems will fail the Task with an ApiException:

client.requestLocationUpdates(LocationRequest.create(), pendingIntent)
        .addOnFailureListener(new OnFailureListener() {
          @Override
          public void onFailure(@NonNull Exception e) {
            if (e instanceof ApiException) {
              Log.w(TAG, ((ApiException) e).getStatusMessage());
            } else {
              Log.w(TAG, e.getMessage());
            }
          }
        });

Read more , or head straight to  https://github.com/googlesamples/android-play-location

Drawable Animation

Drawable animation lets you load a series of Drawable resources one after another to create an animation. This is a traditional animation in the sense that it is created with a sequence of different images, played in order, like a roll of film. The AnimationDrawable class is the basis for Drawable animations.

While you can define the frames of an animation in your code, using the AnimationDrawable class API, it’s more simply accomplished with a single XML file that lists the frames that compose the animation. The XML file for this kind of animation belongs in the res/drawable/ directory of your Android project. In this case, the instructions are the order and duration for each frame of the animation.

The XML file consists of an <animation-list> element as the root node and a series of child <item> nodes that each define a frame: a drawable resource for the frame and the frame duration. Here’s an example XML file for a Drawable animation:

<animation-list xmlns:android=”http://schemas.android.com/apk/res/android”
android:oneshot=”true”>
<item android:drawable=”@drawable/rocket_thrust1″ android:duration=”200″ />
<item android:drawable=”@drawable/rocket_thrust2″ android:duration=”200″ />
<item android:drawable=”@drawable/rocket_thrust3″ android:duration=”200″ />
</animation-list>

This animation runs for just three frames. By setting the android:oneshot attribute of the list to true, it will cycle just once then stop and hold on the last frame. If it is set false then the animation will loop. With this XML saved as rocket_thrust.xml in the res/drawable/ directory of the project, it can be added as the background image to a View and then called to play. Here’s an example Activity, in which the animation is added to an ImageView and then animated when the screen is touched:

AnimationDrawable rocketAnimation;

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

ImageView rocketImage = (ImageView) findViewById(R.id.rocket_image);
rocketImage.setBackgroundResource(R.drawable.rocket_thrust);
rocketAnimation = (AnimationDrawable) rocketImage.getBackground();
}

public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
rocketAnimation.start();
return true;
}
return super.onTouchEvent(event);
}
It’s important to note that the start() method called on the AnimationDrawable cannot be called during the onCreate() method of your Activity, because the AnimationDrawable is not yet fully attached to the window. If you want to play the animation immediately, without requiring interaction, then you might want to call it from the onWindowFocusChanged() method in your Activity, which will get called when Android brings your window into focus.

PHP for the Internet of Things

Analysts claim the connected devices to reach the mark of 6.5 billion by the starting of 2017. This makes PHP and IOT go hand in hand. Thanks to icicle, one can write asynchronous code using synchronous coding techniques in PHP. It means that now the PHP code is able to run several tasks by using the same script. Methods of asynchronous programming provide better data exchange between connected gadgets. Some hardware platforms such as Arduino already support PHP, and you can control Arduino board with your PHP-based script. There is also a possibility to build a PHP application that uses GPS data gathered from an IOT device. Like the GPS sensor on your Android phone can send its location to the Bluemix cloud, and the PHP application is able to publish this data on your website.