2015-03-08 146 views
1

我試圖從當前登錄到應用程序的用戶獲取私人播放列表。如何從當前登錄的用戶獲取user_id?

SpotifyApi api = new SpotifyApi(); 
api.setAccessToken(response.getAccessToken()); 
SpotifyService spotify = api.getService(); 
Playlist playlist = spotify.getPlaylist(user_id, playlist_id); 

如何獲取user_id?

編輯

我試過這段代碼:

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 

    if (requestCode == REQUEST_CODE) { 
     AuthenticationResponse response = AuthenticationClient.getResponse(resultCode, data); 
     if (response.getType() == AuthenticationResponse.Type.TOKEN) { 
      SpotifyApi api = new SpotifyApi(); 
      api.setAccessToken(response.getAccessToken()); 
      SpotifyService spotify = api.getService(); 
      User user = spotify.getMe(); 
      Log.d("TAG", user.id); 

     } 
    } 
    super.onActivityResult(requestCode, resultCode, data); 
} 

這給了我一個錯誤:

java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1337, result=-1, data=Intent { (has extras) }} to activity {de.test.spotifytest/de.test.spotifytest.activities.MainActivity}: retrofit.RetrofitError 

回答

1

我不得不在AsyncTask中獲取用戶對象,因爲無法在主線程上執行網絡操作。這同樣適用於獲取用戶播放列表。

private class MyTask extends AsyncTask<String, Integer, Pager<Playlist>>{ 

    @Override 
    protected Pager<Playlist> doInBackground(String... params) { 
     Pager<Playlist> playlists = spotify.getPlaylists(spotify.getMe().id); 
     return playlists; 
    } 

    @Override 
    protected void onPostExecute(Pager<Playlist> playlistPager) { 
     //do something with the playlists 
    } 
} 

在主線程:

new MyTask().execute(""); 
+0

感謝您分享您的解決方案。順便說一句,你也可以使用AsyncTask.execute(new Runnable(){ @Override public void run(){ } }); – david72 2017-12-28 19:46:06

0

我不知道你的庫」回覆使用,但它看起來像spotify-web-api-android包裝。

如果是這樣,您可以通過使用SpotifyService的getMe()方法調用Get Current User's Profile端點來檢索當前用戶的用戶ID。 getMe()將返回一個User object,該成員名爲id

更新:看起來問題可能與包裝無關,而是一般的Android問題。這Stack Overflow question似乎有關。

在輸入if塊之前添加檢查以查看resultCode是否不是RESULT_CANCELED可能會解決此問題。

protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    if (resultCode != RESULT_CANCELED && resultCode == REQUEST_CODE) { 
    AuthenticationResponse response = AuthenticationClient.getResponse(resultCode, data); 
    ... 
    } 
} 

其他使用額外的resultCode == RESULT_OK,這對我的理解也是有效的。

+0

是的,我使用Spotify的的web-API的Android包裝。當我嘗試顯示用戶標識時,它給我一個runtimeException。我編輯了我的問題並添加了更多代碼。我錯了什麼? – Antict 2015-03-10 16:48:31

+0

我已經更新了我的回覆。 – 2015-03-10 17:06:50

相關問題