Example usage for android.database Cursor moveToPosition

List of usage examples for android.database Cursor moveToPosition

Introduction

In this page you can find the example usage for android.database Cursor moveToPosition.

Prototype

boolean moveToPosition(int position);

Source Link

Document

Move the cursor to an absolute position.

Usage

From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java

public String CopyFile(String sTmpSrcFileName, String sTmpDstFileName) {
    String sRet = sErrorPrefix + "Could not copy " + sTmpSrcFileName + " to " + sTmpDstFileName;
    ContentValues cv = null;//from w w w .ja v a2  s .co  m
    File destFile = null;
    Uri ffxSrcFiles = null;
    Uri ffxDstFiles = null;
    FileInputStream srcFile = null;
    FileOutputStream dstFile = null;
    byte[] buffer = new byte[4096];
    int nRead = 0;
    long lTotalRead = 0;
    long lTotalWritten = 0;
    ContentResolver crIn = null;
    ContentResolver crOut = null;

    if (sTmpSrcFileName.contains("org.mozilla.fennec") || sTmpSrcFileName.contains("org.mozilla.firefox")) {
        ffxSrcFiles = Uri.parse(
                "content://" + (sTmpSrcFileName.contains("fennec") ? fenProvider : ffxProvider) + "/file");
        crIn = contextWrapper.getContentResolver();
    } else {
        try {
            srcFile = new FileInputStream(sTmpSrcFileName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    if (sTmpDstFileName.contains("org.mozilla.fennec") || sTmpDstFileName.contains("org.mozilla.firefox")) {
        ffxDstFiles = Uri.parse(
                "content://" + (sTmpDstFileName.contains("fennec") ? fenProvider : ffxProvider) + "/file");
        crOut = contextWrapper.getContentResolver();
        cv = new ContentValues();
    } else {
        try {
            dstFile = new FileOutputStream(sTmpDstFileName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    if (srcFile != null) {
        try {
            while ((nRead = srcFile.read(buffer)) != -1) {
                lTotalRead += nRead;
                if (dstFile != null) {
                    dstFile.write(buffer, 0, nRead);
                    dstFile.flush();
                } else {
                    cv.put("length", nRead);
                    cv.put("chunk", buffer);
                    if (crOut.update(ffxDstFiles, cv, sTmpDstFileName, null) == 0)
                        break;
                    lTotalWritten += nRead;
                }
            }

            srcFile.close();

            if (dstFile != null) {
                dstFile.flush();
                dstFile.close();

                destFile = new File(sTmpDstFileName);
                lTotalWritten = destFile.length();
            }

            if (lTotalWritten == lTotalRead) {
                sRet = sTmpSrcFileName + " copied to " + sTmpDstFileName;
            } else {
                sRet = sErrorPrefix + "Failed to copy " + sTmpSrcFileName + " [length = " + lTotalWritten
                        + "] to " + sTmpDstFileName + " [length = " + lTotalRead + "]";
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    } else {
        String[] columns = new String[] { "_id", "chunk", "length" };

        Cursor myCursor = crIn.query(ffxSrcFiles, columns, // Which columns to return
                sTmpSrcFileName, // Which rows to return (all rows)
                null, // Selection arguments (none)
                null); // Order clause (none)
        if (myCursor != null) {
            int nRows = myCursor.getCount();

            byte[] buf = null;

            for (int lcv = 0; lcv < nRows; lcv++) {
                if (myCursor.moveToPosition(lcv)) {
                    buf = myCursor.getBlob(myCursor.getColumnIndex("chunk"));
                    if (buf != null) {
                        nRead = buf.length;
                        try {
                            lTotalRead += nRead;
                            if (dstFile != null) {
                                dstFile.write(buffer, 0, nRead);
                                dstFile.flush();
                            } else {
                                cv.put("length", nRead);
                                cv.put("chunk", buffer);
                                if (crOut.update(ffxDstFiles, cv, sTmpDstFileName, null) == 0)
                                    break;
                                lTotalWritten += nRead;
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        buf = null;
                    }
                }
            }

            if (nRows == -1) {
                sRet = sErrorPrefix + sTmpSrcFileName + ",-1\nNo such file or directory";
            } else {
                myCursor.close();

                if (dstFile != null) {
                    try {
                        dstFile.flush();
                        dstFile.close();

                        destFile = new File(sTmpDstFileName);
                        lTotalWritten = destFile.length();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                if (lTotalWritten == lTotalRead) {
                    sRet = sTmpSrcFileName + " copied to " + sTmpDstFileName;
                } else {
                    sRet = sErrorPrefix + "Failed to copy " + sTmpSrcFileName + " [length = " + lTotalWritten
                            + "] to " + sTmpDstFileName + " [length = " + lTotalRead + "]";
                }
            }
        } else {
            sRet = sErrorPrefix + sTmpSrcFileName + ",-1\nUnable to access file (internal error)";
        }
    }

    return (sRet);
}

From source file:org.openintents.shopping.ui.ShoppingActivity.java

/**
 * Create list of tags./*from  www. j a v  a2s . c  o m*/
 * <p/>
 * Tags for notes can be comma-separated. Here we create a list of the
 * unique tags.
 *
 * @param listId
 * @return
 */
String[] getTaglist(String listId) {
    Cursor c;

    if (listId == null) {
        c = getContentResolver().query(ShoppingContract.Items.CONTENT_URI,
                new String[] { ShoppingContract.Items.TAGS }, null, null,
                ShoppingContract.Items.DEFAULT_SORT_ORDER);
    } else {
        Uri uri = Uri.parse("content://org.openintents.shopping/listtags").buildUpon().appendPath(listId)
                .build();
        c = getContentResolver().query(uri, new String[] { ShoppingContract.ContainsFull.ITEM_TAGS }, null,
                null, null);
    }

    // Create a set of all tags (every tag should only appear once).
    HashSet<String> tagset = new HashSet<String>();
    c.moveToPosition(-1);
    while (c.moveToNext()) {
        String tags = c.getString(0);
        if (tags != null) {
            // Split several tags in a line, separated by comma
            String[] smalltaglist = tags.split(",");
            for (String tag : smalltaglist) {
                if (!tag.equals("")) {
                    tagset.add(tag.trim());
                }
            }
        }
    }
    c.close();

    // Sort the list
    // 1. Convert HashSet to String list.
    ArrayList<String> list = new ArrayList<String>();
    list.addAll(tagset);
    // 2. Sort the String list
    Collections.sort(list);
    // 3. Convert it to String array
    return list.toArray(new String[list.size()]);
}

From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java

public String PrintDir(String sDir) {
    String sRet = "";
    int nFiles = 0;
    String sTmpDir = fixFileName(sDir);

    if (sTmpDir.contains("org.mozilla.fennec") || sTmpDir.contains("org.mozilla.firefox")) {
        ContentResolver cr = contextWrapper.getContentResolver();
        Uri ffxFiles = null;//from  w ww. j a va  2 s.  c  o m

        ffxFiles = Uri.parse("content://" + (sTmpDir.contains("fennec") ? fenProvider : ffxProvider) + "/dir");

        String[] columns = new String[] { "_id", "isdir", "filename", "length" };

        Cursor myCursor = cr.query(ffxFiles, columns, // Which columns to return
                sTmpDir, // Which rows to return (all rows)
                null, // Selection arguments (none)
                null); // Order clause (none)
        if (myCursor != null) {
            nFiles = myCursor.getCount();

            // If only one entry and the index is -1 this is not a directory
            int nNdx = myCursor.getColumnIndex("_id");
            // If no entries the dir is empty
            if (nFiles == 1) {
                sRet = "<empty>";
            } else {
                // Show the entries
                for (int lcv = 1; lcv < nFiles; lcv++) {
                    if (myCursor.moveToPosition(lcv)) {
                        if ((lcv == 0) && (myCursor.getLong(nNdx) == -1)) {
                            sRet = sErrorPrefix + sTmpDir + " is not a directory";
                        } else {
                            sRet += myCursor.getString(2);
                            if (lcv < (nFiles - 1))
                                sRet += "\n";
                        }
                    }
                }
            }
            myCursor.close();
        }
    } else {
        File dir = new File(sTmpDir);

        if (dir.isDirectory()) {
            File[] files = dir.listFiles();

            if (files != null) {
                if ((nFiles = files.length) > 0) {
                    for (int lcv = 0; lcv < nFiles; lcv++) {
                        sRet += files[lcv].getName();
                        if (lcv < (nFiles - 1)) {
                            sRet += "\n";
                        }
                    }
                } else {
                    sRet = "<empty>";
                }
            }
        } else {
            sRet = sErrorPrefix + sTmpDir + " is not a directory";
        }
    }
    return (sRet);
}

From source file:org.getlantern.firetweet.provider.FiretweetDataProvider.java

private void showMessagesNotification(AccountPreferences pref, StringLongPair[] pairs,
        ContentValues[] valuesArray) {//from  ww  w  . j a  v  a 2s  .  co  m
    final long accountId = pref.getAccountId();
    final long prevOldestId = mReadStateManager.getPosition(TAG_OLDEST_MESSAGES, String.valueOf(accountId));
    long oldestId = -1;
    for (final ContentValues contentValues : valuesArray) {
        final long messageId = contentValues.getAsLong(DirectMessages.MESSAGE_ID);
        oldestId = oldestId < 0 ? messageId : Math.min(oldestId, messageId);
        if (messageId <= prevOldestId)
            return;
    }
    mReadStateManager.setPosition(TAG_OLDEST_MESSAGES, String.valueOf(accountId), oldestId, false);
    final Context context = getContext();
    final Resources resources = context.getResources();
    final NotificationManager nm = getNotificationManager();
    final ArrayList<Expression> orExpressions = new ArrayList<>();
    final String prefix = accountId + "-";
    final int prefixLength = prefix.length();
    final Set<Long> senderIds = new CompactHashSet<>();
    for (StringLongPair pair : pairs) {
        final String key = pair.getKey();
        if (key.startsWith(prefix)) {
            final long senderId = Long.parseLong(key.substring(prefixLength));
            senderIds.add(senderId);
            final Expression expression = Expression.and(Expression.equals(DirectMessages.SENDER_ID, senderId),
                    Expression.greaterThan(DirectMessages.MESSAGE_ID, pair.getValue()));
            orExpressions.add(expression);
        }
    }
    orExpressions
            .add(Expression.notIn(new Column(DirectMessages.SENDER_ID), new RawItemArray(senderIds.toArray())));
    final Expression selection = Expression.and(Expression.equals(DirectMessages.ACCOUNT_ID, accountId),
            Expression.greaterThan(DirectMessages.MESSAGE_ID, prevOldestId),
            Expression.or(orExpressions.toArray(new Expression[orExpressions.size()])));
    final String filteredSelection = selection.getSQL();
    final String[] userProjection = { DirectMessages.SENDER_ID, DirectMessages.SENDER_NAME,
            DirectMessages.SENDER_SCREEN_NAME };
    final String[] messageProjection = { DirectMessages.MESSAGE_ID, DirectMessages.SENDER_ID,
            DirectMessages.SENDER_NAME, DirectMessages.SENDER_SCREEN_NAME, DirectMessages.TEXT_UNESCAPED,
            DirectMessages.MESSAGE_TIMESTAMP };
    final Cursor messageCursor = mDatabaseWrapper.query(DirectMessages.Inbox.TABLE_NAME, messageProjection,
            filteredSelection, null, null, null, DirectMessages.DEFAULT_SORT_ORDER);
    final Cursor userCursor = mDatabaseWrapper.query(DirectMessages.Inbox.TABLE_NAME, userProjection,
            filteredSelection, null, DirectMessages.SENDER_ID, null, DirectMessages.DEFAULT_SORT_ORDER);
    try {
        final int usersCount = userCursor.getCount();
        final int messagesCount = messageCursor.getCount();
        if (messagesCount == 0 || usersCount == 0)
            return;
        final String accountName = Utils.getAccountName(context, accountId);
        final String accountScreenName = Utils.getAccountScreenName(context, accountId);
        final int idxMessageText = messageCursor.getColumnIndex(DirectMessages.TEXT_UNESCAPED),
                idxMessageTimestamp = messageCursor.getColumnIndex(DirectMessages.MESSAGE_TIMESTAMP),
                idxMessageId = messageCursor.getColumnIndex(DirectMessages.MESSAGE_ID),
                idxMessageUserId = messageCursor.getColumnIndex(DirectMessages.SENDER_ID),
                idxMessageUserName = messageCursor.getColumnIndex(DirectMessages.SENDER_NAME),
                idxMessageUserScreenName = messageCursor.getColumnIndex(DirectMessages.SENDER_SCREEN_NAME),
                idxUserName = userCursor.getColumnIndex(DirectMessages.SENDER_NAME),
                idxUserScreenName = userCursor.getColumnIndex(DirectMessages.SENDER_NAME),
                idxUserId = userCursor.getColumnIndex(DirectMessages.SENDER_NAME);

        final CharSequence notificationTitle = resources.getQuantityString(R.plurals.N_new_messages,
                messagesCount, messagesCount);
        final String notificationContent;
        userCursor.moveToFirst();
        final String displayName = UserColorNameUtils.getUserNickname(context, userCursor.getLong(idxUserId),
                mNameFirst ? userCursor.getString(idxUserName) : userCursor.getString(idxUserScreenName));
        if (usersCount == 1) {
            if (messagesCount == 1) {
                notificationContent = context.getString(R.string.notification_direct_message, displayName);
            } else {
                notificationContent = context.getString(R.string.notification_direct_message_multiple_messages,
                        displayName, messagesCount);
            }
        } else {
            notificationContent = context.getString(R.string.notification_direct_message_multiple_users,
                    displayName, usersCount - 1, messagesCount);
        }

        final LongSparseArray<Long> idsMap = new LongSparseArray<>();
        // Add rich notification and get latest tweet timestamp
        long when = -1;
        final InboxStyle style = new InboxStyle();
        for (int i = 0; messageCursor.moveToPosition(i) && i < messagesCount; i++) {
            if (when < 0) {
                when = messageCursor.getLong(idxMessageTimestamp);
            }
            if (i < 5) {
                final SpannableStringBuilder sb = new SpannableStringBuilder();
                sb.append(UserColorNameUtils.getUserNickname(context, messageCursor.getLong(idxUserId),
                        mNameFirst ? messageCursor.getString(idxMessageUserName)
                                : messageCursor.getString(idxMessageUserScreenName)));
                sb.setSpan(new StyleSpan(Typeface.BOLD), 0, sb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                sb.append(' ');
                sb.append(messageCursor.getString(idxMessageText));
                style.addLine(sb);
            }
            final long userId = messageCursor.getLong(idxMessageUserId);
            final long messageId = messageCursor.getLong(idxMessageId);
            idsMap.put(userId, Math.max(idsMap.get(userId, -1L), messageId));
        }
        if (mNameFirst) {
            style.setSummaryText(accountName);
        } else {
            style.setSummaryText("@" + accountScreenName);
        }
        final StringLongPair[] positions = new StringLongPair[idsMap.size()];
        for (int i = 0, j = idsMap.size(); i < j; i++) {
            positions[i] = new StringLongPair(String.valueOf(idsMap.keyAt(i)), idsMap.valueAt(i));
        }

        // Setup notification
        final NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
        builder.setAutoCancel(true);
        builder.setSmallIcon(R.drawable.ic_stat_direct_message);
        builder.setTicker(notificationTitle);
        builder.setContentTitle(notificationTitle);
        builder.setContentText(notificationContent);
        builder.setCategory(NotificationCompat.CATEGORY_SOCIAL);
        builder.setContentIntent(getContentIntent(context, AUTHORITY_DIRECT_MESSAGES, accountId));
        builder.setContentIntent(getDeleteIntent(context, AUTHORITY_DIRECT_MESSAGES, accountId, positions));
        builder.setNumber(messagesCount);
        builder.setWhen(when);
        builder.setStyle(style);
        builder.setColor(pref.getNotificationLightColor());
        setNotificationPreferences(builder, pref, pref.getDirectMessagesNotificationType());
        nm.notify("messages_" + accountId, NOTIFICATION_ID_DIRECT_MESSAGES, builder.build());
        Utils.sendPebbleNotification(context, notificationContent);
    } finally {
        messageCursor.close();
        userCursor.close();
    }
}

From source file:com.guardtrax.ui.screens.HomeScreen.java

public static void updateTour(String tagNumber) {
    if (GTConstants.tourName.length() == 0)
        return;/*from  www  .  j  ava  2 s .  c  o  m*/

    boolean tourComplete = true;
    int i = 0; //this will be the position of the first item in the list that has not been scanned
    String temp = "";
    List<Boolean> tourtagsScanned = new ArrayList<Boolean>();
    List<Boolean> tourtagsIncluded = new ArrayList<Boolean>();
    List<Integer> tourOrder = new ArrayList<Integer>();

    tourDB.open();

    Cursor c = tourDB.getRecordByTour(GTConstants.tourName);

    if (c != null && c.moveToFirst()) {
        //get the included tags from the tour list
        tourtagsIncluded = refreshtourtagList(c.getCount(), false, false, true, false);
        tourtagsScanned = refreshtourtagList(c.getCount(), false, true, false, false);
        tourOrder = gettourOrder(c.getCount());

        //first update tag scanned information
        if (tagNumber.length() > 0) {
            //String setTime = c.getString(4);   //this is the time set for the tour

            for (i = 0; i < c.getCount(); i++) {
                //check if tag matches a tag in the tour list that has not yet been scanned
                if (tourtagsIncluded.get(i) && !tourtagsScanned.get(i)) {
                    //move to the database location of this item
                    c.moveToPosition(tourOrder.get(i));

                    if (c.getString(3).equals(tagNumber)) {
                        //Toast.makeText(ctx, "Tag: " + c.getString(3), Toast.LENGTH_SHORT).show();

                        //Toast.makeText(ctx, "item # / i: " + String.valueOf(touritemNumber) + " / " + tourOrder.get(i), Toast.LENGTH_SHORT).show();

                        //first check if this is a single display random tour and that this is the correct tag.  If not exit!
                        if (tourOrder.get(i) != touritemNumber && isSingleRandomTour()) {
                            tourDB.close();
                            return;
                        }

                        //write to the tour tag list
                        refreshtourtagList(i, false, false, false, true);

                        //if trp file not yet created, then create it
                        if (GTConstants.trpfilename.length() < 2) {
                            //create the tour report file name
                            GTConstants.trpfilename = GTConstants.LICENSE_ID.substring(7) + "_"
                                    + Utility.getUTCDate() + "_" + Utility.getUTCTime() + ".trp";

                            //write the version to the trp file
                            Utility.write_to_file(ctx,
                                    GTConstants.dardestinationFolder + GTConstants.trpfilename,
                                    "Version;" + GTConstants.version + "\r\n", false);

                            //write the tour name to the trp file
                            Utility.write_to_file(ctx,
                                    GTConstants.dardestinationFolder + GTConstants.trpfilename,
                                    "Tour;" + GTConstants.tourName + ";" + Utility.getLocalTime() + ";"
                                            + Utility.getLocalDate() + "\r\n",
                                    true);

                            //write the user name to the trp file
                            Utility.write_to_file(ctx,
                                    GTConstants.dardestinationFolder + GTConstants.trpfilename,
                                    "Name;" + GTConstants.report_name + "\r\n", true);

                        }

                        //check if scan is late
                        temp = String.valueOf(Utility.istourOntime(tourEnd));

                        Utility.write_to_file(ctx, GTConstants.dardestinationFolder + GTConstants.trpfilename,
                                "Tag Scan;" + tagNumber + ";" + temp + ";" + Utility.getLocalTime() + ";"
                                        + Utility.getLocalDate() + "\r\n",
                                true);

                        break;
                    }
                }
            }

        }

        //get the list of scannedtags from file
        tourtagsScanned = refreshtourtagList(c.getCount(), false, true, false, false);

        //check the tourtagsScanned list to see if all tags have been scanned and set the touritemNumber (touritemNumber is the location in the database list)
        for (i = 0; i < c.getCount(); i++) {
            if (!tourtagsScanned.get(i) && tourtagsIncluded.get(i)) {
                //go to the position of the next tag to scan which is the next one in the tour order list
                touritemNumber = tourOrder.get(i);

                //Toast.makeText(ctx, "Tour item #: " + String.valueOf(touritemNumber), Toast.LENGTH_SHORT).show();
                //get the location name from the database 
                c.moveToPosition(touritemNumber);
                temp = c.getString(2);

                tourComplete = false;
                break;
            }
        }

        //if tour is done then reset and display message
        if (tourComplete) {
            tourDB.close();

            //write to the trp file 
            endtrpFile(true);

            setwarningText("Tour complete");
            return;
        } else {
            //check if single display randomized tour.  If so, get the next tag info and display in popup
            if (isSingleRandomTour()) {
                MainService.mainserviceDialog("Tour Info", "Next Tag: " + CRLF + temp);
            }

            tourDB.close();

            setwarningText("");

            return;
        }
    }

    tourDB.close();
}

From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java

public String processCommand(String theCmdLine, PrintWriter out, BufferedInputStream in, OutputStream cmdOut) {
    String strReturn = "";
    Command cCmd = null;//from   w  w w . j  a v a 2 s.  c  om
    Command cSubCmd = null;

    if (bTraceOn)
        ((ASMozStub) this.contextWrapper).SendToDataChannel(theCmdLine);

    String[] Argv = parseCmdLine2(theCmdLine);

    int Argc = Argv.length;

    cCmd = Command.getCmd(Argv[0]);

    switch (cCmd) {
    case TRACE:
        if (Argc == 2)
            bTraceOn = (Argv[1].equalsIgnoreCase("on") ? true : false);
        else
            strReturn = sErrorPrefix + "Wrong number of arguments for trace command!";
        break;

    case VER:
        strReturn = prgVersion;
        break;

    case CLOK:
        strReturn = GetClok();
        break;

    case TZGET:
        strReturn = GetTimeZone();
        break;

    case TZSET:
        if (Argc == 2)
            strReturn = SetTimeZone(Argv[1]);
        else
            strReturn = sErrorPrefix + "Wrong number of arguments for settz command!";
        break;

    case UPDT:
        if (Argc >= 2)
            strReturn = StrtUpdtOMatic(Argv[1], Argv[2], (Argc > 3 ? Argv[3] : null),
                    (Argc > 4 ? Argv[4] : null));
        else
            strReturn = sErrorPrefix + "Wrong number of arguments for updt command!";
        break;

    case SETTIME:
        strReturn = SetSystemTime(Argv[1], (Argc > 2 ? Argv[2] : null), cmdOut);
        break;

    case CWD:
        try {
            strReturn = new java.io.File(currentDir).getCanonicalPath();
        } catch (IOException e) {
            e.printStackTrace();
        }
        break;

    case CD:
        if (Argc == 2)
            strReturn = changeDir(Argv[1]);
        else
            strReturn = sErrorPrefix + "Wrong number of arguments for cd command!";
        break;

    case LS:
        strReturn = PrintDir(((Argc > 1) ? Argv[1] : currentDir));
        break;

    case GETAPPROOT:
        if (Argc == 2)
            strReturn = GetAppRoot(Argv[1]);
        else
            strReturn = sErrorPrefix + "Wrong number of arguments for getapproot command!";
        break;

    case ISDIR:
        if (Argc == 2)
            strReturn = isDirectory(Argv[1]);
        else
            strReturn = sErrorPrefix + "Wrong number of arguments for isdir command!";
        break;

    case TESTROOT:
        strReturn = GetTestRoot();
        break;

    case DEAD:
        if (Argc == 2)
            strReturn = (IsProcessDead(Argv[1]) ? (Argv[1] + " is hung or unresponsive")
                    : (Argv[1] + " is ok"));
        else
            strReturn = sErrorPrefix + "Wrong number of arguments for dead command!";
        break;

    case PS:
        strReturn = GetProcessInfo();
        break;

    case PULL:
        if (Argc >= 2) {
            long lOff = 0;
            long lLen = -1;
            if (Argc > 2) {
                try {
                    lOff = Long.parseLong(Argv[2].trim());
                } catch (NumberFormatException nfe) {
                    lOff = 0;
                    System.out.println("NumberFormatException: " + nfe.getMessage());
                }
            }
            if (Argc == 4) {
                try {
                    lLen = Long.parseLong(Argv[3].trim());
                } catch (NumberFormatException nfe) {
                    lLen = -1;
                    System.out.println("NumberFormatException: " + nfe.getMessage());
                }
            }
            strReturn = Pull(Argv[1], lOff, lLen, cmdOut);
        } else {
            strReturn = sErrorPrefix + "Wrong number of arguments for pull command!";
        }
        break;

    case PUSH:
        if (Argc == 3) {
            long lArg = 0;
            try {
                lArg = Long.parseLong(Argv[2].trim());
            } catch (NumberFormatException nfe) {
                System.out.println("NumberFormatException: " + nfe.getMessage());
            }

            strReturn = Push(Argv[1], in, lArg);
        } else
            strReturn = sErrorPrefix + "Wrong number of arguments for push command!";
        break;

    case INST:
        if (Argc >= 2)
            strReturn = InstallApp(Argv[1], cmdOut);
        else
            strReturn = sErrorPrefix + "Wrong number of arguments for inst command!";
        break;

    case UNINST:
        if (Argc >= 2)
            strReturn = UnInstallApp(Argv[1], cmdOut, true);
        else
            strReturn = sErrorPrefix + "Wrong number of arguments for uninst command!";
        break;

    case UNINSTALL:
        if (Argc >= 2)
            strReturn = UnInstallApp(Argv[1], cmdOut, false);
        else
            strReturn = sErrorPrefix + "Wrong number of arguments for uninstall command!";
        break;

    case ALRT:
        if (Argc > 1) {
            if (Argv[1].contentEquals("on")) {
                String sTitle = "Agent Alert";
                String sMsg = "The Agent Alert System has been activated!";
                if (Argc == 3) {
                    sTitle = Argv[2];
                    sMsg = "";
                } else if (Argc == 4) {
                    sTitle = Argv[2];
                    sMsg = Argv[3];
                }
                StartAlert(sTitle, sMsg);
            } else {
                StopAlert();
            }
        } else {
            strReturn = sErrorPrefix + "Wrong number of arguments for alrt command!";
        }
        break;

    case REBT:
        if (Argc >= 1)
            strReturn = RunReboot(cmdOut, (Argc > 1 ? Argv[1] : null), (Argc > 2 ? Argv[2] : null));
        else
            strReturn = sErrorPrefix + "Wrong number of arguments for rebt command!";
        //                RunReboot(cmdOut);
        break;

    case TMPD:
        strReturn = GetTmpDir();
        break;

    case DEVINFO:
        if (Argc == 1) {
            strReturn += SUTAgentAndroid.sUniqueID;
            strReturn += "\n";
            strReturn += GetOSInfo();
            strReturn += "\n";
            strReturn += GetSystemTime();
            strReturn += "\n";
            strReturn += GetUptime();
            strReturn += "\n";
            strReturn += GetUptimeMillis();
            strReturn += "\n";
            strReturn += GetSutUptimeMillis();
            strReturn += "\n";
            strReturn += GetScreenInfo();
            strReturn += "\n";
            strReturn += GetRotationInfo();
            strReturn += "\n";
            strReturn += GetMemoryInfo();
            strReturn += "\n";
            strReturn += GetPowerInfo();
            strReturn += "\n";
            strReturn += GetTemperatureInfo();
            strReturn += "\n";
            strReturn += GetProcessInfo();
            strReturn += "\n";
            strReturn += GetSutUserInfo();
            strReturn += "\n";
            strReturn += GetDiskInfo("/data");
            strReturn += "\n";
            strReturn += GetDiskInfo("/system");
            strReturn += "\n";
            strReturn += GetDiskInfo("/mnt/sdcard");
        } else {
            cSubCmd = Command.getCmd(Argv[1]);
            switch (cSubCmd) {
            case ID:
                strReturn = SUTAgentAndroid.sUniqueID;
                break;

            case SCREEN:
                strReturn = GetScreenInfo();
                break;

            case ROTATION:
                strReturn = GetRotationInfo();
                break;

            case PROCESS:
                strReturn = GetProcessInfo();
                break;

            case OS:
                strReturn = GetOSInfo();
                break;

            case SYSTIME:
                strReturn = GetSystemTime();
                break;

            case UPTIME:
                strReturn = GetUptime();
                break;

            case UPTIMEMILLIS:
                strReturn = GetUptimeMillis();
                break;

            case SUTUPTIMEMILLIS:
                strReturn = GetSutUptimeMillis();
                break;

            case MEMORY:
                strReturn = GetMemoryInfo();
                break;

            case POWER:
                strReturn += GetPowerInfo();
                break;

            case SUTUSERINFO:
                strReturn += GetSutUserInfo();
                break;

            case TEMPERATURE:
                strReturn += GetTemperatureInfo();
                break;

            case DISK:
                strReturn += "\n";
                strReturn += GetDiskInfo("/data");
                strReturn += "\n";
                strReturn += GetDiskInfo("/system");
                strReturn += "\n";
                strReturn += GetDiskInfo("/mnt/sdcard");
                break;

            default:
                break;
            }
        }
        break;

    case STAT:
        if (Argc == 2)
            strReturn = StatProcess(Argv[1]);
        else
            strReturn = sErrorPrefix + "Wrong number of arguments for ping command!";
        break;

    case PING:
        if (Argc == 2)
            strReturn = SendPing(Argv[1], cmdOut);
        else
            strReturn = sErrorPrefix + "Wrong number of arguments for ping command!";
        break;

    case HASH:
        if (Argc == 2)
            strReturn = HashFile(Argv[1]);
        else
            strReturn = sErrorPrefix + "Wrong number of arguments for hash command!";
        break;

    case PRUNE:
        if (Argc == 2)
            strReturn = PruneDir(Argv[1]);
        else
            strReturn = sErrorPrefix + "Wrong number of arguments for prune command!";
        break;

    case FTPG:
        if (Argc == 4)
            strReturn = FTPGetFile(Argv[1], Argv[2], Argv[3], cmdOut);
        else
            strReturn = sErrorPrefix + "Wrong number of arguments for ftpg command!";
        break;

    case CAT:
        if (Argc == 2)
            strReturn = Cat(Argv[1], cmdOut);
        else
            strReturn = sErrorPrefix + "Wrong number of arguments for cat command!";
        break;

    case DIRWRITABLE:
        if (Argc == 2)
            strReturn = IsDirWritable(Argv[1]);
        else
            strReturn = sErrorPrefix + "Wrong number of arguments for dirwritable command!";
        break;

    case TIME:
        if (Argc == 2)
            strReturn = PrintFileTimestamp(Argv[1]);
        else
            strReturn = sErrorPrefix + "Wrong number of arguments for time command!";
        break;

    case MKDR:
        if (Argc == 2)
            strReturn = MakeDir(Argv[1]);
        else
            strReturn = sErrorPrefix + "Wrong number of arguments for mkdr command!";
        break;

    case RM:
        if (Argc == 2)
            strReturn = RemoveFile(Argv[1]);
        else
            strReturn = sErrorPrefix + "Wrong number of arguments for rm command!";
        break;

    case MV:
        if (Argc == 3)
            strReturn = Move(Argv[1], Argv[2]);
        else
            strReturn = sErrorPrefix + "Wrong number of arguments for mv command!";
        break;

    case CP:
        if (Argc == 3)
            strReturn = CopyFile(Argv[1], Argv[2]);
        else
            strReturn = sErrorPrefix + "Wrong number of arguments for cp command!";
        break;

    case QUIT:
    case EXIT:
        strReturn = Argv[0];
        break;

    case DBG:
        Debug.waitForDebugger();
        strReturn = "waitForDebugger on";
        break;

    case ADB:
        if (Argc == 2) {
            if (Argv[1].contains("ip") || Argv[1].contains("usb")) {
                strReturn = SetADB(Argv[1]);
            } else {
                strReturn = sErrorPrefix + "Unrecognized argument for adb command!";
            }
        } else {
            strReturn = sErrorPrefix + "Wrong number of arguments for adb command!";
        }
        break;

    case TEST:
        long lFreeMemory = Runtime.getRuntime().freeMemory();
        long lTotMemory = Runtime.getRuntime().totalMemory();
        long lMaxMemory = Runtime.getRuntime().maxMemory();

        if (lFreeMemory > 0) {
            strReturn = "Max memory: " + lMaxMemory + "\nTotal Memory: " + lTotMemory + "\nFree memory: "
                    + lFreeMemory;
            break;
        }

        ContentResolver cr = contextWrapper.getContentResolver();
        Uri ffxFiles = null;

        if (Argv[1].contains("fennec")) {
            ffxFiles = Uri.parse("content://" + fenProvider + "/dir");
        } else if (Argv[1].contains("firefox")) {
            ffxFiles = Uri.parse("content://" + ffxProvider + "/dir");
        }

        //                Uri ffxFiles = Uri.parse("content://org.mozilla.fencp/file");
        String[] columns = new String[] { "_id", "isdir", "filename", "length" };
        //                String[] columns = new String[] {
        //                        "_id",
        //                        "chunk"
        //                     };
        Cursor myCursor = cr.query(ffxFiles, columns, // Which columns to return
                (Argc > 1 ? Argv[1] : null), // Which rows to return (all rows)
                null, // Selection arguments (none)
                null); // Put the results in ascending order by name
        /*
        if (myCursor != null) {
            int nRows = myCursor.getCount();
            String [] colNames = myCursor.getColumnNames();
            int    nID = 0;
            int nBytesRecvd = 0;
                
            for (int lcv = 0; lcv < nRows; lcv++) {
                if  (myCursor.moveToPosition(lcv)) {
                    nID = myCursor.getInt(0);
                    byte [] buf = myCursor.getBlob(1);
                    if (buf != null) {
                        nBytesRecvd += buf.length;
                        strReturn += new String(buf);
                        buf = null;
                    }
                }
            }
            strReturn += "[eof - " + nBytesRecvd + "]";
            myCursor.close();
        }
                
        */
        if (myCursor != null) {
            int nRows = myCursor.getCount();
            int nID = 0;
            String sFileName = "";
            long lFileSize = 0;
            boolean bIsDir = false;

            for (int lcv = 0; lcv < nRows; lcv++) {
                if (myCursor.moveToPosition(lcv)) {
                    nID = myCursor.getInt(0);
                    bIsDir = (myCursor.getInt(1) == 1 ? true : false);
                    sFileName = myCursor.getString(2);
                    lFileSize = myCursor.getLong(3);
                    strReturn += "" + nID + "\t" + (bIsDir ? "<dir> " : "      ") + sFileName + "\t" + lFileSize
                            + "\n";
                }
            }
            myCursor.close();
        }
        break;

    case EXEC:
    case ENVRUN:
        if (Argc >= 2) {
            String[] theArgs = new String[Argc - 1];

            for (int lcv = 1; lcv < Argc; lcv++) {
                theArgs[lcv - 1] = Argv[lcv];
            }

            strReturn = StartPrg2(theArgs, cmdOut, null, false, DEFAULT_STARTPRG_TIMEOUT_SECONDS);
        } else {
            strReturn = sErrorPrefix + "Wrong number of arguments for " + Argv[0] + " command!";
        }
        break;

    case EXECSU:
        if (Argc >= 2) {
            String[] theArgs = new String[Argc - 1];

            for (int lcv = 1; lcv < Argc; lcv++) {
                theArgs[lcv - 1] = Argv[lcv];
            }

            strReturn = StartPrg2(theArgs, cmdOut, null, true, DEFAULT_STARTPRG_TIMEOUT_SECONDS);
        } else {
            strReturn = sErrorPrefix + "Wrong number of arguments for " + Argv[0] + " command!";
        }
        break;

    case EXECCWD:
        if (Argc >= 3) {
            String[] theArgs = new String[Argc - 2];

            for (int lcv = 2; lcv < Argc; lcv++) {
                theArgs[lcv - 2] = Argv[lcv];
            }

            strReturn = StartPrg2(theArgs, cmdOut, Argv[1], false, DEFAULT_STARTPRG_TIMEOUT_SECONDS);
        } else {
            strReturn = sErrorPrefix + "Wrong number of arguments for " + Argv[0] + " command!";
        }
        break;

    case EXECCWDSU:
        if (Argc >= 3) {
            String[] theArgs = new String[Argc - 2];

            for (int lcv = 2; lcv < Argc; lcv++) {
                theArgs[lcv - 2] = Argv[lcv];
            }

            strReturn = StartPrg2(theArgs, cmdOut, Argv[1], true, DEFAULT_STARTPRG_TIMEOUT_SECONDS);
        } else {
            strReturn = sErrorPrefix + "Wrong number of arguments for " + Argv[0] + " command!";
        }
        break;

    case RUN:
        if (Argc >= 2) {
            String[] theArgs = new String[Argc - 1];

            for (int lcv = 1; lcv < Argc; lcv++) {
                theArgs[lcv - 1] = Argv[lcv];
            }

            if (Argv[1].contains("/") || Argv[1].contains("\\") || !Argv[1].contains("."))
                strReturn = StartPrg(theArgs, cmdOut, false, DEFAULT_STARTPRG_TIMEOUT_SECONDS);
            else
                strReturn = StartJavaPrg(theArgs, null);
        } else {
            strReturn = sErrorPrefix + "Wrong number of arguments for " + Argv[0] + " command!";
        }
        break;

    case EXECEXT:
        // An "extended" exec command with format:
        //    execext [su] [cwd=<path>] [t=<timeout in seconds>] arg1 ...
        if (Argc >= 2) {
            boolean su = false;
            String cwd = null;
            int timeout = DEFAULT_STARTPRG_TIMEOUT_SECONDS;
            int extra;
            for (extra = 1; extra < Argc; extra++) {
                if (Argv[extra].equals("su")) {
                    su = true;
                } else if (Argv[extra].startsWith("cwd=")) {
                    cwd = Argv[extra].substring(4);
                } else if (Argv[extra].startsWith("t=")) {
                    timeout = Integer.parseInt(Argv[extra].substring(2));
                    if (timeout < 1 || timeout > 4 * 60 * 60) {
                        Log.e("SUTAgentAndroid", "invalid execext timeout " + Argv[extra].substring(2)
                                + "; using default instead");
                        timeout = DEFAULT_STARTPRG_TIMEOUT_SECONDS;
                    }
                } else {
                    break;
                }
            }

            if (extra < Argc) {
                String[] theArgs = new String[Argc - extra];
                for (int lcv = extra; lcv < Argc; lcv++) {
                    theArgs[lcv - extra] = Argv[lcv];
                }

                strReturn = StartPrg2(theArgs, cmdOut, cwd, su, timeout);
            } else {
                strReturn = sErrorPrefix + "No regular arguments for " + Argv[0] + " command!";
            }
        } else {
            strReturn = sErrorPrefix + "Wrong number of arguments for " + Argv[0] + " command!";
        }
        break;

    case KILL:
        if (Argc == 2)
            strReturn = KillProcess(Argv[1], cmdOut);
        else
            strReturn = sErrorPrefix + "Wrong number of arguments for kill command!";
        break;

    case DISK:
        strReturn = GetDiskInfo((Argc == 2 ? Argv[1] : "/"));
        break;

    case UNZP:
        strReturn = Unzip(Argv[1], (Argc == 3 ? Argv[2] : ""));
        break;

    case ZIP:
        strReturn = Zip(Argv[1], (Argc == 3 ? Argv[2] : ""));
        break;

    case CHMOD:
        if (Argc == 2)
            strReturn = ChmodDir(Argv[1]);
        else
            strReturn = sErrorPrefix + "Wrong number of arguments for chmod command!";
        break;

    case TOPACTIVITY:
        strReturn = TopActivity();
        break;

    case HELP:
        strReturn = PrintUsage();
        break;

    default:
        strReturn = sErrorPrefix + "[" + Argv[0] + "] command";
        if (Argc > 1) {
            strReturn += " with arg(s) =";
            for (int lcv = 1; lcv < Argc; lcv++) {
                strReturn += " [" + Argv[lcv] + "]";
            }
        }
        strReturn += " is currently not implemented.";
        break;
    }

    return (strReturn);
}

From source file:org.tvbrowser.tvbrowser.TvBrowser.java

private void uploadChannels() {
    String[] projection = { TvBrowserContentProvider.GROUP_KEY_GROUP_ID,
            TvBrowserContentProvider.CHANNEL_KEY_CHANNEL_ID,
            TvBrowserContentProvider.CHANNEL_KEY_ORDER_NUMBER };

    Cursor channels = getContentResolver().query(TvBrowserContentProvider.CONTENT_URI_CHANNELS, projection,
            TvBrowserContentProvider.CHANNEL_KEY_SELECTION, null,
            TvBrowserContentProvider.CHANNEL_KEY_ORDER_NUMBER);

    SparseArray<String> groupKeys = new SparseArray<String>();

    StringBuilder uploadChannels = new StringBuilder();

    try {//from ww  w  .jav a  2  s. c o  m
        channels.moveToPosition(-1);

        int groupKeyColumn = channels.getColumnIndex(TvBrowserContentProvider.GROUP_KEY_GROUP_ID);
        int channelKeyColumn = channels.getColumnIndex(TvBrowserContentProvider.CHANNEL_KEY_CHANNEL_ID);
        int channelKeyOrderNumberColumn = channels
                .getColumnIndex(TvBrowserContentProvider.CHANNEL_KEY_ORDER_NUMBER);

        while (channels.moveToNext()) {
            int groupKey = channels.getInt(groupKeyColumn);
            String channelId = channels.getString(channelKeyColumn);
            int orderNumber = channels.getInt(channelKeyOrderNumberColumn);

            String groupId = groupKeys.get(groupKey);

            if (groupId == null) {
                String[] groupProjection = { TvBrowserContentProvider.GROUP_KEY_GROUP_ID,
                        TvBrowserContentProvider.GROUP_KEY_DATA_SERVICE_ID };

                Cursor groups = getContentResolver().query(TvBrowserContentProvider.CONTENT_URI_GROUPS,
                        groupProjection, TvBrowserContentProvider.KEY_ID + "=" + groupKey, null, null);

                try {
                    if (groups.moveToFirst()) {
                        String dataServiceId = groups.getString(
                                groups.getColumnIndex(TvBrowserContentProvider.GROUP_KEY_DATA_SERVICE_ID));
                        String goupIdValue = groups
                                .getString(groups.getColumnIndex(TvBrowserContentProvider.GROUP_KEY_GROUP_ID));

                        String dataServiceIdNumber = SettingConstants.getNumberForDataServiceKey(dataServiceId);

                        if (dataServiceIdNumber != null) {
                            if (dataServiceId.equals(SettingConstants.EPG_FREE_KEY)) {
                                groupId = dataServiceIdNumber + ":" + goupIdValue + ":";
                            } else if (dataServiceId.equals(SettingConstants.EPG_DONATE_KEY)) {
                                groupId = dataServiceIdNumber + ":";
                            }
                            groupKeys.put(groupKey, groupId);
                        }
                    }
                } finally {
                    groups.close();
                }
            }

            uploadChannels.append(groupId).append(channelId);

            if (orderNumber > 0) {
                uploadChannels.append(":").append(orderNumber);
            }

            uploadChannels.append("\n");
        }
    } finally {
        channels.close();
    }

    if (uploadChannels.toString().trim().length() > 0) {
        startSynchronizeUp(true, uploadChannels.toString().trim(),
                "http://android.tvbrowser.org/data/scripts/syncUp.php?type=channelsFromDesktop",
                SettingConstants.SYNCHRONIZE_UP_DONE, getString(R.string.backup_channels_success));
    }
}

From source file:com.tct.email.provider.EmailMessageCursor.java

public EmailMessageCursor(final Context c, final Cursor cursor, final String htmlColumn,
        final String textColumn) {
    super(cursor);
    mHtmlColumnIndex = cursor.getColumnIndex(htmlColumn);
    mTextColumnIndex = cursor.getColumnIndex(textColumn);
    final int cursorSize = cursor.getCount();
    mHtmlParts = new SparseArray<String>(cursorSize);
    mTextParts = new SparseArray<String>(cursorSize);
    //TS: jian.xu 2015-11-03 EMAIL BUGFIX-845079 ADD_S
    mHtmlLinkifyColumnIndex = cursor.getColumnIndex(UIProvider.MessageColumns.BODY_HTML_LINKIFY);
    mHtmlLinkifyParts = new SparseArray<String>(cursorSize);
    mTextLinkifyColumnIndex = cursor.getColumnIndex(UIProvider.MessageColumns.BODY_TEXT_LINKIFY);
    mTextLinkifyParts = new SparseArray<String>(cursorSize);
    //TS: jian.xu 2015-11-03 EMAIL BUGFIX-845079 ADD_E

    final ContentResolver cr = c.getContentResolver();

    while (cursor.moveToNext()) {
        final int position = cursor.getPosition();
        final long messageId = cursor.getLong(cursor.getColumnIndex(BaseColumns._ID));
        // TS: chao.zhang 2015-09-14 EMAIL BUGFIX-1039046  MOD_S
        InputStream htmlIn = null;
        InputStream textIn = null;
        try {//w  w  w . ja v a2 s .co m
            if (mHtmlColumnIndex != -1) {
                final Uri htmlUri = Body.getBodyHtmlUriForMessageWithId(messageId);
                //WARNING: Actually openInput will used 2 PIPE(FD) to connect,but if some exception happen during connect,
                //such as fileNotFoundException,maybe the connection will not be closed. just a try!!!
                htmlIn = cr.openInputStream(htmlUri);
                final String underlyingHtmlString;
                try {
                    underlyingHtmlString = IOUtils.toString(htmlIn);
                } finally {
                    htmlIn.close();
                    htmlIn = null;
                }
                //TS: zhaotianyong 2015-04-05 EMAIL BUGFIX_964325 MOD_S
                final String sanitizedHtml = HtmlSanitizer.sanitizeHtml(underlyingHtmlString);
                mHtmlParts.put(position, sanitizedHtml);
                //TS: zhaotianyong 2015-04-05 EMAIL BUGFIX_964325 MOD_E
                //TS: jian.xu 2015-11-03 EMAIL BUGFIX-845079 ADD_S
                //NOTE: add links for sanitized html
                if (!TextUtils.isEmpty(sanitizedHtml)) {
                    final String linkifyHtml = com.tct.mail.utils.Linkify.addLinks(sanitizedHtml);
                    mHtmlLinkifyParts.put(position, linkifyHtml);
                } else {
                    mHtmlLinkifyParts.put(position, "");
                }
                //TS: jian.xu 2015-11-03 EMAIL BUGFIX-845079 ADD_E
            }
        } catch (final IOException e) {
            LogUtils.v(LogUtils.TAG, e, "Did not find html body for message %d", messageId);
        } catch (final OutOfMemoryError oom) {
            LogUtils.v(LogUtils.TAG, oom,
                    "Terrible,OOM happen durning query EmailMessageCursor in bodyHtml,current message %d",
                    messageId);
            mHtmlLinkifyParts.put(position, "");
        }
        try {
            if (mTextColumnIndex != -1) {
                final Uri textUri = Body.getBodyTextUriForMessageWithId(messageId);
                textIn = cr.openInputStream(textUri);
                final String underlyingTextString;
                try {
                    underlyingTextString = IOUtils.toString(textIn);
                } finally {
                    textIn.close();
                    textIn = null;
                }
                mTextParts.put(position, underlyingTextString);
                //TS: jian.xu 2015-11-03 EMAIL BUGFIX-845079 ADD_S
                //NOTE: add links for underlying text string
                if (!TextUtils.isEmpty(underlyingTextString)) {
                    final SpannableString spannable = new SpannableString(underlyingTextString);
                    Linkify.addLinks(spannable,
                            Linkify.EMAIL_ADDRESSES | Linkify.WEB_URLS | Linkify.PHONE_NUMBERS);
                    final String linkifyText = Html.toHtml(spannable);
                    mTextLinkifyParts.put(position, linkifyText);
                } else {
                    mTextLinkifyParts.put(position, "");
                }
                //TS: jian.xu 2015-11-03 EMAIL BUGFIX-845079 ADD_E
            }
        } catch (final IOException e) {
            LogUtils.v(LogUtils.TAG, e, "Did not find text body for message %d", messageId);
        } catch (final OutOfMemoryError oom) {
            LogUtils.v(LogUtils.TAG, oom,
                    "Terrible,OOM happen durning query EmailMessageCursor in bodyText,current message %d",
                    messageId);
            mTextLinkifyParts.put(position, "");
        }
        //NOTE:Remember that this just a protective code,for better release Not used Resources.
        if (htmlIn != null) {
            try {
                htmlIn.close();
            } catch (IOException e1) {
                LogUtils.v(LogUtils.TAG, e1, "IOException happen while close the htmlInput connection ");
            }
        }
        if (textIn != null) {
            try {
                textIn.close();
            } catch (IOException e2) {
                LogUtils.v(LogUtils.TAG, e2, "IOException happen while close the textInput connection ");
            }
        } // TS: chao.zhang 2015-09-14 EMAIL BUGFIX-1039046  MOD_E
    }
    cursor.moveToPosition(-1);
}

From source file:org.tvbrowser.tvbrowser.TvBrowser.java

private void showChannelSelectionInternal(final String selection, final String title, final String help,
        final boolean delete) {
    String[] projection = {/*from   w ww  .  j  a  v  a  2 s . c  om*/
            TvBrowserContentProvider.CHANNEL_TABLE + "." + TvBrowserContentProvider.KEY_ID + " AS "
                    + TvBrowserContentProvider.KEY_ID,
            TvBrowserContentProvider.GROUP_KEY_DATA_SERVICE_ID, TvBrowserContentProvider.CHANNEL_KEY_NAME,
            TvBrowserContentProvider.CHANNEL_KEY_SELECTION, TvBrowserContentProvider.CHANNEL_KEY_CATEGORY,
            TvBrowserContentProvider.CHANNEL_KEY_LOGO, TvBrowserContentProvider.CHANNEL_KEY_ALL_COUNTRIES };

    ContentResolver cr = getContentResolver();
    Cursor channels = cr.query(TvBrowserContentProvider.CONTENT_URI_CHANNELS_WITH_GROUP, projection, selection,
            null, TvBrowserContentProvider.CHANNEL_KEY_NAME);
    channels.moveToPosition(-1);

    // populate array list with all available channels
    final ArrayListWrapper channelSelectionList = new ArrayListWrapper();
    ArrayList<Country> countryList = new ArrayList<Country>();

    int channelIdColumn = channels.getColumnIndex(TvBrowserContentProvider.KEY_ID);
    int categoryColumn = channels.getColumnIndex(TvBrowserContentProvider.CHANNEL_KEY_CATEGORY);
    int logoColumn = channels.getColumnIndex(TvBrowserContentProvider.CHANNEL_KEY_LOGO);
    int dataServiceColumn = channels.getColumnIndex(TvBrowserContentProvider.GROUP_KEY_DATA_SERVICE_ID);
    int nameColumn = channels.getColumnIndex(TvBrowserContentProvider.CHANNEL_KEY_NAME);
    int countyColumn = channels.getColumnIndex(TvBrowserContentProvider.CHANNEL_KEY_ALL_COUNTRIES);
    int selectionColumn = channels.getColumnIndex(TvBrowserContentProvider.CHANNEL_KEY_SELECTION);
    ;
    while (channels.moveToNext()) {
        int channelID = channels.getInt(channelIdColumn);
        int category = channels.getInt(categoryColumn);
        byte[] logo = channels.getBlob(logoColumn);
        String dataService = channels.getString(dataServiceColumn);
        String name = channels.getString(nameColumn);
        String countries = channels.getString(countyColumn);
        boolean isSelected = channels.getInt(selectionColumn) == 1 && !delete;

        if (countries.contains("$")) {
            String[] values = countries.split("\\$");

            for (String country : values) {
                Country test = new Country(new Locale(country, country));

                if (!countryList.contains(test) && test.mLocale.getDisplayCountry().trim().length() > 0) {
                    countryList.add(test);
                }
            }
        } else {
            Country test = new Country(new Locale(countries, countries));

            if (!countryList.contains(test) && test.mLocale.getDisplayCountry().trim().length() > 0) {
                countryList.add(test);
            }
        }

        Bitmap channelLogo = UiUtils.createBitmapFromByteArray(logo);

        if (channelLogo != null) {
            BitmapDrawable l = new BitmapDrawable(getResources(), channelLogo);

            ColorDrawable background = new ColorDrawable(SettingConstants.LOGO_BACKGROUND_COLOR);
            background.setBounds(0, 0, channelLogo.getWidth() + 2, channelLogo.getHeight() + 2);

            LayerDrawable logoDrawable = new LayerDrawable(new Drawable[] { background, l });
            logoDrawable.setBounds(background.getBounds());

            l.setBounds(2, 2, channelLogo.getWidth(), channelLogo.getHeight());

            channelLogo = UiUtils.drawableToBitmap(logoDrawable);
        }

        channelSelectionList.add(new ChannelSelection(channelID, name, category, countries, channelLogo,
                isSelected, SettingConstants.EPG_DONATE_KEY.equals(dataService)));
    }

    // sort countries for filtering
    Collections.sort(countryList, new Comparator<Country>() {
        @Override
        public int compare(Country lhs, Country rhs) {
            return lhs.toString().compareToIgnoreCase(rhs.toString());
        }
    });

    countryList.add(0, new Country(null));

    channels.close();

    // create filter for filtering of category and country
    final ChannelFilter filter = new ChannelFilter(SettingConstants.TV_CATEGORY, null);

    // create default logo for channels without logo
    final Bitmap defaultLogo = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);

    final Set<String> firstDeletedChannels = PrefUtils.getStringSetValue(R.string.PREF_FIRST_DELETED_CHANNELS,
            new HashSet<String>());
    final Set<String> keptDeletedChannels = PrefUtils.getStringSetValue(R.string.PREF_KEPT_DELETED_CHANNELS,
            new HashSet<String>());

    final int firstDeletedColor = getResources().getColor(R.color.pref_first_deleted_channels);
    final int keptDeletedColor = getResources().getColor(R.color.pref_kept_deleted_channels);

    // Custom array adapter for channel selection
    final ArrayAdapter<ChannelSelection> channelSelectionAdapter = new ArrayAdapter<ChannelSelection>(
            TvBrowser.this, R.layout.channel_row, channelSelectionList) {
        public View getView(int position, View convertView, ViewGroup parent) {
            ChannelSelection value = getItem(position);
            ViewHolder holder = null;

            if (convertView == null) {
                LayoutInflater mInflater = (LayoutInflater) getContext()
                        .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);

                holder = new ViewHolder();

                convertView = mInflater.inflate(R.layout.channel_row, getParentViewGroup(), false);

                holder.mTextView = (TextView) convertView.findViewById(R.id.row_of_channel_text);
                holder.mCheckBox = (CheckBox) convertView.findViewById(R.id.row_of_channel_selection);
                holder.mLogo = (ImageView) convertView.findViewById(R.id.row_of_channel_icon);

                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            SpannableStringBuilder nameBuilder = new SpannableStringBuilder(value.toString());

            String channelID = String.valueOf(value.getChannelID());

            if (keptDeletedChannels.contains(channelID)) {
                nameBuilder.setSpan(new ForegroundColorSpan(keptDeletedColor), 0, value.toString().length(),
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            } else if (firstDeletedChannels.contains(channelID)) {
                nameBuilder.setSpan(new ForegroundColorSpan(firstDeletedColor), 0, value.toString().length(),
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }

            if (value.isEpgDonateChannel()) {
                nameBuilder.append("\n(EPGdonate)");
                nameBuilder.setSpan(new RelativeSizeSpan(0.65f), value.toString().length(),
                        nameBuilder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }

            holder.mTextView.setText(nameBuilder);
            holder.mCheckBox.setChecked(value.isSelected());

            Bitmap logo = value.getLogo();

            if (logo != null) {
                holder.mLogo.setImageBitmap(logo);
            } else {
                holder.mLogo.setImageBitmap(defaultLogo);
            }

            return convertView;
        }
    };

    // inflate channel selection view
    View channelSelectionView = getLayoutInflater().inflate(R.layout.dialog_channel_selection_list,
            getParentViewGroup(), false);
    channelSelectionView.findViewById(R.id.channel_selection_selection_buttons).setVisibility(View.GONE);
    channelSelectionView.findViewById(R.id.channel_selection_input_id_name).setVisibility(View.GONE);

    TextView infoView = (TextView) channelSelectionView.findViewById(R.id.channel_selection_label_id_name);

    if (help != null) {
        infoView.setText(help);
        infoView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
                getResources().getDimension(R.dimen.epg_donate_info_font_size));
    } else {
        infoView.setVisibility(View.GONE);
    }

    // get spinner for country filtering and create array adapter with all available countries
    Spinner country = (Spinner) channelSelectionView.findViewById(R.id.channel_country_value);

    final ArrayAdapter<Country> countryListAdapter = new ArrayAdapter<Country>(this,
            android.R.layout.simple_spinner_item, countryList);
    countryListAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    country.setAdapter(countryListAdapter);

    // add item selection listener to react of user setting filter for country
    country.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            Country country = countryListAdapter.getItem(position);

            filter.mCountry = country.getCountry();
            channelSelectionList.setFilter(filter);
            channelSelectionAdapter.notifyDataSetChanged();
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });

    // get spinner for category selection and add listener to react to user category selection
    Spinner category = (Spinner) channelSelectionView.findViewById(R.id.channel_category_value);
    category.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            switch (position) {
            case 1:
                filter.mCategory = SettingConstants.TV_CATEGORY;
                break;
            case 2:
                filter.mCategory = SettingConstants.RADIO_CATEGORY;
                break;
            case 3:
                filter.mCategory = SettingConstants.CINEMA_CATEGORY;
                break;

            default:
                filter.mCategory = SettingConstants.NO_CATEGORY;
                break;
            }

            channelSelectionList.setFilter(filter);
            channelSelectionAdapter.notifyDataSetChanged();
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });

    if (delete) {
        channelSelectionView.findViewById(R.id.channel_country_label).setVisibility(View.GONE);
        channelSelectionView.findViewById(R.id.channel_category_label).setVisibility(View.GONE);

        country.setVisibility(View.GONE);
        category.setVisibility(View.GONE);
    }

    // get the list view of the layout and add adapter with available channels
    ListView list = (ListView) channelSelectionView.findViewById(R.id.channel_selection_list);
    list.setAdapter(channelSelectionAdapter);

    // add listener to react to user selection of channels
    list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            CheckBox check = (CheckBox) view.findViewById(R.id.row_of_channel_selection);

            if (check != null) {
                check.setChecked(!check.isChecked());
                channelSelectionAdapter.getItem(position).setSelected(check.isChecked());
            }
        }
    });

    // show dialog only if channels are available
    if (!channelSelectionList.isEmpty()) {
        AlertDialog.Builder builder = new AlertDialog.Builder(TvBrowser.this);

        if (title == null) {
            builder.setTitle(R.string.select_channels);
        } else {
            builder.setTitle(title);
        }

        builder.setView(channelSelectionView);

        builder.setPositiveButton(android.R.string.ok, new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                boolean somethingSelected = false;
                boolean somethingChanged = false;

                Iterator<ChannelSelection> it = channelSelectionList.superIterator();

                StringBuilder deleteWhere = new StringBuilder();
                HashSet<String> keep = new HashSet<String>();

                while (it.hasNext()) {
                    ChannelSelection sel = it.next();

                    if (sel.isSelected() && !sel.wasSelected()) {
                        somethingChanged = somethingSelected = true;

                        if (delete) {
                            if (deleteWhere.length() > 0) {
                                deleteWhere.append(", ");
                            }

                            deleteWhere.append(sel.getChannelID());
                        } else {
                            ContentValues values = new ContentValues();

                            values.put(TvBrowserContentProvider.CHANNEL_KEY_SELECTION, 1);

                            getContentResolver().update(
                                    ContentUris.withAppendedId(TvBrowserContentProvider.CONTENT_URI_CHANNELS,
                                            sel.getChannelID()),
                                    values, null, null);
                        }
                    } else if (!sel.isSelected() && sel.wasSelected()) {
                        somethingChanged = true;

                        ContentValues values = new ContentValues();

                        values.put(TvBrowserContentProvider.CHANNEL_KEY_SELECTION, 0);

                        getContentResolver().update(
                                ContentUris.withAppendedId(TvBrowserContentProvider.CONTENT_URI_CHANNELS,
                                        sel.getChannelID()),
                                values, null, null);

                        getContentResolver().delete(TvBrowserContentProvider.CONTENT_URI_DATA_VERSION,
                                TvBrowserContentProvider.CHANNEL_KEY_CHANNEL_ID + "=" + sel.getChannelID(),
                                null);
                        getContentResolver().delete(TvBrowserContentProvider.CONTENT_URI_DATA,
                                TvBrowserContentProvider.CHANNEL_KEY_CHANNEL_ID + "=" + sel.getChannelID(),
                                null);
                    } else if (delete && !sel.isSelected()) {
                        keep.add(String.valueOf(sel.getChannelID()));
                    }
                }

                if (delete) {
                    if (deleteWhere.length() > 0) {
                        deleteWhere.insert(0, TvBrowserContentProvider.KEY_ID + " IN ( ");
                        deleteWhere.append(" ) ");

                        Log.d("info2", "DELETE WHERE FOR REMOVED CHANNELS " + deleteWhere.toString());

                        int count = getContentResolver().delete(TvBrowserContentProvider.CONTENT_URI_CHANNELS,
                                deleteWhere.toString(), null);

                        Log.d("info2", "REMOVED CHANNELS COUNT " + count);
                    }

                    Editor edit = PreferenceManager.getDefaultSharedPreferences(TvBrowser.this).edit();
                    edit.putStringSet(getString(R.string.PREF_KEPT_DELETED_CHANNELS), keep);
                    edit.commit();
                }

                // if something was changed we need to update channel list bar in program list and the complete program table
                if (somethingChanged) {
                    SettingConstants.initializeLogoMap(TvBrowser.this, true);
                    updateProgramListChannelBar();
                }

                // if something was selected we need to download new data
                if (somethingSelected && !delete) {
                    checkTermsAccepted();
                }
            }
        });

        builder.setNegativeButton(android.R.string.cancel, new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (delete) {
                    HashSet<String> keep = new HashSet<String>();
                    Iterator<ChannelSelection> it = channelSelectionList.superIterator();

                    while (it.hasNext()) {
                        ChannelSelection sel = it.next();

                        keep.add(String.valueOf(sel.getChannelID()));
                    }

                    Editor edit = PreferenceManager.getDefaultSharedPreferences(TvBrowser.this).edit();
                    edit.putStringSet(getString(R.string.PREF_KEPT_DELETED_CHANNELS), keep);
                    edit.commit();
                }
            }
        });

        builder.show();
    }

    selectingChannels = false;
}

From source file:org.tvbrowser.tvbrowser.TvBrowser.java

private void synchronizeDontWantToSee(final boolean replace) {
    new Thread() {
        public void run() {
            if (!SettingConstants.UPDATING_FILTER) {
                SettingConstants.UPDATING_FILTER = true;

                Context applicationContext = getApplicationContext();

                NotificationCompat.Builder builder;

                builder = new NotificationCompat.Builder(TvBrowser.this);
                builder.setSmallIcon(R.drawable.ic_stat_notify);
                builder.setOngoing(true);
                builder.setContentTitle(getResources().getText(R.string.action_dont_want_to_see));
                builder.setContentText(getResources().getText(R.string.dont_want_to_see_notification_text));

                int notifyID = 2;

                NotificationManager notification = (NotificationManager) getSystemService(
                        Context.NOTIFICATION_SERVICE);
                notification.notify(notifyID, builder.build());

                updateProgressIcon(true);

                URL documentUrl;//from w ww .  java  2s. co  m

                try {
                    documentUrl = new URL(
                            "http://android.tvbrowser.org/data/scripts/syncDown.php?type=dontWantToSee");
                    URLConnection connection = documentUrl.openConnection();

                    SharedPreferences pref = getSharedPreferences("transportation", Context.MODE_PRIVATE);

                    String car = pref.getString(SettingConstants.USER_NAME, null);
                    String bicycle = pref.getString(SettingConstants.USER_PASSWORD, null);

                    if (car != null && bicycle != null) {
                        String userpass = car + ":" + bicycle;
                        String basicAuth = "basic "
                                + Base64.encodeToString(userpass.getBytes(), Base64.NO_WRAP);

                        connection.setRequestProperty("Authorization", basicAuth);

                        BufferedReader read = new BufferedReader(new InputStreamReader(
                                new GZIPInputStream(connection.getInputStream()), "UTF-8"));

                        String line = null;

                        StringBuilder exclusionBuilder = new StringBuilder();
                        HashSet<String> exclusions = new HashSet<String>();
                        ArrayList<DontWantToSeeExclusion> exclusionList = new ArrayList<DontWantToSeeExclusion>();

                        while ((line = read.readLine()) != null) {
                            if (line.contains(";;") && line.trim().length() > 0) {
                                exclusions.add(line);
                                exclusionList.add(new DontWantToSeeExclusion(line));
                                exclusionBuilder.append(line).append("\n");
                            }
                        }

                        String key = getString(R.string.I_DONT_WANT_TO_SEE_ENTRIES);
                        SharedPreferences pref1 = PreferenceManager.getDefaultSharedPreferences(TvBrowser.this);

                        Set<String> oldValues = pref1.getStringSet(key, null);

                        if (exclusions.size() > 0) {
                            if (!replace && oldValues != null) {
                                for (String old : oldValues) {
                                    if (!exclusions.contains(old)) {
                                        exclusions.add(old);
                                        exclusionList.add(new DontWantToSeeExclusion(old));
                                        exclusionBuilder.append(old).append("\n");
                                    }
                                }
                            }

                            Editor edit = pref1.edit();

                            edit.putStringSet(key, exclusions);
                            edit.commit();

                            DontWantToSeeExclusion[] exclusionArr = exclusionList
                                    .toArray(new DontWantToSeeExclusion[exclusionList.size()]);

                            Cursor c = getContentResolver().query(TvBrowserContentProvider.CONTENT_URI_DATA,
                                    new String[] { TvBrowserContentProvider.KEY_ID,
                                            TvBrowserContentProvider.DATA_KEY_TITLE },
                                    null, null, TvBrowserContentProvider.KEY_ID);
                            c.moveToPosition(-1);

                            builder.setProgress(c.getCount(), 0, true);
                            notification.notify(notifyID, builder.build());

                            ArrayList<ContentProviderOperation> updateValuesList = new ArrayList<ContentProviderOperation>();

                            int keyColumn = c.getColumnIndex(TvBrowserContentProvider.KEY_ID);
                            int titleColumn = c.getColumnIndex(TvBrowserContentProvider.DATA_KEY_TITLE);

                            while (c.moveToNext()) {
                                builder.setProgress(c.getCount(), c.getPosition(), false);
                                notification.notify(notifyID, builder.build());

                                String title = c.getString(titleColumn);

                                boolean filter = UiUtils.filter(getApplicationContext(), title, exclusionArr);
                                long progID = c.getLong(keyColumn);

                                ContentValues values = new ContentValues();
                                values.put(TvBrowserContentProvider.DATA_KEY_DONT_WANT_TO_SEE, filter ? 1 : 0);

                                ContentProviderOperation.Builder opBuilder = ContentProviderOperation
                                        .newUpdate(ContentUris.withAppendedId(
                                                TvBrowserContentProvider.CONTENT_URI_DATA_UPDATE, progID));
                                opBuilder.withValues(values);

                                updateValuesList.add(opBuilder.build());
                            }

                            c.close();

                            if (!updateValuesList.isEmpty()) {
                                try {
                                    getContentResolver().applyBatch(TvBrowserContentProvider.AUTHORITY,
                                            updateValuesList);
                                    UiUtils.sendDontWantToSeeChangedBroadcast(applicationContext, true);
                                    handler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(getApplicationContext(),
                                                    R.string.dont_want_to_see_sync_success, Toast.LENGTH_LONG)
                                                    .show();
                                        }
                                    });
                                } catch (RemoteException e) {
                                    e.printStackTrace();
                                } catch (OperationApplicationException e) {
                                    e.printStackTrace();
                                }
                            }

                            if (!replace && exclusionBuilder.length() > 0) {
                                startSynchronizeUp(false, exclusionBuilder.toString(),
                                        "http://android.tvbrowser.org/data/scripts/syncUp.php?type=dontWantToSee",
                                        null, null);
                            }
                        } else {
                            if (!replace && oldValues != null && !oldValues.isEmpty()) {
                                for (String old : oldValues) {
                                    exclusionBuilder.append(old).append("\n");
                                }

                                startSynchronizeUp(false, exclusionBuilder.toString(),
                                        "http://android.tvbrowser.org/data/scripts/syncUp.php?type=dontWantToSee",
                                        null, null);
                            }

                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(getApplicationContext(), R.string.no_dont_want_to_see_sync,
                                            Toast.LENGTH_LONG).show();
                                }
                            });
                        }
                    }
                } catch (Throwable t) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(), R.string.no_dont_want_to_see_sync,
                                    Toast.LENGTH_LONG).show();
                        }
                    });
                }

                notification.cancel(notifyID);
                updateProgressIcon(false);

                SettingConstants.UPDATING_FILTER = false;
            }
        }
    }.start();
}