简体   繁体   English

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

[英]How can I store loacally a list of tweets (status)?

I'm pulling a list of tweets using twitter4j. 我正在使用twitter4j提取一条推文列表。 Here is my code: 这是我的代码:

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();
}

Now this works fine... but the problem is I need to store this locally. 现在可以正常工作了……但是问题是我需要将其存储在本地。 Does anyone know what is the best way to store a Status (tweet) object? 有谁知道存储状态(tweet)对象的最佳方法是什么? I've trie to store it in SQLite as a blob but I get this error when attempting to read from DB. 我试图将其作为Blob存储在SQLite中,但是在尝试从数据库读取时出现此错误。 This is how I tried to store it locally: 这是我尝试在本地存储的方式:

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;
}

I get this error when attempting to read the getFavoritesStatuses() 尝试读取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

NOTE: this how a tweet object looks like 注意:这是一个tweet对象的样子

{"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}

Thank you in advance! 先感谢您!

In twitter4j, Status is actually an Interface , but since lots of twitter4j interfaces are based on JSON you can convert Status to JSON string and vice versa. 在twitter4j中, Status实际上是一个Interface ,但是由于许多twitter4j接口都是基于JSON的,因此您可以将Status转换为JSON字符串,反之亦然。 You can just save your Status as String. 您可以将Status另存为字符串。

In order to do this, first set JSON Store to enabled in your Configuration and set it: 为此,请先在Configuration中将JSON存储设置为enabled,然后进行设置:

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

And you can start converting them: 您可以开始转换它们:

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

or 要么

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

so now you can save Status as String in your database. 因此现在您可以在数据库中将Status另存为String

For setting Configuration with ConfigurationBuilder , read here: 要使用ConfigurationBuilder设置Configuration ,请阅读此处:

Also check out some twitter4j documentations: 另请查看一些twitter4j文档:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在数据库中存储字符串列表? - How can I store list of Strings in DataBase? 我如何使用json解析最后3条推文而不是最后1条 - How can i parse the last 3 tweets instead of the last 1 with json Google Play 商店显示应用内购买状态(我如何删除它) - Google Play store shows in-app-purchase status (how can i remove that) 如何列出要存储在服务器上的歌曲详细信息 - How can I list songs details to be store on server 如何解决此存储卡状态:商户无权在PayU付款网关中使用存储卡api? - How can I fix this stored card status: merchant is not authorized to use store card api in PayU payment gateway? 我如何在列表视图中存储多个字段 - How Can i Store more Than One Fields in List View 如何在Android的列表视图中显示推文? - how to show tweets in list view in android? Android:如何缓存使用Fabric SDK离线模式获得的推文? - Android : How can I cache the tweets that I’ve got using the Fabric SDK for offline mode? 如何在 map 中存储有状态和无状态小部件列表以及如何访问特定的键值? - How can I store stateful and stateless widget list both in the map and how can access spesific key value? Android应用程序如何在列表视图中缓存/存储推文? - How does Twitter App in Android cache/store tweets in the listview?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM