@Override
 public synchronized List<ParcelableStatus> loadInBackground() {
   final List<ParcelableStatus> data = getData();
   final long account_id = getAccountId();
   ResponseList<Status> statuses = null;
   try {
     final Paging paging = new Paging();
     final SharedPreferences prefs =
         getContext().getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
     final int load_item_limit =
         prefs.getInt(PREFERENCE_KEY_LOAD_ITEM_LIMIT, PREFERENCE_DEFAULT_LOAD_ITEM_LIMIT);
     paging.setCount(load_item_limit);
     if (mMaxId != -1) {
       paging.setMaxId(mMaxId);
     }
     statuses = getStatuses(paging);
   } catch (final TwitterException e) {
     e.printStackTrace();
   }
   if (statuses != null) {
     for (final Status status : statuses) {
       data.add(new ParcelableStatus(status, account_id, false));
     }
   }
   Collections.sort(data);
   return data;
 }
  private ArrayAdapter<String> getTimeline() {
    SharedPreferences sp = getSharedPreferences("token", MODE_PRIVATE);
    String token = sp.getString("token", "");
    String tokenSecret = sp.getString("token_seacret", "");

    // twitterオブジェクトの作成
    Twitter tw = new TwitterFactory().getInstance();

    // AccessTokenオブジェクトの作成
    AccessToken at = new AccessToken(token, tokenSecret);

    // Consumer keyとConsumer key seacretの設定
    tw.setOAuthConsumer("iy2FEHXmSXNReJ6nYQ8FRg", "KYro4jM8BHlLSMsSdTylnTcm3pYaTCiG2UZrYK1yI4");

    // AccessTokenオブジェクトを設定
    tw.setOAuthAccessToken(at);

    try {
      // TLの取得
      ResponseList<Status> homeTl = tw.getHomeTimeline();

      ArrayAdapter<String> adapter =
          new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1);

      for (Status status : homeTl) {
        // つぶやきのユーザーIDの取得
        String userName = status.getUser().getScreenName();
        // つぶやきの取得
        String tweet = status.getText();
        adapter.add("ユーザーID:" + userName + "\r\n" + "tweet:" + tweet);
      }
      Status s = homeTl.get(homeTl.size());
      Paging p = new Paging();
      p.setMaxId(s.getId());

      homeTl = null;
      homeTl = tw.getHomeTimeline(p);

      for (Status status : homeTl) {
        // つぶやきのユーザーIDの取得
        String userName = status.getUser().getScreenName();
        // つぶやきの取得
        String tweet = status.getText();
        adapter.add("ユーザーID:" + userName + "\r\n" + "tweet:" + tweet);
      }

      return adapter;
    } catch (TwitterException e) {
      e.printStackTrace();
      if (e.isCausedByNetworkIssue()) {
        Toast.makeText(getApplicationContext(), "ネットワークに接続して下さい", Toast.LENGTH_LONG);
      } else {
        Toast.makeText(getApplicationContext(), "エラーが発生しました。", Toast.LENGTH_LONG);
      }
    }
    return null;
  }
 @Override
 public List<Status> getStatuses(final Twitter twitter, final Paging paging)
     throws TwitterException {
   if (twitter == null) return null;
   final Query query = new Query(processQuery(mQuery));
   query.setRpp(paging.getCount());
   if (paging.getMaxId() > 0) {
     query.setMaxId(paging.getMaxId());
   }
   return Arrays.asList(twitter.search(query).getStatuses());
 }
  private MetaList<Tweet> getSavedSearchFromTwitter(int searchId, boolean fromDbOnly) {
    MetaList<Tweet> messages;

    Paging paging = new Paging();
    paging.setCount(20);

    messages = th.getSavedSearchesTweets(searchId, fromDbOnly, paging);

    tweets = messages.getList();

    return messages;
  }
  private MetaList<DirectMessage> getDirectsFromTwitter(boolean fromDbOnly) {
    MetaList<DirectMessage> messages;

    long last = tdb.getLastRead(account.getId(), -2);
    Paging paging = new Paging();
    if (last > -1) paging.setSinceId(last);

    messages = th.getDirectMessages(fromDbOnly, paging);
    directs = messages.getList();

    return messages;
  }
    @Override
    protected ResponseList<DirectMessage> doInBackground(Void... params) {
      try {
        Twitter twitter = TwitterManager.getTwitter();

        // 受信したDM
        Paging directMessagesPaging = new Paging();
        if (mDirectMessagesMaxId > 0 && !mReloading) {
          directMessagesPaging.setMaxId(mDirectMessagesMaxId - 1);
          directMessagesPaging.setCount(BasicSettings.getPageCount() / 2);
        } else {
          directMessagesPaging.setCount(10);
        }
        ResponseList<DirectMessage> directMessages =
            twitter.getDirectMessages(directMessagesPaging);
        for (DirectMessage directMessage : directMessages) {
          if (mDirectMessagesMaxId <= 0L || mDirectMessagesMaxId > directMessage.getId()) {
            mDirectMessagesMaxId = directMessage.getId();
          }
        }

        // 送信したDM
        Paging sentDirectMessagesPaging = new Paging();
        if (mSentDirectMessagesMaxId > 0 && !mReloading) {
          sentDirectMessagesPaging.setMaxId(mSentDirectMessagesMaxId - 1);
          sentDirectMessagesPaging.setCount(BasicSettings.getPageCount() / 2);
        } else {
          sentDirectMessagesPaging.setCount(10);
        }
        ResponseList<DirectMessage> sentDirectMessages =
            twitter.getSentDirectMessages(sentDirectMessagesPaging);
        for (DirectMessage directMessage : sentDirectMessages) {
          if (mSentDirectMessagesMaxId <= 0L || mSentDirectMessagesMaxId > directMessage.getId()) {
            mSentDirectMessagesMaxId = directMessage.getId();
          }
        }

        directMessages.addAll(sentDirectMessages);

        // 日付でソート
        Collections.sort(
            directMessages,
            new Comparator<DirectMessage>() {

              @Override
              public int compare(DirectMessage arg0, DirectMessage arg1) {
                return arg1.getCreatedAt().compareTo(arg0.getCreatedAt());
              }
            });
        return directMessages;
      } catch (OutOfMemoryError e) {
        return null;
      } catch (Exception e) {
        e.printStackTrace();
        return null;
      }
    }
    @Override
    protected List<HaikuStatus> doInBackground(Void... params) {

      twitter4j.Status lastStatus = mAdapter.getItem(mAdapter.getCount() - 1).getStatus();

      Paging paging = new Paging();
      paging.setMaxId(lastStatus.getId() - 1);
      ResponseList<twitter4j.Status> timeline;

      try {
        timeline = mTwitter.getUserTimeline(userScreenName, paging);
      } catch (TwitterException e) {
        Log.e(TAG, e.toString());
        isThereTweetException = true;
        return null;
      }

      MorphologicalAnalysisByGooAPI analyzer =
          new MorphologicalAnalysisByGooAPI(getString(R.string.goo_id));
      List<HaikuStatus> haikuStatusList = new ArrayList<>();

      if (canCreateHaiku) {
        for (twitter4j.Status status : timeline) {
          try {
            List<Word> list =
                analyzer.analyze(
                    status.getRetweetedStatus() != null
                        ? status.getText().replaceFirst("RT", "")
                        : status.getText());
            String haiku = new HaikuGeneratorByGooAPI(list).generateHaikuStrictly();
            haikuStatusList.add(new HaikuStatus(haiku, status));
          } catch (IOException e) {
            Log.d(TAG, e.toString());
          }
        }
      } else {
        for (twitter4j.Status status : timeline) {
          String haiku = "";
          haikuStatusList.add(new HaikuStatus(haiku, status));
        }
      }

      return haikuStatusList;
    }
 @Override
 public List<ParcelableStatus> loadInBackground() {
   final List<ParcelableStatus> data = getData();
   final long account_id = getAccountId();
   ResponseList<Status> statuses = null;
   try {
     final Paging paging = new Paging();
     final SharedPreferences prefs =
         getContext().getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
     final int load_item_limit =
         prefs.getInt(PREFERENCE_KEY_LOAD_ITEM_LIMIT, PREFERENCE_DEFAULT_LOAD_ITEM_LIMIT);
     paging.setCount(load_item_limit);
     if (mMaxId != -1) {
       paging.setMaxId(mMaxId);
     }
     statuses = getStatuses(paging);
   } catch (final TwitterException e) {
     e.printStackTrace();
   }
   if (statuses != null) {
     Collections.sort(statuses, TWITTER4J_STATUS_ID_COMPARATOR);
     int deleted_count = 0;
     final int size = statuses.size();
     for (int i = 0; i < size; i++) {
       final Status status = statuses.get(i);
       if (deleteStatus(status.getId())) {
         deleted_count++;
       }
       data.add(
           new ParcelableStatus(
               status,
               account_id,
               i == statuses.size() - 1 ? deleted_count > 1 : false,
               isForceSSLConnection()));
     }
   }
   Collections.sort(data, ParcelableStatus.STATUS_ID_COMPARATOR);
   return data;
 }
  @Override
  public void onHandleIntent(Intent intent) {
    if (!MainActivity.canSwitch
        || CatchupPull.isRunning
        || WidgetRefreshService.isRunning
        || TimelineRefreshService.isRunning) {
      return;
    }
    if (MainActivity.canSwitch) {
      TimelineRefreshService.isRunning = true;
      sharedPrefs =
          getSharedPreferences(
              "com.klinker.android.twitter_world_preferences",
              Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);

      Context context = getApplicationContext();
      int numberNew = 0;

      AppSettings settings = AppSettings.getInstance(context);

      // if they have mobile data on and don't want to sync over mobile data
      if (intent.getBooleanExtra("on_start_refresh", false)) {

      } else if (Utils.getConnectionStatus(context) && !settings.syncMobile) {
        return;
      }

      Twitter twitter = Utils.getTwitter(context, settings);

      HomeDataSource dataSource = HomeDataSource.getInstance(context);

      int currentAccount = sharedPrefs.getInt("current_account", 1);

      List<twitter4j.Status> statuses = new ArrayList<twitter4j.Status>();

      boolean foundStatus = false;

      Paging paging = new Paging(1, 200);

      long[] lastId = null;
      long id;
      try {
        lastId = dataSource.getLastIds(currentAccount);
        id = lastId[1];
      } catch (Exception e) {
        try {
          Thread.sleep(5000);
        } catch (InterruptedException i) {

        }
        TimelineRefreshService.isRunning = false;
        return;
      }

      if (id == 0) {
        id = 1;
      }

      try {
        paging.setSinceId(id);
      } catch (Exception e) {
        paging.setSinceId(1l);
      }

      for (int i = 0; i < settings.maxTweetsRefresh; i++) {
        try {
          if (!foundStatus) {
            paging.setPage(i + 1);
            List<Status> list = twitter.getHomeTimeline(paging);
            statuses.addAll(list);

            if (statuses.size() <= 1 || statuses.get(statuses.size() - 1).getId() == lastId[0]) {
              Log.v("talon_inserting", "found status");
              foundStatus = true;
            } else {
              Log.v("talon_inserting", "haven't found status");
              foundStatus = false;
            }
          }
        } catch (Exception e) {
          // the page doesn't exist
          foundStatus = true;
        } catch (OutOfMemoryError o) {
          // don't know why...
        }
      }

      Log.v("talon_pull", "got statuses, new = " + statuses.size());

      // hash set to check for duplicates I guess
      HashSet hs = new HashSet();
      hs.addAll(statuses);
      statuses.clear();
      statuses.addAll(hs);

      Log.v("talon_inserting", "tweets after hashset: " + statuses.size());

      lastId = dataSource.getLastIds(currentAccount);

      Long currentTime = Calendar.getInstance().getTimeInMillis();
      if (currentTime - sharedPrefs.getLong("last_timeline_insert", 0l) < 10000) {
        Log.v("talon_refresh", "don't insert the tweets on refresh");
        sendBroadcast(
            new Intent("com.klinker.android.twitter.TIMELINE_REFRESHED").putExtra("number_new", 0));

        TimelineRefreshService.isRunning = false;
        context.getContentResolver().notifyChange(HomeContentProvider.CONTENT_URI, null);
        return;
      } else {
        sharedPrefs.edit().putLong("last_timeline_insert", currentTime).commit();
      }

      int inserted =
          HomeDataSource.getInstance(context).insertTweets(statuses, currentAccount, lastId);

      if (inserted > 0 && statuses.size() > 0) {
        sharedPrefs
            .edit()
            .putLong("account_" + currentAccount + "_lastid", statuses.get(0).getId())
            .commit();
      }

      if (!intent.getBooleanExtra("on_start_refresh", false)) {
        sharedPrefs.edit().putBoolean("refresh_me", true).commit();

        if (settings.notifications
            && (settings.timelineNot || settings.favoriteUserNotifications)
            && inserted > 0
            && !intent.getBooleanExtra("from_launcher", false)) {
          NotificationUtils.refreshNotification(context, !settings.timelineNot);
        }

        if (settings.preCacheImages) {
          startService(new Intent(this, PreCacheService.class));
        }
      } else {
        Log.v("talon_refresh", "sending broadcast to fragment");
        sendBroadcast(
            new Intent("com.klinker.android.twitter.TIMELINE_REFRESHED")
                .putExtra("number_new", inserted));
      }

      sendBroadcast(new Intent("com.klinker.android.talon.UPDATE_WIDGET"));
      getContentResolver().notifyChange(HomeContentProvider.CONTENT_URI, null);

      TimelineRefreshService.isRunning = false;
    }
  }
  /**
   * Retrieve a list of statuses. Depending on listId, this is taken from different sources:
   *
   * <ul>
   *   <li>0 : home timeline
   *   <li>-1 : mentions
   *   <li>>0 : User list
   * </ul>
   *
   * This method may trigger a network call if fromDbOnly is false. The filter if not null is a
   * regular expression, that if matches filters the tweet.
   *
   * @param fromDbOnly If true only statuses already in the DB are returned
   * @param listId Id of the list / timeline to fetch (see above)
   * @param updateStatusList Should the currently displayed list be updated?
   * @return List of status items along with some counts
   */
  private MetaList<Status> getTimlinesFromTwitter(
      boolean fromDbOnly, int listId, boolean updateStatusList) {
    Paging paging = new Paging();

    MetaList<Status> myStatuses;

    long last = tdb.getLastRead(account.getId(), listId);
    if (last > 0) // && !Debug.isDebuggerConnected())
    paging.sinceId(last).setCount(200);
    else paging.setCount(50); // 50 Tweets if we don't have the timeline yet

    switch (listId) {
      case 0:
        // Home time line
        myStatuses = th.getTimeline(paging, listId, fromDbOnly);

        break;
      case -1:
        myStatuses = th.getTimeline(paging, listId, fromDbOnly);
        break;
      case -2:
        // see below at getDirectsFromTwitter
        myStatuses = new MetaList<Status>();
        break;
      case -3:
        myStatuses = th.getTimeline(paging, listId, fromDbOnly);
        break;
      case -4:
        myStatuses = th.getTimeline(paging, listId, fromDbOnly);
        break;
      default:
        myStatuses = th.getUserList(paging, listId, fromDbOnly, unreadCount);
        if (unreadCount > -1) {
          List<Status> list = myStatuses.getList();
          if (list.size() <= unreadCount) unreadCount = list.size() - 1;
          if (unreadCount > -1) last = list.get(unreadCount).getId();
        }

        break;
    }

    long newLast = -1;
    // Update the 'since' id in the database
    if (myStatuses.getList().size() > 0) {
      newLast =
          myStatuses
              .getList()
              .get(0)
              .getId(); // assumption is that twitter sends the newest (=highest id) first
      tdb.updateOrInsertLastRead(account.getId(), listId, newLast);
    }

    // Sync with TweetMarker
    long newLast2 = -1;
    if (listId >= 0 && !account.isStatusNet() && !fromDbOnly) {
      if (listId == 0)
        newLast2 = TweetMarkerSync.syncFromTweetMarker("timeline", account.getName());
      else newLast2 = TweetMarkerSync.syncFromTweetMarker("lists." + listId, account.getName());

      if (newLast2 > newLast) {
        tdb.updateOrInsertLastRead(account.getId(), listId, newLast2);
      } else {
        if (listId == 0)
          TweetMarkerSync.syncToTweetMarker("timeline", newLast, account.getName(), th.getOAuth());
        else
          TweetMarkerSync.syncToTweetMarker(
              "lists." + listId, newLast, account.getName(), th.getOAuth());
      }
    }

    MetaList<Status> metaList;
    if (updateStatusList) {
      statuses = new ArrayList<Status>();
      List<Status> data = new ArrayList<Status>(myStatuses.getList().size());
      if (filterPattern == null) {
        setupFilter(); // TODO report errors?
      }
      for (Status status : myStatuses.getList()) {
        boolean shouldFilter = matchesFilter(status);
        if (shouldFilter) {
          Log.i(
              "TweetListActivity::filter, filtered ",
              status.getUser().getScreenName() + " - " + status.getText());
        } else {
          data.add(status);
          statuses.add(status);
        }
      }
      metaList = new MetaList<Status>(data, myStatuses.getNumOriginal(), myStatuses.getNumAdded());
    } else {
      metaList = new MetaList<Status>(new ArrayList<Status>(), 0, 0);
    }

    if (newLast2 > last) {
      metaList.oldLast = newLast2;
      // the read status from remote is newer than the last read locally, so lets mark those in
      // between as read
      for (Status s : statuses) {
        long id = s.getId();
        if (id > last) {
          th.markStatusAsOld(id);
        }
      }
    } else {
      metaList.oldLast = last;
    }

    for (Status status : metaList.getList()) {
      AccountHolder accountHolder = AccountHolder.getInstance();
      accountHolder.addUserName(status.getUser().getScreenName());
      if (status.getHashtagEntities() != null) {
        for (HashtagEntity hte : status.getHashtagEntities()) {
          accountHolder.addHashTag(hte.getText());
        }
      }
    }

    return metaList;
  }