Introduction

In this tutorial, we are going to learn about HTTP/HTTPS POST & GET Requests. Http is an underlying protocol used by world wide web. POST and GET are two most commonly used HTTP methods for request and response between the client and the server. GET method basically requests data from specified resource, whereas Post method submits data to be processed to a specified resource.

Step 2

Create new project

1. Create a new project in Android Studio. File => New => New Project.

2. Give the application name and then click Next. Select the platform and API and then click Next.

3. Select Empty Activity and click Next. Give the activity name or you can use default name.

4. And finally click Finish.

Step 3

Give Permission

You need to provide some permissions to access the internet from your application. So, open your AndroidManifest.xml file and add the following code snippet.

1

<uses-permissionandroid:name="android.permission.INTERNET"/>

Step 4

Create layout show response

In activity_main.xml file, add two button named “Send POST Request” and “Send GET Request” and set an on click listener to them. Methods called on onClick() method will be sendPostRequest() and sendGetRequest() respectively.

Add TextView and give it a unique id. So that we can show the response in the textview by calling its id. You can use the code written below:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Send POST Request"

android:id="@+id/sendPost"

android:layout_alignParentTop="true"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true"

android:layout_alignRight="@+id/sendGet"

android:layout_alignEnd="@+id/sendGet"

android:onClick="sendPostRequest"/>

<Button

style="?android:attr/buttonStyleSmall"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Send GET Request"

android:id="@+id/sendGet"

android:layout_below="@+id/sendPost"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true"

android:layout_alignParentRight="true"

android:layout_alignParentEnd="true"

android:onClick="sendGetRequest"/>

<TextView

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="Response..."

android:id="@+id/showOutput"

android:layout_below="@+id/sendGet"

android:layout_alignParentRight="true"

android:layout_alignParentEnd="true"/>

Step 5

Send Post Request

We have to create a class which sends Post request asynchronously.

1

2

3

4

5

6

privateclassPostClass extendsAsyncTask<String, Void, Void> {

@Override

protectedVoid doInBackground(String... params) {

returnnull;

}

}

Get the textview context, then set a url using URL class and parameters in a string.

1

2

3

finalTextView outputView = (TextView) findViewById(R.id.showOutput);

URL url = newURL("Your URL");</pre>

<pre>String urlParameters = "fizz=buzz";

Now open the connection using HttpURLConnection and set its properties like method, user_agent and language.

connection.setDoOutput(true); // You need to set it to true if you want to send (output) a request body, for example with POST or PUT requests. Sending the request body itself is done via the connection's output stream:

Now, we have to use DataOutPutStream for controlling the output. We can do multiple operation on output stream using DataOutPutStream, It also helps us to write primitive Java data types to an output stream.

dStream.writeBytes(urlParameters); //Writes out the string to the underlying output stream as a sequence of bytes

dStream.flush(); // Flushes the data output stream.

dStream.close(); // Closing the output stream.

Next step in the process would be getting the response from server using BufferedReader. It reads text from a character-input stream, buffering characters so as to provide for efficient reading of characters, arrays, and lines.

Questions inside:
What is a protocol?
How do you submit an app to the app store?
What is ARC?
What is an app bundle?
When would you use a swift struct vs class?
What is pass by value vs pass by type?
How do you create a custom view?
How to do http requests and parse JSON?
What do you use to show a list of data on the screen?
What is polymorphism?
What is UIWindow? UIApplication?
Difference between viewDidLoad and viewWillAppear?
What is NSNotificationCenter? Delegates?
How do threads work in iOS?
Diff between XIBs and Storyboard files?

Rate this:

Share this:

In this tutorial I’ll explain you how to fill an iOS UITableView component by loadingthe data directly from an URL using the JSON format. You’ll see how to define a tableview controller in swift, how to load the data from URL and how to extract the data from the JSON format.

Define the project

Let’s create a new Swift iOS single view project.

In the Main.storyboard you can disable the use size classes option.

Now you can removethe View controller that is inside the storyboard as default, we don’t need that!

Define the layout and the custom classes

In the Main.storyboard you’ve to add the UITableViewController element.

Now you’ve to set a custom class for the UITableViewController that allows you to manage the data that will be displayed.

Create a new iOS Cocoa Touch Class and set the subclass asUITableViewController and the name of the class as TableController and create it.

Now in the Main.storyboard select again your UITableViewController and in the identity inspector set the TableController class that you’ve prevously created.

In the Attribute inspector turn on the is initial view controller option.

Now you have to select the table view cell and under the attribute inspector set the identifier to cell.

TableController custom class

Now you’ve to implement the table controller class. This class is the core of the table. Here you’ll define the download function, the json extractor function and finally the cell definition.

The first thing you’ve to do is to define the array that will be used to store and read the data. Let’s define the TableData String array as:

varTableData:Array<String>=Array<String>()

The viewDidLoad() is the function that will be called as soon as the view has been loaded. Inside it you should call the get_data_from_url function. We will define this function later, but let’s add the function call placeholder.

Configure now the cell to load the array string at the position defined by the indexPath object. The “cell” identifier is the same identifier name that you previously set for the cell element. The cellForRowAtIndexPath function is called for every cell that is visible on the screen at a particular moment. So, for example, if you have to load 200 cells on your table, this function is called only 10-15 times, that’s because only the elements that have to be displayed are loaded. Every time you scroll your table, this function is called again for the items that have to be displayed.
In this case we’ll use the textlabel that is defined in the default cell layout.

When the get_data_from_url function has done the download of the json data, the extract_json function is called. Let’s now implement it. This function will extract the json data and fill the TableData array. In a JSONformat there are two different main types: the array and the objects. Arrays are identified by the [ ] brackets while the object are identified by the { } brackets. This two types in Swift are defined by NSArray and NSDictionary respectively. For every JSON object you’ve to define a safe variable (using let and the question mark) with the right type. The json used in this example has this structure:

Rate this:

Share this:

The YouTube Android Player API enables you to incorporate video playback functionality into your Android applications. The API allows you to load and play YouTube videos (and playlists) and to customize and control the video playback experience.

You can load or cue videos into a player view embedded in your application’s UI. You can then control playback programmatically. For example play, pause, or seek to a specific point in the loaded video. You can register event listeners to get callbacks for certain events, such as the player loading a video or the player state changing. The API also has helper functionality to support orientation changes as well as transitions to fullscreen playback.

More from this author

To get started, create a new project. I called mine VideoTube. In the Next screens of the Android Studio wizard select API 10, Blank Activity and MainActivity as the activity name.

Before using the Android Youtube API, you need to register your application, including your digitally signed .apk file’s public certificate in the Google Developers Console. To register the application, follow these steps.

On the page that appears after project creation, expand APIs & auth on the left sidebar. Next, click APIs. In the list of APIs, click on YouTube Data API and enable the Youtube Data API v3 on the page that follows.

In the sidebar on the left, select Credentials. For credentials, the API supports OAuth 2.0, the use of an API key and of a Service account. We’ll use the API key option.

Select API key from the Add Credentials dropdown menu. A popup will appear for you to specify the key type. Select Android Key. Next select Add package name and fingerprint and add the Android app’s package name (Mine is com.echessa.videotube) and then run the following command in Terminal to get the SHA-1 certificate fingerprint.

keytool -list -v-keystore ~/.android/debug.keystore

Enter android as the password when prompted. The above command prints information on the debug keystore that is located at ~/.android/debug.keystore on your computer. This was generated automatically by Eclipse or Android Studio when you first built an Android app. In the Terminal, you will see the MD5 and SHA-1 certificate fingerprints. Copy the SHA-1 fingerprint and paste it on the Google Developer Console and click on the Create button. An API key will be generated. We’ll use this later.

Back in the Android app, create a class named Config.java and paste in the following.

Download the latest version of the YouTube Android Player API (1.2.1 at the time of writing). Unzip the downloaded file to find the library jar file and a sample application that you can use to see what the library offers. The jar file is located in the libs folder. Copy and paste it into your project’s libs folder. To access the libs folder, use the Project perspective on the Android Studio Project Explorer. Then expand VideoTube -> app -> libs.

Change back to the Android perspective, select the build.gradle (Module: app) file and add the following to the dependencies.

compile files('libs/YouTubeAndroidPlayerApi.jar')

Sync the project’s gradle files.

Add the following permission for internet access to the AndroidManifest.xml file as a child of the manifest tag and a sibling to the application.

<uses-permission android:name="android.permission.INTERNET"/>

Edit the strings.xml file as shown. These are all the string resources we’ll require.

In the above code, we created a class that is a subclass of YouTubeBaseActivity. This is required to make use of YouTubePlayerView. We implemented YouTubePlayer.OnInitializedListener to listen for initialization success or failure. The interface has two methods, named onInitializationFailure() and onInitializationSuccess(). If initialization is successful, the cueVideo() method plays the YouTube video and incase of failure, checks to see whether the error is recoverable by user action.

If it’s not then a Toast of the error is shown to the user and if it’s user-recoverable, then the getErrorDialog() method shows a dialog that will enable the user to recover from the error.

For example, if the YouTube app isn’t installed on the user’s device or is out of date, the dialog will have a prompt that upon confirmation, will open the Google Play Store for the user to install or update it accordingly. If the YouTube app is disabled on the device, then the prompt will open System Settings for the user to enable it.

When the user returns from the error recovery dialog, onActivityResult() is called checks to see if the user performed a recovery action. If so, we retry initialization.

Run the app and you should be able to play the video specified in the code. Note that you will need the YouTube app on your device. The API client library interacts with a service that is distributed as part of the YouTube app for the Android platform. Users need to run version 4.2.16 of the mobile YouTube app (or higher) to use the API. Generally, devices running Android 2.2 (Froyo) or later that have the Google Play Store app should be able to run the up-to-date version of the YouTube app.

What this means, is that unless you have installed Google Apps on your virtual device, you won’t be able to test the code on the emulator. The default Android emulator doesn’t support installing Google Apps on the device, but if you use an emulator like Genymotion you will be able to (despite the team discontinuing support for Google Apps). Even with Google Apps installed on my emulator, I still could not play the video. The video thumbnail loaded okay on the view, but upon tapping the Play button, a loading indicator would appear, but then loading would fail with a message of ‘Connection to server lost’. You probably need a real device for this.

Responding to Playback Events and State Changes

In the app, you might need to take some action depending on the YouTube player’s events such as buffering, play, pause, seek and stop. You might want to show the user a message or overlay the player view with another view once video playback stops or ends.

The YouTubePlayer has the following interface definitions to listen to such events:

YouTubePlayer.PlayerStateChangeListener – Interface definition for callbacks which invoked when the high level player state changes.

YouTubePlayer.OnFullscreenListener – Interface definition for callbacks which invoked when the player toggles between fullscreen on or off, either due to the user clicking the fullscreen button or a call to setFullscreen(boolean).

This will create a Toast with the message passed into the function. This will save us from writing similar lines of code.

Next add the following two subclasses to the MainActivity class.

privatefinalclassMyPlaybackEventListenerimplementsYouTubePlayer.PlaybackEventListener{
@Override
publicvoidonPlaying(){// Called when playback starts, either due to user action or call to play().showMessage("Playing");}
@Override
publicvoidonPaused(){// Called when playback is paused, either due to user action or call to pause().showMessage("Paused");}
@Override
publicvoidonStopped(){// Called when playback stops for a reason other than being paused.showMessage("Stopped");}
@Override
publicvoidonBuffering(boolean b){// Called when buffering starts or ends.}
@Override
publicvoidonSeekTo(int i){// Called when a jump in playback position occurs, either// due to user scrubbing or call to seekRelativeMillis() or seekToMillis()}}privatefinalclassMyPlayerStateChangeListenerimplementsYouTubePlayer.PlayerStateChangeListener{
@Override
publicvoidonLoading(){// Called when the player is loading a video// At this point, it's not ready to accept commands affecting playback such as play() or pause()}
@Override
publicvoidonLoaded(String s){// Called when a video is done loading.// Playback methods such as play(), pause() or seekToMillis(int) may be called after this callback.}
@Override
publicvoidonAdStarted(){// Called when playback of an advertisement starts.}
@Override
publicvoidonVideoStarted(){// Called when playback of the video starts.}
@Override
publicvoidonVideoEnded(){// Called when the video reaches its end.}
@Override
publicvoidonError(YouTubePlayer.ErrorReason errorReason){// Called when an error occurs.}}

The above creates classes that implement the YouTubePlayer.PlaybackEventListener and YouTubePlayer.PlayerStateChangeListener interfaces. For each class, I have implemented the interface methods and included a comment of when the callback is invoked. You can take whatever action you want in each callback. For our example, I have included a Toast output for the onPlaying(), onPaused() and onStopped() methods that will output a message when the event happens.

Run the app and you should see different Toast messages appear when you start playing the video, when you pause it and when it stops (for a reason other than being paused, e.g. the video ending or a playback error).

Custom Player Controls

The YouTube library does a good job of creating an out-of-the-box user friendly interface to play YouTube videos. As a developer, you might want to take this further and provide custom controls that will give the user more control over playback. For example, enable them to jump back and forth in the video, or enable them to play the next or previous video in a playlist.

We’ll create a control in our app that will enable the user to jump to a specific time in the video.

The API provides two methods to jump playback:

seekToMillis() – Seeks to the specified time in the video.

seekRelativeMillis() – Seeks forward or backwards by the specified number of seconds.

Run the app and you should be able to enter a number (in seconds) and have the video skip to that point. If you input a number that is larger than the duration of the video, then the video will skip to the end.

Conclusion

In this tutorial, we have looked at how to embed a YouTube player in your app. This is handy if you want your app users to be able to play YouTube videos while remaining in your app, instead of the YouTube app opening to play the video and then the user returning to your app after playback.

The YouTube Android library provides a great API that enables you to customise this experience and we’ve only touched on its capabilities. To find out more about the library, be sure to read through the documentation and the sample app that comes with the library download.

Rate this:

Share this:

Google has introduced a new design guideline with the release of Android 5.0 (Lollipop) known as Material Design, and with this guidelines Google provide Material Theme to the android developer. This is a new user interface. In this post, I will show you way to use custom material design theme and color in your application.

Setup Material Theme

First of all, you have to setup material design theme to your styles.xml file. You can choose any of three material themes according to your wish:
• Theme.Material
• Theme.Material.Light
• Theme.Material.Light.DarkActionBar
Here I have used Theme.Material.Light.DarkActionBar as app theme.