Пример #1
0
 /**
  * Based on <a href="http://www.screaming-penguin.com/node/7749">Backing up your Android SQLite
  * database to the SD card</a>
  *
  * @param src
  * @param dst
  * @return true if success
  * @throws IOException
  */
 boolean copyFile(File src, File dst) throws IOException {
   long sizeIn = -1;
   long sizeCopied = 0;
   boolean ok = false;
   if (src != null && src.exists()) {
     sizeIn = src.length();
     if (!dst.createNewFile()) {
       MyLog.e(this, "New file was not created: '" + dst.getCanonicalPath() + "'");
     } else if (src.getCanonicalPath().compareTo(dst.getCanonicalPath()) == 0) {
       MyLog.d(this, "Cannot copy to itself: '" + src.getCanonicalPath() + "'");
     } else {
       FileInputStream fileInputStream = null;
       java.nio.channels.FileChannel inChannel = null;
       FileOutputStream fileOutputStream = null;
       java.nio.channels.FileChannel outChannel = null;
       try {
         fileInputStream = new FileInputStream(src);
         inChannel = fileInputStream.getChannel();
         fileOutputStream = new FileOutputStream(dst);
         outChannel = fileOutputStream.getChannel();
         sizeCopied = inChannel.transferTo(0, inChannel.size(), outChannel);
         ok = (sizeIn == sizeCopied);
       } finally {
         DbUtils.closeSilently(outChannel);
         DbUtils.closeSilently(fileOutputStream);
         DbUtils.closeSilently(inChannel);
         DbUtils.closeSilently(fileInputStream);
       }
     }
   }
   MyLog.d(this, "Copied " + sizeCopied + " bytes of " + sizeIn);
   return ok;
 }
Пример #2
0
    // This is in the UI thread, so we can mess with the UI
    @Override
    protected void onPostExecute(TaskResult result) {
      DialogFactory.dismissSafely(dlg);
      if (result == null) {
        MyLog.e(this, "Result is Null");
        return;
      }
      MyLog.d(
          this,
          this.getClass().getSimpleName()
              + " ended, "
              + (result.success ? (result.moved ? "moved" : "didn't move") : "failed"));

      if (!result.success) {
        result.messageBuilder.insert(0, mContext.getString(R.string.error) + ": ");
      }
      Toast.makeText(mContext, result.getMessage(), Toast.LENGTH_LONG).show();
      parentFragment.showUseExternalStorage();
    }
Пример #3
0
  /**
   * Get a cursor to the database
   *
   * @see android.content.ContentProvider#query(android.net.Uri, java.lang.String[],
   *     java.lang.String, java.lang.String[], java.lang.String)
   */
  @Override
  public Cursor query(
      Uri uri,
      String[] projection,
      String selectionIn,
      String[] selectionArgsIn,
      String sortOrder) {
    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
    boolean built = false;
    String selection = selectionIn;
    String[] selectionArgs = selectionArgsIn;
    String sql = "";

    ParsedUri uriParser = ParsedUri.fromUri(uri);
    switch (uriParser.matched()) {
      case TIMELINE:
        qb.setDistinct(true);
        qb.setTables(TimelineSql.tablesForTimeline(uri, projection));
        qb.setProjectionMap(ProjectionMap.MSG);
        break;

      case TIMELINE_ITEM:
        qb.setTables(TimelineSql.tablesForTimeline(uri, projection));
        qb.setProjectionMap(ProjectionMap.MSG);
        qb.appendWhere(
            ProjectionMap.MSG_TABLE_ALIAS + "." + BaseColumns._ID + "=" + uriParser.getMessageId());
        break;

      case TIMELINE_SEARCH:
        qb.setTables(TimelineSql.tablesForTimeline(uri, projection));
        qb.setProjectionMap(ProjectionMap.MSG);
        String searchQuery = uriParser.getSearchQuery();
        if (!TextUtils.isEmpty(searchQuery)) {
          if (!TextUtils.isEmpty(selection)) {
            selection = " AND (" + selection + ")";
          } else {
            selection = "";
          }
          // TODO: Search in MyDatabase.User.USERNAME also
          selection = "(" + User.AUTHOR_NAME + " LIKE ?  OR " + Msg.BODY + " LIKE ?)" + selection;

          selectionArgs = addBeforeArray(selectionArgs, "%" + searchQuery + "%");
          selectionArgs = addBeforeArray(selectionArgs, "%" + searchQuery + "%");
        }
        break;

      case MSG_COUNT:
        sql = "SELECT count(*) FROM " + Msg.TABLE_NAME + " AS " + ProjectionMap.MSG_TABLE_ALIAS;
        if (!TextUtils.isEmpty(selection)) {
          sql += " WHERE " + selection;
        }
        break;

      case MSG:
        qb.setTables(Msg.TABLE_NAME + " AS " + ProjectionMap.MSG_TABLE_ALIAS);
        qb.setProjectionMap(ProjectionMap.MSG);
        break;

      case USER:
      case USERLIST:
        qb.setTables(User.TABLE_NAME);
        qb.setProjectionMap(ProjectionMap.USER);
        break;

      case USER_ITEM:
        qb.setTables(User.TABLE_NAME);
        qb.setProjectionMap(ProjectionMap.USER);
        qb.appendWhere(BaseColumns._ID + "=" + uriParser.getUserId());
        break;

      default:
        throw new IllegalArgumentException(uriParser.toString());
    }

    // If no sort order is specified use the default
    String orderBy;
    if (TextUtils.isEmpty(sortOrder)) {
      switch (uriParser.matched()) {
        case TIMELINE:
        case TIMELINE_ITEM:
        case TIMELINE_SEARCH:
          orderBy = Msg.DEFAULT_SORT_ORDER;
          break;

        case MSG_COUNT:
          orderBy = "";
          break;

        case USER:
        case USERLIST:
        case USER_ITEM:
          orderBy = User.DEFAULT_SORT_ORDER;
          break;

        default:
          throw new IllegalArgumentException(uriParser.toString());
      }
    } else {
      orderBy = sortOrder;
    }

    Cursor c = null;
    if (MyContextHolder.get().isReady()) {
      // Get the database and run the query
      SQLiteDatabase db = MyContextHolder.get().getDatabase().getReadableDatabase();
      boolean logQuery = MyLog.isVerboseEnabled();
      try {
        if (sql.length() == 0) {
          sql = qb.buildQuery(projection, selection, null, null, orderBy, null);
          built = true;
        }
        // Here we substitute ?-s in selection with values from selectionArgs
        c = db.rawQuery(sql, selectionArgs);
        if (c == null) {
          MyLog.e(this, "Null cursor returned");
          logQuery = true;
        }
      } catch (Exception e) {
        logQuery = true;
        MyLog.e(this, "Database query failed", e);
      }

      if (logQuery) {
        String msg = "query, SQL=\"" + sql + "\"";
        if (selectionArgs != null && selectionArgs.length > 0) {
          msg += "; selectionArgs=" + Arrays.toString(selectionArgs);
        }
        MyLog.v(TAG, msg);
        if (built) {
          msg =
              "uri="
                  + uri
                  + "; projection="
                  + Arrays.toString(projection)
                  + "; selection="
                  + selection
                  + "; sortOrder="
                  + sortOrder
                  + "; qb.getTables="
                  + qb.getTables()
                  + "; orderBy="
                  + orderBy;
          MyLog.v(TAG, msg);
        }
      }
    }

    if (c != null) {
      c.setNotificationUri(getContext().getContentResolver(), uri);
    }
    return c;
  }
Пример #4
0
  /**
   * Insert a new record into the database.
   *
   * @see android.content.ContentProvider#insert(android.net.Uri, android.content.ContentValues)
   */
  @Override
  public Uri insert(Uri uri, ContentValues initialValues) {

    ContentValues values;
    MsgOfUserValues msgOfUserValues = new MsgOfUserValues(0);
    FollowingUserValues followingUserValues = null;
    long accountUserId = 0;

    long rowId;
    Uri newUri = null;
    try {
      Long now = System.currentTimeMillis();
      SQLiteDatabase db = MyContextHolder.get().getDatabase().getWritableDatabase();

      String table;

      if (initialValues != null) {
        values = new ContentValues(initialValues);
      } else {
        values = new ContentValues();
      }

      ParsedUri uriParser = ParsedUri.fromUri(uri);
      switch (uriParser.matched()) {
        case MSG_ITEM:
          accountUserId = uriParser.getAccountUserId();

          table = Msg.TABLE_NAME;
          /** Add default values for missed required fields */
          if (!values.containsKey(Msg.AUTHOR_ID) && values.containsKey(Msg.SENDER_ID)) {
            values.put(Msg.AUTHOR_ID, values.get(Msg.SENDER_ID).toString());
          }
          if (!values.containsKey(Msg.BODY)) {
            values.put(Msg.BODY, "");
          }
          if (!values.containsKey(Msg.VIA)) {
            values.put(Msg.VIA, "");
          }
          values.put(Msg.INS_DATE, now);

          msgOfUserValues = MsgOfUserValues.valueOf(accountUserId, values);
          break;

        case ORIGIN_ITEM:
          table = Origin.TABLE_NAME;
          break;

        case USER_ITEM:
          table = User.TABLE_NAME;
          values.put(User.INS_DATE, now);
          accountUserId = uriParser.getAccountUserId();
          followingUserValues = FollowingUserValues.valueOf(accountUserId, 0, values);
          break;

        default:
          throw new IllegalArgumentException(uriParser.toString());
      }

      rowId = db.insert(table, null, values);
      if (rowId == -1) {
        throw new SQLException("Failed to insert row into " + uri);
      } else if (User.TABLE_NAME.equals(table)) {
        optionallyLoadAvatar(rowId, values);
      }

      msgOfUserValues.setMsgId(rowId);
      msgOfUserValues.insert(db);

      if (followingUserValues != null) {
        followingUserValues.followingUserId = rowId;
        followingUserValues.update(db);
      }

      switch (uriParser.matched()) {
        case MSG_ITEM:
          newUri = MatchedUri.getMsgUri(accountUserId, rowId);
          break;
        case ORIGIN_ITEM:
          newUri = MatchedUri.getOriginUri(rowId);
          break;
        case USER_ITEM:
          newUri = MatchedUri.getUserUri(accountUserId, rowId);
          break;
        default:
          break;
      }
    } catch (Exception e) {
      MyLog.e(this, "Insert " + uri, e);
    }
    return newUri;
  }
Пример #5
0
  @Override
  public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
    final String method = "onCreateContextMenu";
    super.onCreateContextMenu(menu, v, menuInfo);
    if (getViewItem() == null) {
      return;
    }
    MyAccount myActor = getMyActor();
    if (!myActor.isValid() || !myActor.getOrigin().equals(getOrigin())) {
      setMyActor(getMyContext().persistentAccounts().getFirstSucceededForOrigin(getOrigin()));
    }

    int order = 0;
    try {
      new ContextMenuHeader(getActivity(), menu)
          .setTitle(getViewItem().mbUser.toUserTitle(false))
          .setSubtitle(getMyActor().getAccountName());
      String shortName = getViewItem().mbUser.getUserName();
      if (getViewItem().mbUser.isIdentified()) {
        UserListContextMenuItem.USER_MESSAGES.addTo(
            menu,
            order++,
            String.format(
                getActivity().getText(R.string.menu_item_user_messages).toString(), shortName));
        UserListContextMenuItem.FRIENDS.addTo(
            menu,
            order++,
            String.format(getActivity().getText(R.string.friends_of).toString(), shortName));
        UserListContextMenuItem.FOLLOWERS.addTo(
            menu,
            order++,
            String.format(getActivity().getText(R.string.followers_of).toString(), shortName));
        if (getViewItem().userIsFollowedBy(getMyActor())) {
          UserListContextMenuItem.STOP_FOLLOWING.addTo(
              menu,
              order++,
              String.format(
                  getActivity().getText(R.string.menu_item_stop_following_user).toString(),
                  shortName));
        } else if (getViewItem().getUserId() != getMyActor().getUserId()) {
          UserListContextMenuItem.FOLLOW.addTo(
              menu,
              order++,
              String.format(
                  getActivity().getText(R.string.menu_item_follow_user).toString(), shortName));
        }
        switch (getMyActor().numberOfAccountsOfThisOrigin()) {
          case 0:
          case 1:
            break;
          case 2:
            UserListContextMenuItem.ACT_AS_FIRST_OTHER_USER.addTo(
                menu,
                order++,
                String.format(
                    getActivity().getText(R.string.menu_item_act_as_user).toString(),
                    getMyActor()
                        .firstOtherAccountOfThisOrigin()
                        .getShortestUniqueAccountName(getMyContext())));
            break;
          default:
            UserListContextMenuItem.ACT_AS.addTo(menu, order++, R.string.menu_item_act_as);
            break;
        }
      }
      UserListContextMenuItem.GET_USER.addTo(menu, order++, R.string.get_user);
    } catch (Exception e) {
      MyLog.e(this, method, e);
    }
  }