Cocos2d-xとTwitter Kitを使ってOAuth認証&ユーザタイムライン取得-Android編その4

Cocos2d-xとTwitter Kitを使ってOAuth認証&ユーザタイムライン取得-Android編その3の続き
ではいよいよ最終目標のユーザタイムラインの取得をします。
今回もまたAppActivityでメソッドを作ってNativeLauncherにjniを追加します。

AppActivity.java

static String userTimeline_text[];
public static String[] showUserTimeline() throws InterruptedException{
    final CountDownLatch cdl = new CountDownLatch(1);
    final int count = 5;
    StatusesService statusesService = Twitter.getApiClient().getStatusesService();
    statusesService.userTimeline(null,null,count, null, null, true, false, true, true,
        new Callback<List<Tweet>>() {
            @Override
            public void success(Result<List<Tweet>> listResult) {
                String text[] = new String[count];
                int tweetNum = 0;
                for (Tweet tweet : listResult.data) {
                    text[tweetNum] = tweet.text;
                    tweetNum++;
                }
                userTimeline_text = text;                 
                cdl.countDown();
            }
            @Override
            public void failure(TwitterException e) {
                System.out.println("failure");
            }
        });
    cdl.await();
    return userTimeline_text;
}

前回とだいたい同じですが、今回は配列を返します。
パラメータやデータ構造はGET statuses/user_timelineを見てください。
countのところが取得するツイート数です。
リツイートを含めない設定にしていても、1ツイートとしてカウントされるので注意してください。

NativeLauncher

NativeLauncher.h
#include <string.h>
#include "cocos2d.h"

using namespace std;
using namespace cocos2d;

class NativeLauncher{
public:
    static void loginTwitter();
    static std::string showTweet();
    static std::vector<std::string> showUserTimeline();
};

NativeLauncher.cpp
std::vector<std::string> NativeLauncher::showUserTimeline(){
    std::vector<std::string> userTimeline_text;
    JniMethodInfo JMI;
    if (JniHelper::getStaticMethodInfo(JMI, CLASS_NAME, "showUserTimeline", "()[Ljava/lang/String;")) {
        jobjectArray joa = (jobjectArray)JMI.env->CallStaticObjectMethod(JMI.classID, JMI.methodID);
        jsize len = JMI.env->GetArrayLength(joa);
        for (int i=0; i < len; i++){
            jstring jStr = (jstring)JMI.env->GetObjectArrayElement(joa, i);
            const char *str = JMI.env->GetStringUTFChars(jStr,NULL);
            userTimeline_text.push_back(str);
            JMI.env->ReleaseStringUTFChars(jStr, str);
        }
        JMI.env->DeleteLocalRef(JMI.classID);
    }
    return userTimeline_text;
}

戻り値の指定が"()[Ljava/lang/String;"と"["が入っているのに注意してください。
一旦jobjectArrayに格納した配列をstd::vector<std::string> userTimeline_textにループで入れています。
jinについて詳しくはここをcocos2d-xでjniを使ってみる


NativeLauncher::showUserTimeline();とcocosから呼び出せばユーザタイムラインが取得できるはずです。
他のREST_APIの機能も同じような感じで使えると思います。

続き、iOS::Cocos2d-xとTwitter Kitを使ってOAuth認証&ユーザタイムライン取得-iOS編その1

コメント

このブログの人気の投稿

2次元配列のコピー::JavaScript

iframeの利点と欠点

chromyを実行するとエラー:"Failed to launch a browser"が出る