Android – Create a New Playlist in Your Spotify Account utilizing Spotify Net API

Android – Create a New Playlist in Your Spotify Account utilizing Spotify Net API

Spotify is among the world’s hottest music streaming platforms, and it has an unlimited assortment of songs, albums, playlists, and podcasts. With the Spotify Net API, builders can create superb purposes that work together with the Spotify service. Utilizing the Net API’s endpoints, one can get detailed metadata about artists, albums, and tracks instantly from the Spotify Knowledge Catalogue. It additionally offers entry to the at the moment logged-in person’s information, such because the playlists and tracks saved within the Your Music Library of the person. 

On this article, we’ll create an Android app utilizing which we are able to create a brand new playlist within the logged-in person’s Spotify Account. Fundamentals of Java and Android App Growth data are stipulations for this text. We will even use the Volley library to make the networking calls to the Spotify Net API and the GSON library to parse the returned JSON information.

Step By Step Implementation

Step 1: Create a New Undertaking in Android Studio

Please seek advice from  How you can Create/Begin a New Undertaking in Android Studio to discover ways to create a brand new mission. Identify the mission “My Spotify App” (or any identify of your alternative) and choose Java because the programming language. A brand new mission will probably be created with a Principal Exercise and its XML file as follows:

 

Step 2: Create an app within the Spotify Dashboard

  • Head over to the Spotify Dashboard and log in utilizing your Spotify account. 
  • Click on on “Create an app.”
  • Write the app identify (My Spotify App), give it an outline, settle for the T&C, and click on on create button.

As soon as the app is created, the Dashboard will seem like this:

 

Step 3: Finalize mission settings within the dashboard

We are going to add a Redirect URI, our package deal identify, and the SHA-1 key of our Android Studio. The Redirect URI is used to redirect again to your utility from an online browser (on this case, the net web page for authentication). Due to this fact we create a novel URI for our app.

The package deal identify of an Android app is a novel identifier that distinguishes it from different apps on the gadget and the Google Play retailer. Equally, the SHA-1 secret is used to uniquely establish your Android Studio put in in your PC. Confer with this text to discover ways to get the SHA-1 key in Android Studio.

These particulars are wanted to limit our API key to solely work with our app and stop unauthorized use by others. Comply with the next steps so as to add these particulars:

  • Within the mission dashboard, click on on “Edit Settings.”
  • Beneath “Redirect URIs”, add your package deal identify as a redirect URI: <package-name>://callback, which on this case is:
com.instance.myspotifyapp://callback
  • Additionally, add your package deal identify beneath the “Android Packages” part, alongside along with your Android Studio’s distinctive SHA-1 key. 

Click on on Save, and you’ll be finished with the mission settings within the Spotify Dashboard. Your app will at the moment be in growth mode and can solely help a most of 25 customers. To make your app accessible to greater than 25 customers, you have to to Submit a quota extension request to the Spotify workforce.

Step 4: Add the mandatory dependencies and permissions

We might want to authenticate the person to make calls to the Spotify Net API. We are going to use the Spotify Android auth library, which is chargeable for authenticating the person and fetching the authorization code/entry token that may subsequently be used to play music or in requests to the API. 

We are going to use the Volley library to make HTTP calls to the API and the GSON library to parse the outcomes and use them in our app. We’ll examine the Maven Central repository to get the newest model of the libraries. The hyperlinks for every library are talked about under. Select the newest model and Gradle from the respective dropdowns, copy the dependency and, paste it into your module-level gradle file, then sync your mission. 

The Maven Central repository will look as follows:

 

Since Spotify Auth library model 2.0.0, we should additionally present the scheme and host of the redirect URI our app makes use of for authorizing in our module-level construct.gradle file. On this case, we have to paste the next in our defaultConfig scope inside android:

manifestPlaceholders = [redirectSchemeName: "com.example.myspotifyapp", redirectHostName: "callback"]

Sync your mission. The Gradle file will seem like this:

 

We should additionally add web permission in our app’s manifest file. Paste the next snippet in your AndroidManifest.xml file above the applying tag:

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

Step 5: Add the mandatory string values within the strings.xml file

Including the strings like keys and many others. that are utilized in many locations throughout the android app within the strings.xml file, is taken into account a greatest apply. We’ll retailer our Shopper ID, Redirect URI, and the shared preferences key within the string.xml file. You will get your Shopper ID and redirect URI from the Spotify Developer Dashboard. We’ll use “Spotify” as our key to entry shared preferences. The code for the strings.xml file will look as follows:

XML

<sources>

    <string identify="app_name">My Spotify App</string>

    <string identify="CLIENT_ID">YOUR_CLIENT_ID</string>

    <string identify="REDIRECT_URI">YOUR_REDIRECT_URI</string>

    <string identify="shared_pref_key">Spotify</string>

</sources>

Step 6: Add the code for authentication

Create a brand new Exercise, identify it LoginActivity in Android Studio, and choose it because the launcher exercise. We are going to write the code for authentication on this exercise and launch the MainActivity as soon as authentication is profitable. As soon as authentication is finished, we obtain a token, which is later used for authorization in making requests to the API. We’ll retailer the token in android’s persistent storage Shared Preferences for later use. We additionally have to outline the scope to entry the particular info we’ll be accessing from our person’s account. For instance, the user-read-email scope is used to learn the linked e-mail handle of the person. You may learn extra about scopes right here. The code for LoginActivity.java is as proven under:

Java

package deal com.instance.myspotifyapp;

  

import android.content material.Intent;

import android.content material.SharedPreferences;

import android.os.Bundle;

import android.util.Log;

import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.RequestQueue;

import com.android.volley.toolbox.Volley;

import com.spotify.sdk.android.auth.AuthorizationClient;

import com.spotify.sdk.android.auth.AuthorizationRequest;

import com.spotify.sdk.android.auth.AuthorizationResponse;

  

public class LoginActivity extends AppCompatActivity {

  

    

    non-public SharedPreferences.Editor editor;

    non-public SharedPreferences sharedPreferences;

  

    

    non-public RequestQueue requestQueue;

  

    

    

    non-public static last int REQUEST_CODE = 1234;

  

    

    non-public static last String SCOPES

        = "user-read-email,user-read-private,playlist-modify-private,playlist-modify-public";

  

    @Override

    protected void onCreate(Bundle savedInstanceState)

    {

        tremendous.onCreate(savedInstanceState);

        setContentView(R.format.activity_login);

  

        

        sharedPreferences = this.getSharedPreferences(

            getString(R.string.shared_pref_key),

            MODE_PRIVATE);

        requestQueue = Volley.newRequestQueue(this);

  

        

        AuthorizationRequest.Builder builder

            = new AuthorizationRequest.Builder(

                getString(R.string.CLIENT_ID),

                AuthorizationResponse.Sort.TOKEN,

                getString(R.string.REDIRECT_URI));

  

        builder.setScopes(new String[] { SCOPES });

        AuthorizationRequest request = builder.construct();

  

        

        AuthorizationClient.openLoginActivity(

            this, REQUEST_CODE, request);

    }

  

    

    

    protected void onActivityResult(int requestCode,

                                    int resultCode,

                                    Intent intent)

    {

        tremendous.onActivityResult(requestCode, resultCode,

                               intent);

  

        

        if (requestCode == REQUEST_CODE) {

            AuthorizationResponse response

                = AuthorizationClient.getResponse(

                    resultCode, intent);

  

            swap (response.getType()) {

            

            case TOKEN:

                

                editor = getSharedPreferences(

                             getString(

                                 R.string.shared_pref_key),

                             MODE_PRIVATE)

                             .edit();

  

                editor.putString("token",

                                 response.getAccessToken());

                editor.apply();

  

                

                Toast.makeText(this, "Auth profitable",Toast.LENGTH_SHORT)

                    .present();

  

                

                startActivity(new Intent(LoginActivity.this,

                               MainActivity.class));

  

                break;

  

            

            case ERROR:

                Log.d("LoginActivity", response.getError());

                break;

  

            default:

                Log.d("LoginActivity", response.toString());

            }

        }

    }

}

The XML file of LoginActivity, MainActivity, and its Java file would be the identical because the default for now. Now you can run the app and examine if auth is operating efficiently. You must see a toast saying “Auth profitable”, and the MainActivity ought to pop up proper after. 

Step 7: Create helper lessons to get logged-in person’s particulars

Now that the authentication is finished, we’ll attempt to get some person particulars and examine them within the MainActivity. We have to get the person particulars in order that we are able to pay money for the person’s Spotify ID, which will probably be wanted to create a playlist in that person’s account and way more stuff. You may learn extra concerning the endpoint for getting person particulars right here. We are going to first have to create a mannequin Person class to serialize the response from the endpoint. We are going to create variables for identify, e-mail, and person ID as a result of that’s the solely info we at the moment want.

Java

public class Person {

     

      

    public String display_name;

    public String e-mail;

    public String id;

  

    public String getDisplayName() {

        return display_name;

    }

  

    public String getEmail() {

        return e-mail;

    }

  

  

    public String getId() {

        return id;

    }

}

We are going to now create a UserInfo class to fetch the response from the API’s endpoint. We are going to make the decision to the API utilizing the Volley library and parse it into the Person class utilizing GSON.

Java

import android.content material.SharedPreferences;

import com.android.volley.AuthFailureError;

import com.android.volley.RequestQueue;

import com.android.volley.toolbox.JsonObjectRequest;

import com.google.gson.Gson;

import java.util.HashMap;

import java.util.Map;

  

public class UserInfo

{

    

    non-public SharedPreferences sharedPreferences;

    non-public RequestQueue queue;

    non-public Person person;

  

    

    

    

    public UserInfo(RequestQueue queue, SharedPreferences sharedPreferences) {

        this.queue = queue;

        this.sharedPreferences = sharedPreferences;

    }

  

    public Person getUser() {

        return person;

    }

  

    

    public void get(last VolleyCallBack callBack) {

          

        

        

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(URL,

                null, response -> 

        {

            

            Gson gson = new Gson(); 

  

            

            person = gson.fromJson(response.toString(), Person.class);

  

              

            callBack.onSuccess(); 

        }, error -> get(() -> {

  

        })) {

            

            @Override

            public Map<String, String> getHeaders() throws AuthFailureError {

                Map<String, String> headers = new HashMap<>();

                  

                

                String token = sharedPreferences.getString("token", "");

                String auth = "Bearer " + token;

                  

                

                headers.put("Authorization", auth);

                return headers;

            }

        };

        

          

        queue.add(jsonObjectRequest);

    }

}

Step 8: Show the main points within the Principal Exercise

Add a TextView on which we’ll show the person’s particulars. The XML code for the Principal Exercise class is given under:

XML

<?xml model="1.0" encoding="utf-8"?>

<androidx.constraintlayout.widget.ConstraintLayout 

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    instruments:context=".MainActivity">

  

    <TextView

        android:id="@+id/userDetails"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_margin="30dp"

        app:layout_constraintStart_toStartOf="father or mother"

        app:layout_constraintTop_toTopOf="father or mother" />

    

</androidx.constraintlayout.widget.ConstraintLayout>

Now we’ll write the code within the MainActivity.java file to show the person’s information. 

Java

import androidx.appcompat.app.AppCompatActivity;

import android.content material.SharedPreferences;

import android.os.Bundle;

import android.widget.TextView;

  

public class MainActivity extends AppCompatActivity {

    

    TextView userDetails;

    SharedPreferences sharedPreferences;

  

    non-public static last String TAG = "MainActivity";

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        tremendous.onCreate(savedInstanceState);

        setContentView(R.format.activity_main);

  

        

        userDetails = findViewById(R.id.userDetails);

          

        

        sharedPreferences = this.getSharedPreferences(getString(R.string.shared_pref_key),

                MODE_PRIVATE);

  

        

        String identify = sharedPreferences.getString("display_name", "Could not retrieve identify");

        String e-mail = sharedPreferences.getString("e-mail", "Could not get token");

  

        

        userDetails.setText("Identify: " +identify);

        userDetails.append("nEmail ID: " +e-mail);

    }

  

}

Now you can run the app. It is possible for you to to see your identify and e-mail on the Principal Exercise. A pattern screenshot is hooked up under: 

 

Step 9: Add code to create a brand new playlist in your Spotify account

We are going to now programmatically create a playlist in our Spotify account. The small print of the API for creating a brand new playlist may be discovered right here. First, we’ll create a button within the Principal Exercise for creating a brand new playlist. The XML code is as follows:

XML

<?xml model="1.0" encoding="utf-8"?>

<androidx.constraintlayout.widget.ConstraintLayout

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    instruments:context=".MainActivity">

  

    <Button

        android:id="@+id/createPlaylistBtn"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_margin="30dp"

        android:textual content="Create New Playlist"

        app:layout_constraintBottom_toBottomOf="father or mother"

        app:layout_constraintEnd_toEndOf="father or mother"

        app:layout_constraintStart_toStartOf="father or mother" />

  

    <TextView

        android:id="@+id/userDetails"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_margin="30dp"

        app:layout_constraintStart_toStartOf="father or mother"

        app:layout_constraintTop_toTopOf="father or mother" />

    

</androidx.constraintlayout.widget.ConstraintLayout>

Now we’ll make the request to the endpoint on the button click on in our Principal Exercise. The Java code is as follows:

Java

import androidx.appcompat.app.AppCompatActivity;

import android.content material.SharedPreferences;

import android.os.Bundle;

import android.widget.Button;

import android.widget.TextView;

import android.widget.Toast;

  

import com.android.volley.AuthFailureError;

import com.android.volley.Request;

import com.android.volley.RequestQueue;

import com.android.volley.toolbox.JsonObjectRequest;

import com.android.volley.toolbox.Volley;

  

import org.json.JSONException;

import org.json.JSONObject;

  

import java.util.HashMap;

import java.util.Map;

  

public class MainActivity extends AppCompatActivity {

    TextView userDetails;

    Button createPlaylistBtn;

    SharedPreferences sharedPreferences;

    non-public RequestQueue queue;

  

    non-public static last String TAG = "MainActivity";

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        tremendous.onCreate(savedInstanceState);

        setContentView(R.format.activity_main);

  

        

          

        userDetails = findViewById(R.id.userDetails);

        createPlaylistBtn = findViewById(R.id.createPlaylistBtn);

  

        

        sharedPreferences = this.getSharedPreferences(getString(R.string.shared_pref_key),

                MODE_PRIVATE);

  

        

        String identify = sharedPreferences.getString("display_name", "Could not retrieve identify");

        String e-mail = sharedPreferences.getString("e-mail", "Could not get token");

  

        

        userDetails.setText("Identify: " +identify);

        userDetails.append("nEmail ID: " +e-mail);

  

        

        queue = Volley.newRequestQueue(this);

  

        

        createPlaylistBtn.setOnClickListener(view -> {

            createTestPlaylist();

        });

    }

  

    

    non-public void createTestPlaylist()

    {

        

          

        

        JSONObject information = new JSONObject();

  

        strive{

            information.put("identify", "The Empty Canvas");

            information.put("description", "A playlist created by me utilizing Spotify's Net API :)");

        } catch (JSONException e) {

            throw new RuntimeException(e);

        }

  

        

                + sharedPreferences.getString("userId", "Could not get userid") + "/playlists";

  

        

        

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Technique.POST, endpoint,

                information, response -> {

            

            Toast.makeText(this, ""The Empty Canvas" playlist created", Toast.LENGTH_SHORT).present();

        },

                error -> {

                    

                    Toast.makeText(this, error.toString(), Toast.LENGTH_SHORT).present();

                }) {

            

            @Override

            public Map<String, String> getHeaders() throws AuthFailureError {

                Map<String, String> headers = new HashMap<>();

  

                

                String token = sharedPreferences.getString("token", "");

                String auth = "Bearer " + token;

  

                

                headers.put("Authorization", auth);

                headers.put("Content material-Sort", "utility/json");

                return headers;

            }

        };

  

        

          

        queue.add(jsonObjectRequest);

    }

}

Now you can run the app, and after clicking the button, you’ll discover a playlist has been created in your Spotify account. A pattern app and Spotify screenshots have been hooked up under.