如何存储推文列表(状态)?

时间:2017-06-13 09:43:34

标签: android sqlite mobile twitter twitter4j

我使用twitter4j提取推文列表。这是我的代码:

private ResponseList<Status> favouritesSavedLocally;

ConfigurationBuilder builder = new ConfigurationBuilder();

builder.setOAuthConsumerKey(ConstantValues.TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(ConstantValues.TWITTER_CONSUMER_SECRET);
builder.setOAuthAccessToken(SharedPref.getPrefKeyOauthToken());
builder.setOAuthAccessTokenSecret(SharedPref.getPrefKeyOauthSecret());
builder.setJSONStoreEnabled(true);
builder.setIncludeEntitiesEnabled(true);
builder.setIncludeMyRetweetEnabled(true);

AccessToken accessToken = new AccessToken(SharedPref.getPrefKeyOauthToken(), SharedPref.getPrefKeyOauthSecret());
Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);

try {
    favouritesSavedLocally = twitter.getFavorites();
} catch (TwitterException e) {
    e.printStackTrace();
}

现在这很好用......但问题是我需要在本地存储它。有谁知道存储状态(推文)对象的最佳方法是什么?我将它作为blob存储在SQLite中,但是在尝试从DB读取时出现此错误。这就是我尝试在本地存储它的方式:

private static final String COLUMN_ID = "ID";
private static final String COLUMN_FAVOURITE_TWEET = "FAVOURITE_TWEET";

...

@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
    sqLiteDatabase.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,FAVOURITE_TWEET BLOB) ");
}

...

public boolean addFavouriteStatus(byte[] status) {

    SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COLUMN_FAVOURITE_TWEET, status);

    long result = sqLiteDatabase.insert(TABLE_NAME, null, contentValues);

    if (result == -1) {
        return false;
    } else {
        sqLiteDatabase.close();
        return true;
    }
}

public Cursor getFavouriteStatuses() {

    SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
    Cursor result = sqLiteDatabase.rawQuery("select * from " + TABLE_NAME, null);

    return result;
}

尝试阅读getFavoritesStatuses()

时出现此错误
FATAL EXCEPTION: AsyncTask #2
Process: xxxxxxxx.clientfeed, PID: 11221
java.lang.RuntimeException: An error occurred while executing doInBackground()
    at android.os.AsyncTask$3.done(AsyncTask.java:309)
    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
    at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
    at java.util.concurrent.FutureTask.run(FutureTask.java:242)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
    at java.lang.Thread.run(Thread.java:818)
Caused by: android.database.sqlite.SQLiteException: unknown error (code 0): INTEGER data in nativeGetBlob 
#################################################################
Error Code : 0 (SQLITE_OK)
Caused By : unknown error (code 0): INTEGER data in nativeGetBlob 
#################################################################
    at android.database.CursorWindow.nativeGetBlob(Native Method)
    at android.database.CursorWindow.getBlob(CursorWindow.java:416)
    at android.database.AbstractWindowedCursor.getBlob(AbstractWindowedCursor.java:45)
    at xxxxxxxx.ui.TwitterFeedListFragment$GetFavouritesLocalTweets.doInBackground(TwitterFeedListFragment.java:132)
    at xxxxxxxx.ui.TwitterFeedListFragment$GetFavouritesLocalTweets.doInBackground(TwitterFeedListFragment.java:120)
    at android.os.AsyncTask$2.call(AsyncTask.java:295)
    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
    ... 4 more

注意:这是推文对象的样子

{"id_str":"873961105277767680","coordinates":null,"in_reply_to_user_id_str":null,"source":"<a href=\"http:\/\/instagram.com\" rel=\"nofollow\">Instagram<\/a>","geo":null,"possibly_sensitive_appealable":false,"in_reply_to_user_id":null,"retweet_count":0,"user":{"default_profile_image":false,"screen_name":"klaussdeejay","profile_link_color":"0084B4","profile_background_color":"C0DEED","is_translator":false,"url":null,"profile_background_image_url":"http:\/\/pbs.twimg.com\/profile_background_images\/868651398\/9e71de37e9836eb30c0e171028a134d2.jpeg","statuses_count":704,"profile_text_color":"333333","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/3601781438\/76e5351fe2de382e89486e86f6a3bc18_normal.jpeg","following":true,"profile_sidebar_border_color":"C0DEED","verified":false,"id":1396650608,"lang":"en","entities":{"description":{"urls":[]}},"profile_background_tile":false,"listed_count":3,"id_str":"1396650608","profile_sidebar_fill_color":"DDEEF6","profile_background_image_url_https":"https:\/\/pbs.twimg.com\/profile_background_images\/868651398\/9e71de37e9836eb30c0e171028a134d2.jpeg","protected":false,"translator_type":"none","utc_offset":null,"is_translation_enabled":false,"profile_use_background_image":true,"notifications":false,"geo_enabled":false,"friends_count":366,"default_profile":false,"followers_count":54,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/3601781438\/76e5351fe2de382e89486e86f6a3bc18_normal.jpeg","follow_request_sent":false,"contributors_enabled":false,"has_extended_profile":false,"description":"","time_zone":null,"location":"London, UK","name":"Claudiu Farcas ","created_at":"Thu May 02 08:46:07 +0000 2013","favourites_count":47},"favorited":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"truncated":false,"favorite_count":0,"id":873961105277767680,"is_quote_status":false,"contributors":null,"lang":"en","possibly_sensitive":false,"entities":{"urls":[{"indices":[20,43],"display_url":"instagram.com\/p\/BVNVW5VlNo-\/","expanded_url":"https:\/\/www.instagram.com\/p\/BVNVW5VlNo-\/","url":"https:\/\/t.co\/ngy7BtnvhP"}],"hashtags":[],"user_mentions":[],"symbols":[]},"text":"Just posted a photo https:\/\/t.co\/ngy7BtnvhP","created_at":"Sun Jun 11 17:52:19 +0000 2017","place":null,"in_reply_to_screen_name":null,"retweeted":false}

提前谢谢!

1 个答案:

答案 0 :(得分:1)

在twitter4j中,Status实际上是Interface,但由于许多twitter4j接口都基于JSON,因此您可以将Status转换为JSON字符串,反之亦然。您可以将Status保存为字符串。

要执行此操作,请先在Configuration中将JSON Store设置为启用并设置:

ConfigurationBuilder cb = ConfigurationBuilder();
...
cb.setJSONStoreEnabled(true);
Configuration configuration = cb.build();
// Setup configuration

你可以开始转换它们了:

String json = TwitterObjectFactory.getRawJSON(status); // Status -> JSON String

Status status = TwitterObjectFactory.createStatus(json); // JSON String -> Status

现在您可以将Status保存为数据库中的String

要使用Configuration设置ConfigurationBuilder,请在此处阅读:

另请查看一些twitter4j文档: