Get YouTube video information with Retrofit and keep it in the Android app.

In this article, we will do three main things.

  1. [Register your app in the list when you "share" from Youtube. ](# -1-Register your app in the list when sharing from youtube)
  2. [Obtain an ID from the link information when "sharing", and acquire Youtube video information from that ID. ](# -2-Obtain the id from the link information when sharing and get the youtube video information from that id)
  3. [Access the API with Retrofit & Gson. The video information is displayed on the acquisition application. ](# -3-retrofit--Access api with gson Get video information Display on app-)

The code is here. SharedText

1. Register your app in the list when "sharing" from Youtube.

First, add an intent-filter to Manifest.xml.

AndroidManifest.xml


// ...Omission...
  <activity android:name=".SharedActivity">
      <intent-filter>
          <action android:name="android.intent.action.SEND" />
          <category android:name="android.intent.category.DEFAULT" />
          <data android:mimeType="text/plain"/>
      </intent-filter>
  </activity>
// ...Omission...

Next, try receiving it with SharedActivity.java.

SharedActivity.java


public class SharedActivity extends AppCompatActivity {

    TextView textView;
    ImageView thumbnail;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shared);

        textView = findViewById(R.id.movieId);
        thumbnail = findViewById(R.id.thumbnail);

        Intent intent = getIntent();
        String id = null;

        if(intent.getType().equals("text/plain")){
            String text = intent.getStringExtra(Intent.EXTRA_TEXT);
            Log.d("text",text);
        }
    }
// ...Omission...
}

Now you can receive the link passed by Intent to text.

[reference]

2. Get the ID from the link information when "sharing" and its Get Youtube video information from ID.

How to get an ID

This obediently extracted the ID from the link string. https://youtu.be/yT_ylSCgY6Q Since you can get the character string like this, the trailing yT_ylSCgY6Q is the ID of the video.

By the way, the link above will take you to BUMP OF CHICKEN feat. HATSUNE MIKU "ray".

Get YouTube video information.

To get YouTube video information, like the article Getting YouTube video information using Data API v3, ** Youtube Data API ** is used. Obtain the API key and enter the following URL in your browser. For information on how to get the API Key, please refer to Getting YouTube video information using Data API v3.

https://www.googleapis.com/youtube/v3/videos?id=yT_ylSCgY6Q&key=【API Key】&fields=items(id,snippet(channelTitle,title,thumbnails),statistics)&part=snippet,contentDetails,statistics

Enter the acquired key in the [API Key] part.

The result is as follows.

result


{
 "items": [
  {
   "id": "yT_ylSCgY6Q",
   "snippet": {
    "title": "BUMP OF CHICKEN feat. HATSUNE MIKU「ray」",
    "thumbnails": {
     "default": {
      "url": "https://i.ytimg.com/vi/yT_ylSCgY6Q/default.jpg ",
      "width": 120,
      "height": 90
     },
     "medium": {
      "url": "https://i.ytimg.com/vi/yT_ylSCgY6Q/mqdefault.jpg ",
      "width": 320,
      "height": 180
     },
     "high": {
      "url": "https://i.ytimg.com/vi/yT_ylSCgY6Q/hqdefault.jpg ",
      "width": 480,
      "height": 360
     },
     "standard": {
      "url": "https://i.ytimg.com/vi/yT_ylSCgY6Q/sddefault.jpg ",
      "width": 640,
      "height": 480
     },
     "maxres": {
      "url": "https://i.ytimg.com/vi/yT_ylSCgY6Q/maxresdefault.jpg ",
      "width": 1280,
      "height": 720
     }
    },
    "channelTitle": "BUMP OF CHICKEN"
   },
   "statistics": {
    "viewCount": "12691874",
    "likeCount": "65136",
    "dislikeCount": "3062",
    "favoriteCount": "0",
    "commentCount": "4337"
   }
  }
 ]
}

[reference]

3. Access API with Retrofit & Gson. The video information is displayed on the acquisition application.

Overview

Introduction

dependencies {
    // ...Omission...
    implementation 'com.google.code.gson:gson:2.8.4'
    implementation 'com.squareup.retrofit2:retrofit:2.4.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
    // ...Omission...
}

[reference]

API interface implementation

ApiService.java


public interface ApiService {
    @Headers("Accept-Language: ja")
    @GET("/youtube/v3/videos?")
    Call<APIResponse> requestMovie(@Query("id") String id,
                                    @Query("key") String key,
                                    @Query("fields") String fields,
                                    @Query("part") String part);
}

Define a class to store the data obtained from API as Java object

APIResponse.java


public class APIResponse {

    public List<Item> items;

    public List<Item> getItems() {
        return items;
    }
}

Item.java


public class Item {

    @SerializedName("id")
    private String id;

    @SerializedName("snippet")
    private Snippet snippet;

    @SerializedName("statistics")
    private Statistics statistics;

    public String getId() {
        return id;
    }

    public Snippet getSnippet() {
        return snippet;
    }

    public Statistics getStatistics() {
        return statistics;
    }
}

Snippet.java


public class Snippet {

    @SerializedName("title")
    private String title;

    @SerializedName("thumbnails")
    private Thumbnails thumbnails;

    public class Thumbnails {

        @SerializedName("default")
        public Default aDefault;

        @SerializedName("medium")
        public Medium medium;

        @SerializedName("high")
        public High high;

        public High getHigh() {
            return high;
        }

        @SerializedName("standard")
        public Standard standard;

        @SerializedName("maxres")
        public Maxres maxres;


        public class Default {
            String url;
            String width;
            String height;
        }

        public class Medium {
            String url;
            String width;
            String height;

        }

        public class High {
            String url;
            String width;
            String height;

            public String getUrl() {
                return url;
            }
        }

        public class Standard {
            String url;
            String width;
            String height;
        }

        public class Maxres {
            String url;
            String width;
            String height;
        }

    }

    @SerializedName("channelTitle")
    String channelTitle;

    public String getTitle() {
        return title;
    }

    public Thumbnails getThumbnails() {
        return thumbnails;
    }

    public String getChannelTitle() {
        return channelTitle;
    }
}

Statistics.java


public class Statistics {

    @SerializedName("viewCount")
    String viewCount;

    @SerializedName("likeCount")
    String likeCount;

    @SerializedName("dislikeCount")
    String dislikeCount;

    @SerializedName("favoriteCount")
    String favoriteCount;

    @SerializedName("commentCount")
    String commentCount;


    public String getViewCount() {
        return viewCount;
    }

    public String getLikeCount() {
        return likeCount;
    }

    public String getDislikeCount() {
        return dislikeCount;
    }

    public String getFavoriteCount() {
        return favoriteCount;
    }

    public String getCommentCount() {
        return commentCount;
    }
}

As I was writing the article, I noticed that I wrote it without thinking too much about modifiers, so I would be grateful if you could do something about it.

Implementation of processing to access YouTube Data API v3 and get video information

MainActivity.java


public class MainActivity extends AppCompatActivity {

    private Retrofit mRetrofit;
    private ApiService mService;

    //API KEY Created from Console
    private final String API_KEY = "dummyAPIKey"; //Please change the API Key as appropriate.
    private final String FIELDS = "items(id,snippet(channelTitle,title,thumbnails),statistics)";
    private final String PART = "snippet,contentDetails,statistics";

    // "BUMP OF CHICKEN feat. HATSUNE MIKU「ray」"
    private String testId = "yT_ylSCgY6Q";

    ImageView picture;
    TextView title;
    Button button;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mRetrofit = new Retrofit.Builder()
                .baseUrl("https://www.googleapis.com")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        mService = mRetrofit.create(ApiService.class);

        picture = findViewById(R.id.picture);
        title = findViewById(R.id.title);
        button = findViewById(R.id.button);
        button.setOnClickListener(onClickListener);
    }
    
    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Call<APIResponse> mCall = mService.requestMovie(testId,API_KEY,FIELDS,PART);

            mCall.enqueue(new Callback<APIResponse>() {
                @Override
                public void onResponse(Call<APIResponse> call, Response<APIResponse> response) {

                    //Get Item from response
                    List<Item> items = response.body().getItems();

                    for(Item item : items){

                        Uri uri = Uri.parse(item.getSnippet().getThumbnails().getHigh().getUrl());
                        Uri.Builder builder = uri.buildUpon();
                        AsyncTaskHttpRequest task = new AsyncTaskHttpRequest(picture);
                        task.execute(builder);
                        
                        title.setText(item.getSnippet().getTitle());
                    }
                }

                @Override
                public void onFailure(Call<APIResponse> call, Throwable t) {

                }
            });

        }
    };
    

}

In addition, I referred to the following site to get the image from the URL and display it in ImageView. Note that even if you copy and paste the above code, the AsyncTaskHttpRequest class will be undefined. [reference]

Layout file implementation

activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/picture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        app:layout_constraintBottom_toTopOf="@+id/title"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@mipmap/ic_launcher" />

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/title"
        app:layout_constraintVertical_bias="0.3" />

</android.support.constraint.ConstraintLayout>

activity.xml


<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp"
    tools:context=".SharedActivity">

    <ImageView
        android:id="@+id/thumbnail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginTop="8dp"
        android:padding="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.201"
        app:srcCompat="@mipmap/ic_launcher" />

    <TextView
        android:id="@+id/movieId"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="TextView"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

AndroidManifest.xml Just in case, I will also post the manifest file.

AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.tomiyama.noir.sharedtext">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".SharedActivity">

            <intent-filter>
                <action android:name="android.intent.action.SEND" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:mimeType="text/plain"/>

            </intent-filter>
        </activity>
    </application>

</manifest>

[reference] It was very helpful when accessing the API around Retrofit. Also, for details, refer to the code posted on Github.

Recommended Posts

Get YouTube video information with Retrofit and keep it in the Android app.
Get your version number in the Android app
[Android development] Get an image from the server in Java and set it in ImageView! !!
Get video information from Nikorepo and throw it to Slack
Get Youtube channel information with Rails app (using Yt gem)
[Rails] Get access_token at the time of Twitter authentication with Sorcery and save it in DB
Graph the sensor information of Raspberry Pi in Java and check it with a web browser
Add the pre-built jar library to Android and call it in the framework
[Rails] How to get the user information currently logged in with devise
Is it possible to put the library (aar) in the Android library (aar) and use it?
The Android app crashes. Just click a button and it will fall.
I'm making an Android app and I'm stuck with errors and how to solve it
[Android] Despaired story with App UserId and SharedUserId
Get the value from the array and find out what number it is included in
I called YouTube video from DB with haml and tried to embed and display it
Vibrate the wristband device with Bluetooth from the Android app
[Java] Get the file path in the folder with List
Implemented pull-down in the original app with Active Hash
Get location information in Rails and sort in ascending order
Access Web API on Android with Get and process Json (Java for the time being)
Until you build a project described in scala with Maven and execute it with the scala command.
Get Android location information
Android app to select and display images from the gallery
How to get values in real time with TextWatcher (Android)
Get information in an instance and calculate numbers Standard version
In Redmine you can get the project with Project.find (<identifier>)
Get error information using DefaultErrorAttributes and ErrorAttributeOptions in Spring Boot 2.3
Elasticsearch> Build with docker, get Twitter information and visualize with Kibana
If it doesn't change with the disable_with option in Safari
[Android] Change the app name and app icon for each Flavor
The difference between programming with Ruby classes and programming without it
Technical causes and countermeasures for the points I was addicted to with the first Android app & Kotlin
[For super beginners] The minimum knowledge you want to keep in mind with hashes and symbols
Generate a serial number with Hibernate (JPA) TableGenerator and store it in the Id of String.