Example usage for android.database Cursor getBlob

List of usage examples for android.database Cursor getBlob

Introduction

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

Prototype

byte[] getBlob(int columnIndex);

Source Link

Document

Returns the value of the requested column as a byte array.

Usage

From source file:com.aware.utils.WebserviceHelper.java

@Override
protected void onHandleIntent(Intent intent) {

    WEBSERVER = Aware.getSetting(getApplicationContext(), Aware_Preferences.WEBSERVICE_SERVER);
    DEVICE_ID = Aware.getSetting(getApplicationContext(), Aware_Preferences.DEVICE_ID);
    DEBUG = Aware.getSetting(getApplicationContext(), Aware_Preferences.DEBUG_FLAG).equals("true");
    DATABASE_TABLE = intent.getStringExtra(EXTRA_TABLE);
    TABLES_FIELDS = intent.getStringExtra(EXTRA_FIELDS);
    CONTENT_URI = Uri.parse(intent.getStringExtra(EXTRA_CONTENT_URI));

    //Fixed: not using webservices
    if (WEBSERVER.length() == 0)
        return;/* w w w . j  a  v  a  2  s.  c o  m*/

    if (intent.getAction().equals(ACTION_AWARE_WEBSERVICE_SYNC_TABLE)) {

        //Check if we should do this only over Wi-Fi
        boolean wifi_only = Aware.getSetting(getApplicationContext(), Aware_Preferences.WEBSERVICE_WIFI_ONLY)
                .equals("true");
        if (wifi_only) {
            ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo active_network = cm.getActiveNetworkInfo();
            if (active_network != null && active_network.getType() != ConnectivityManager.TYPE_WIFI) {
                if (DEBUG) {
                    Log.i("AWARE", "User not connected to Wi-Fi, skipping data sync.");
                }
                return;
            }
        }

        //Check first if we have database table remotely, otherwise create it!
        ArrayList<NameValuePair> fields = new ArrayList<NameValuePair>();
        fields.add(new BasicNameValuePair(Aware_Preferences.DEVICE_ID, DEVICE_ID));
        fields.add(new BasicNameValuePair(EXTRA_FIELDS, TABLES_FIELDS));

        //Create table if doesn't exist on the remote webservice server
        HttpResponse response = new Https(getApplicationContext())
                .dataPOST(WEBSERVER + "/" + DATABASE_TABLE + "/create_table", fields);
        if (response != null && response.getStatusLine().getStatusCode() == 200) {
            if (DEBUG) {
                HttpResponse copy = response;
                try {
                    if (DEBUG)
                        Log.d(Aware.TAG, EntityUtils.toString(copy.getEntity()));
                } catch (ParseException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            String[] columnsStr = new String[] {};
            Cursor columnsDB = getContentResolver().query(CONTENT_URI, null, null, null, null);
            if (columnsDB != null && columnsDB.moveToFirst()) {
                columnsStr = columnsDB.getColumnNames();
                if (DEBUG)
                    Log.d(Aware.TAG, "Total records on " + DATABASE_TABLE + ": " + columnsDB.getCount());
            }
            if (columnsDB != null && !columnsDB.isClosed())
                columnsDB.close();

            try {
                ArrayList<NameValuePair> request = new ArrayList<NameValuePair>();
                request.add(new BasicNameValuePair(Aware_Preferences.DEVICE_ID, DEVICE_ID));

                //check the latest entry in remote database
                HttpResponse latest = new Https(getApplicationContext())
                        .dataPOST(WEBSERVER + "/" + DATABASE_TABLE + "/latest", request);
                if (latest == null)
                    return;

                String data = "[]";
                try {
                    data = EntityUtils.toString(latest.getEntity());
                } catch (IllegalStateException e) {
                    Log.d(Aware.TAG, "Unable to connect to webservices...");
                }

                if (DEBUG) {
                    Log.d(Aware.TAG, "Webservice response: " + data);
                }

                //If in a study, get from joined date onwards
                String study_condition = "";
                if (Aware.getSetting(getApplicationContext(), "study_id").length() > 0
                        && Aware.getSetting(getApplicationContext(), "study_start").length() > 0) {
                    String study_start = Aware.getSetting(getApplicationContext(), "study_start");
                    study_condition = " AND timestamp > " + Long.parseLong(study_start);
                }
                if (DATABASE_TABLE.equalsIgnoreCase("aware_device"))
                    study_condition = "";

                JSONArray remoteData = new JSONArray(data);

                Cursor context_data;
                if (remoteData.length() == 0) {
                    if (exists(columnsStr, "double_end_timestamp")) {
                        context_data = getContentResolver().query(CONTENT_URI, null,
                                "double_end_timestamp != 0" + study_condition, null, "timestamp ASC");
                    } else if (exists(columnsStr, "double_esm_user_answer_timestamp")) {
                        context_data = getContentResolver().query(CONTENT_URI, null,
                                "double_esm_user_answer_timestamp != 0" + study_condition, null,
                                "timestamp ASC");
                    } else {
                        context_data = getContentResolver().query(CONTENT_URI, null, "1" + study_condition,
                                null, "timestamp ASC");
                    }
                } else {
                    long last = 0;
                    if (exists(columnsStr, "double_end_timestamp")) {
                        last = remoteData.getJSONObject(0).getLong("double_end_timestamp");
                        context_data = getContentResolver().query(CONTENT_URI, null,
                                "timestamp > " + last + " AND double_end_timestamp != 0" + study_condition,
                                null, "timestamp ASC");
                    } else if (exists(columnsStr, "double_esm_user_answer_timestamp")) {
                        last = remoteData.getJSONObject(0).getLong("double_esm_user_answer_timestamp");
                        context_data = getContentResolver().query(
                                CONTENT_URI, null, "timestamp > " + last
                                        + " AND double_esm_user_answer_timestamp != 0" + study_condition,
                                null, "timestamp ASC");
                    } else {
                        last = remoteData.getJSONObject(0).getLong("timestamp");
                        context_data = getContentResolver().query(CONTENT_URI, null,
                                "timestamp > " + last + study_condition, null, "timestamp ASC");
                    }
                }

                JSONArray context_data_entries = new JSONArray();
                if (context_data != null && context_data.moveToFirst()) {
                    if (DEBUG)
                        Log.d(Aware.TAG, "Uploading " + context_data.getCount() + " from " + DATABASE_TABLE);

                    do {
                        JSONObject entry = new JSONObject();

                        String[] columns = context_data.getColumnNames();
                        for (String c_name : columns) {

                            //Skip local database ID
                            if (c_name.equals("_id"))
                                continue;

                            if (c_name.equals("timestamp") || c_name.contains("double")) {
                                entry.put(c_name, context_data.getDouble(context_data.getColumnIndex(c_name)));
                            } else if (c_name.contains("float")) {
                                entry.put(c_name, context_data.getFloat(context_data.getColumnIndex(c_name)));
                            } else if (c_name.contains("long")) {
                                entry.put(c_name, context_data.getLong(context_data.getColumnIndex(c_name)));
                            } else if (c_name.contains("blob")) {
                                entry.put(c_name, context_data.getBlob(context_data.getColumnIndex(c_name)));
                            } else if (c_name.contains("integer")) {
                                entry.put(c_name, context_data.getInt(context_data.getColumnIndex(c_name)));
                            } else {
                                entry.put(c_name, context_data.getString(context_data.getColumnIndex(c_name)));
                            }
                        }
                        context_data_entries.put(entry);

                        if (context_data_entries.length() == 1000) {
                            request = new ArrayList<NameValuePair>();
                            request.add(new BasicNameValuePair(Aware_Preferences.DEVICE_ID, DEVICE_ID));
                            request.add(new BasicNameValuePair("data", context_data_entries.toString()));
                            new Https(getApplicationContext())
                                    .dataPOST(WEBSERVER + "/" + DATABASE_TABLE + "/insert", request);

                            context_data_entries = new JSONArray();
                        }
                    } while (context_data.moveToNext());

                    if (context_data_entries.length() > 0) {
                        request = new ArrayList<NameValuePair>();
                        request.add(new BasicNameValuePair(Aware_Preferences.DEVICE_ID, DEVICE_ID));
                        request.add(new BasicNameValuePair("data", context_data_entries.toString()));
                        new Https(getApplicationContext())
                                .dataPOST(WEBSERVER + "/" + DATABASE_TABLE + "/insert", request);
                    }
                } else {
                    if (DEBUG)
                        Log.d(Aware.TAG,
                                "Nothing new in " + DATABASE_TABLE + "!" + " URI=" + CONTENT_URI.toString());
                }

                if (context_data != null && !context_data.isClosed())
                    context_data.close();

            } catch (ParseException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //Clear database table remotely
    if (intent.getAction().equals(ACTION_AWARE_WEBSERVICE_CLEAR_TABLE)) {
        ArrayList<NameValuePair> request = new ArrayList<NameValuePair>();
        request.add(new BasicNameValuePair(Aware_Preferences.DEVICE_ID, DEVICE_ID));
        new Https(getApplicationContext()).dataPOST(WEBSERVER + "/" + DATABASE_TABLE + "/clear_table", request);
    }
}

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  ww  w . ja  va  2  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:com.mozilla.SUTAgentAndroid.service.DoCommand.java

public String Pull(String fileName, long lOffset, long lLength, OutputStream out) {
    String sTmpFileName = fixFileName(fileName);
    String sRet = sErrorPrefix + "Could not read the file " + sTmpFileName;
    byte[] buffer = new byte[4096];
    int nRead = 0;
    long lSent = 0;

    if (sTmpFileName.contains("org.mozilla.fennec") || sTmpFileName.contains("org.mozilla.firefox")) {
        ContentResolver cr = contextWrapper.getContentResolver();
        Uri ffxFiles = null;/*  www  . ja v a2  s .c o m*/

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

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

        String[] args = new String[2];
        args[0] = Long.toString(lOffset);
        args[1] = Long.toString(lLength);

        Cursor myCursor = cr.query(ffxFiles, columns, // Which columns to return
                sTmpFileName, // Which rows to return (all rows)
                args, // Selection arguments (none)
                null); // Order clause (none)
        if (myCursor != null) {
            int nRows = myCursor.getCount();
            long lFileLength = 0;

            for (int lcv = 0; lcv < nRows; lcv++) {
                if (myCursor.moveToPosition(lcv)) {
                    if (lcv == 0) {
                        lFileLength = myCursor.getLong(2);
                        String sTmp = sTmpFileName + "," + lFileLength + "\n";
                        try {
                            out.write(sTmp.getBytes());
                        } catch (IOException e) {
                            e.printStackTrace();
                            break;
                        }
                    }

                    if (lLength != 0) {
                        byte[] buf = myCursor.getBlob(1);
                        if (buf != null) {
                            nRead = buf.length;
                            try {
                                if ((lSent + nRead) <= lFileLength) {
                                    out.write(buf, 0, nRead);
                                    lSent += nRead;
                                } else {
                                    nRead = (int) (lFileLength - lSent);
                                    out.write(buf, 0, nRead);
                                    Log.d("pull warning", "more bytes read than expected");
                                    break;
                                }
                            } catch (IOException e) {
                                e.printStackTrace();
                                sRet = sErrorPrefix + "Could not write to out " + sTmpFileName;
                            }
                            buf = null;
                        }
                    }
                }
            }
            if (nRows == 0) {
                String sTmp = sTmpFileName + "," + lFileLength + "\n";
                try {
                    out.write(sTmp.getBytes());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (nRows == -1) {
                sRet = sErrorPrefix + sTmpFileName + ",-1\nNo such file or directory";
            } else {
                myCursor.close();
                sRet = "";
            }
        } else {
            sRet = sErrorPrefix + sTmpFileName + ",-1\nUnable to access file (internal error)";
        }
    } else {
        try {
            File f = new File(sTmpFileName);
            long lFileLength = f.length();
            FileInputStream fin = new FileInputStream(f);
            if (lFileLength == 0) {
                while ((nRead = fin.read(buffer)) != -1) {
                    lFileLength += nRead;
                }
                fin.close();
                fin = new FileInputStream(f);
            }

            // lLength == -1 return everything between lOffset and eof
            // lLength == 0 return file length
            // lLength > 0 return lLength bytes
            if (lLength == -1) {
                lFileLength = lFileLength - lOffset;
            } else if (lLength == 0) {
                // just return the file length
            } else {
                lFileLength = ((lLength <= (lFileLength - lOffset)) ? lLength : (lFileLength - lOffset));
            }

            String sTmp = sTmpFileName + "," + lFileLength + "\n";
            out.write(sTmp.getBytes());
            if (lLength != 0) {
                if (lOffset > 0) {
                    fin.skip(lOffset);
                }
                while ((nRead = fin.read(buffer)) != -1) {
                    if ((lSent + nRead) <= lFileLength) {
                        out.write(buffer, 0, nRead);
                        lSent += nRead;
                    } else {
                        nRead = (int) (lFileLength - lSent);
                        out.write(buffer, 0, nRead);
                        if (lLength != -1)
                            Log.d("pull warning", "more bytes read than sent");
                        break;
                    }
                }
            }
            fin.close();
            out.flush();
            sRet = "";
        } catch (FileNotFoundException e) {
            sRet = sErrorPrefix + sTmpFileName + ",-1\nNo such file or directory";
        } catch (IOException e) {
            sRet = e.toString();
        }
    }
    return (sRet);
}

From source file:com.piusvelte.sonet.core.SonetService.java

private void buildWidgetButtons(Integer appWidgetId, boolean updatesReady, int page, boolean hasbuttons,
        int scrollable, int buttons_bg_color, int buttons_color, int buttons_textsize, boolean display_profile,
        int margin) {
    final String widget = Integer.toString(appWidgetId);
    // Push update for this widget to the home screen
    int layout;/*from ww  w  . jav  a 2  s  .  com*/
    if (hasbuttons) {
        if (sNativeScrollingSupported) {
            if (margin > 0)
                layout = R.layout.widget_margin_scrollable;
            else
                layout = R.layout.widget_scrollable;
        } else if (display_profile) {
            if (margin > 0)
                layout = R.layout.widget_margin;
            else
                layout = R.layout.widget;
        } else {
            if (margin > 0)
                layout = R.layout.widget_noprofile_margin;
            else
                layout = R.layout.widget_noprofile;
        }
    } else {
        if (sNativeScrollingSupported) {
            if (margin > 0)
                layout = R.layout.widget_nobuttons_margin_scrollable;
            else
                layout = R.layout.widget_nobuttons_scrollable;
        } else if (display_profile) {
            if (margin > 0)
                layout = R.layout.widget_nobuttons_margin;
            else
                layout = R.layout.widget_nobuttons;
        } else {
            if (margin > 0)
                layout = R.layout.widget_nobuttons_noprofile_margin;
            else
                layout = R.layout.widget_nobuttons_noprofile;
        }
    }
    // wrap RemoteViews for backward compatibility
    RemoteViews views = new RemoteViews(getPackageName(), layout);
    if (hasbuttons) {
        Bitmap buttons_bg = Bitmap.createBitmap(1, 1, Config.ARGB_8888);
        Canvas buttons_bg_canvas = new Canvas(buttons_bg);
        buttons_bg_canvas.drawColor(buttons_bg_color);
        views.setImageViewBitmap(R.id.buttons_bg, buttons_bg);
        views.setTextColor(R.id.buttons_bg_clear, buttons_bg_color);
        views.setFloat(R.id.buttons_bg_clear, "setTextSize", buttons_textsize);
        views.setOnClickPendingIntent(R.id.button_post, PendingIntent.getActivity(SonetService.this, 0,
                Sonet.getPackageIntent(SonetService.this, SonetCreatePost.class)
                        .setAction(LauncherIntent.Action.ACTION_VIEW_CLICK)
                        .setData(Uri.withAppendedPath(Widgets.getContentUri(SonetService.this), widget)),
                0));
        views.setTextColor(R.id.button_post, buttons_color);
        views.setFloat(R.id.button_post, "setTextSize", buttons_textsize);
        views.setOnClickPendingIntent(R.id.button_configure, PendingIntent.getActivity(SonetService.this, 0,
                Sonet.getPackageIntent(SonetService.this, ManageAccounts.class).setAction(widget), 0));
        views.setTextColor(R.id.button_configure, buttons_color);
        views.setFloat(R.id.button_configure, "setTextSize", buttons_textsize);
        views.setOnClickPendingIntent(R.id.button_refresh, PendingIntent.getService(SonetService.this, 0,
                Sonet.getPackageIntent(SonetService.this, SonetService.class).setAction(widget), 0));
        views.setTextColor(R.id.button_refresh, buttons_color);
        views.setFloat(R.id.button_refresh, "setTextSize", buttons_textsize);
        views.setTextColor(R.id.page_up, buttons_color);
        views.setFloat(R.id.page_up, "setTextSize", buttons_textsize);
        views.setTextColor(R.id.page_down, buttons_color);
        views.setFloat(R.id.page_down, "setTextSize", buttons_textsize);
    }
    // set margin
    if (scrollable == 0) {
        final AppWidgetManager mgr = AppWidgetManager.getInstance(SonetService.this);
        // check if native scrolling is supported
        if (sNativeScrollingSupported) {
            // native scrolling
            try {
                final Intent intent = SonetRemoteViewsServiceWrapper.getRemoteAdapterIntent(SonetService.this);
                if (intent != null) {
                    intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
                    intent.putExtra(Widgets.DISPLAY_PROFILE, display_profile);
                    intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)));
                    sSetRemoteAdapter.invoke(views, appWidgetId, R.id.messages, intent);
                    // empty
                    sSetEmptyView.invoke(views, R.id.messages, R.id.empty_messages);
                    // onclick
                    // Bind a click listener template for the contents of the message list
                    final Intent onClickIntent = Sonet.getPackageIntent(SonetService.this, SonetWidget.class);
                    onClickIntent.setAction(ACTION_ON_CLICK);
                    onClickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
                    onClickIntent.setData(Uri.parse(onClickIntent.toUri(Intent.URI_INTENT_SCHEME)));
                    final PendingIntent onClickPendingIntent = PendingIntent.getBroadcast(SonetService.this, 0,
                            onClickIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                    sSetPendingIntentTemplate.invoke(views, R.id.messages, onClickPendingIntent);
                } else {
                    // fallback on non-scrolling widget
                    sNativeScrollingSupported = false;
                }
            } catch (NumberFormatException e) {
                Log.e(TAG, e.toString());
            } catch (IllegalArgumentException e) {
                Log.e(TAG, e.toString());
            } catch (IllegalAccessException e) {
                Log.e(TAG, e.toString());
            } catch (InvocationTargetException e) {
                Log.e(TAG, e.toString());
            }

        }
        if (!sNativeScrollingSupported) {
            Cursor statuses_styles = getContentResolver().query(
                    Uri.withAppendedPath(Statuses_styles.getContentUri(SonetService.this), widget),
                    new String[] { Statuses_styles._ID, Statuses_styles.FRIEND, Statuses_styles.PROFILE,
                            Statuses_styles.MESSAGE, Statuses_styles.CREATEDTEXT,
                            Statuses_styles.MESSAGES_COLOR, Statuses_styles.FRIEND_COLOR,
                            Statuses_styles.CREATED_COLOR, Statuses_styles.MESSAGES_TEXTSIZE,
                            Statuses_styles.FRIEND_TEXTSIZE, Statuses_styles.CREATED_TEXTSIZE,
                            Statuses_styles.STATUS_BG, Statuses_styles.ICON, Statuses_styles.PROFILE_BG,
                            Statuses_styles.FRIEND_BG, Statuses_styles.IMAGE_BG, Statuses_styles.IMAGE },
                    null, null, Statuses_styles.CREATED + " DESC LIMIT " + page + ",-1");
            if (statuses_styles.moveToFirst()) {
                int count_status = 0;
                views.removeAllViews(R.id.messages);
                while (!statuses_styles.isAfterLast() && (count_status < 16)) {
                    int friend_color = statuses_styles.getInt(6), created_color = statuses_styles.getInt(7),
                            friend_textsize = statuses_styles.getInt(9),
                            created_textsize = statuses_styles.getInt(10),
                            messages_color = statuses_styles.getInt(5),
                            messages_textsize = statuses_styles.getInt(8);
                    // get the item wrapper
                    RemoteViews itemView;
                    if (display_profile) {
                        itemView = new RemoteViews(getPackageName(), R.layout.widget_item);
                        // set profiles background
                        byte[] profile_bg = statuses_styles.getBlob(13);
                        if (profile_bg != null) {
                            Bitmap profile_bgbmp = BitmapFactory.decodeByteArray(profile_bg, 0,
                                    profile_bg.length, sBFOptions);
                            if (profile_bgbmp != null)
                                itemView.setImageViewBitmap(R.id.profile_bg, profile_bgbmp);
                        }
                        byte[] profile = statuses_styles.getBlob(2);
                        if (profile != null) {
                            Bitmap profilebmp = BitmapFactory.decodeByteArray(profile, 0, profile.length,
                                    sBFOptions);
                            if (profilebmp != null)
                                itemView.setImageViewBitmap(R.id.profile, profilebmp);
                        }
                    } else
                        itemView = new RemoteViews(getPackageName(), R.layout.widget_item_noprofile);
                    itemView.setTextViewText(R.id.friend_bg_clear, statuses_styles.getString(1));
                    itemView.setFloat(R.id.friend_bg_clear, "setTextSize", friend_textsize);
                    itemView.setTextViewText(R.id.message_bg_clear, statuses_styles.getString(3));
                    itemView.setFloat(R.id.message_bg_clear, "setTextSize", messages_textsize);
                    // set friends background
                    byte[] friend_bg = statuses_styles.getBlob(14);
                    if (friend_bg != null) {
                        Bitmap friend_bgbmp = BitmapFactory.decodeByteArray(friend_bg, 0, friend_bg.length,
                                sBFOptions);
                        if (friend_bgbmp != null)
                            itemView.setImageViewBitmap(R.id.friend_bg, friend_bgbmp);
                    }
                    // set messages background
                    byte[] status_bg = statuses_styles.getBlob(11);
                    if (status_bg != null) {
                        Bitmap status_bgbmp = BitmapFactory.decodeByteArray(status_bg, 0, status_bg.length,
                                sBFOptions);
                        if (status_bgbmp != null)
                            itemView.setImageViewBitmap(R.id.status_bg, status_bgbmp);
                    }
                    // set an image
                    byte[] image_bg = statuses_styles.getBlob(15);
                    byte[] image = statuses_styles.getBlob(16);
                    if ((image_bg != null) && (image != null)) {
                        Bitmap image_bgBmp = BitmapFactory.decodeByteArray(image_bg, 0, image_bg.length,
                                sBFOptions);
                        if (image_bgBmp != null) {
                            Bitmap imageBmp = BitmapFactory.decodeByteArray(image, 0, image.length, sBFOptions);
                            itemView.setImageViewBitmap(R.id.image_clear, image_bgBmp);
                            itemView.setImageViewBitmap(R.id.image, imageBmp);
                        }
                    }
                    itemView.setTextViewText(R.id.message, statuses_styles.getString(3));
                    itemView.setTextColor(R.id.message, messages_color);
                    itemView.setFloat(R.id.message, "setTextSize", messages_textsize);
                    itemView.setOnClickPendingIntent(R.id.item,
                            PendingIntent.getActivity(SonetService.this, 0,
                                    Sonet.getPackageIntent(SonetService.this, StatusDialog.class)
                                            .setData(Uri.withAppendedPath(
                                                    Statuses_styles.getContentUri(SonetService.this),
                                                    Long.toString(statuses_styles.getLong(0)))),
                                    0));
                    itemView.setTextViewText(R.id.friend, statuses_styles.getString(1));
                    itemView.setTextColor(R.id.friend, friend_color);
                    itemView.setFloat(R.id.friend, "setTextSize", friend_textsize);
                    itemView.setTextViewText(R.id.created, statuses_styles.getString(4));
                    itemView.setTextColor(R.id.created, created_color);
                    itemView.setFloat(R.id.created, "setTextSize", created_textsize);
                    // set icons
                    byte[] icon = statuses_styles.getBlob(12);
                    if (icon != null) {
                        Bitmap iconbmp = BitmapFactory.decodeByteArray(icon, 0, icon.length, sBFOptions);
                        if (iconbmp != null)
                            itemView.setImageViewBitmap(R.id.icon, iconbmp);
                    }
                    views.addView(R.id.messages, itemView);
                    count_status++;
                    statuses_styles.moveToNext();
                }
                if (hasbuttons && (page < statuses_styles.getCount())) {
                    // there are more statuses to show, allow paging down
                    views.setOnClickPendingIntent(R.id.page_down, PendingIntent.getService(SonetService.this, 0,
                            Sonet.getPackageIntent(SonetService.this, SonetService.class)
                                    .setAction(ACTION_PAGE_DOWN)
                                    .setData(Uri.withAppendedPath(Widgets.getContentUri(SonetService.this),
                                            widget))
                                    .putExtra(ACTION_PAGE_DOWN, page + 1),
                            PendingIntent.FLAG_UPDATE_CURRENT));
                }
            }
            statuses_styles.close();
            if (hasbuttons && (page > 0))
                views.setOnClickPendingIntent(R.id.page_up, PendingIntent.getService(SonetService.this, 0,
                        Sonet.getPackageIntent(SonetService.this, SonetService.class).setAction(ACTION_PAGE_UP)
                                .setData(Uri.withAppendedPath(Widgets.getContentUri(SonetService.this), widget))
                                .putExtra(ACTION_PAGE_UP, page - 1),
                        PendingIntent.FLAG_UPDATE_CURRENT));
        }
        Log.d(TAG, "update native widget: " + appWidgetId);
        mgr.updateAppWidget(appWidgetId, views);
        if (sNativeScrollingSupported) {
            Log.d(TAG, "trigger widget query: " + appWidgetId);
            try {
                // trigger query
                sNotifyAppWidgetViewDataChanged.invoke(mgr, appWidgetId, R.id.messages);
            } catch (NumberFormatException e) {
                Log.e(TAG, e.toString());
            } catch (IllegalArgumentException e) {
                Log.e(TAG, e.toString());
            } catch (IllegalAccessException e) {
                Log.e(TAG, e.toString());
            } catch (InvocationTargetException e) {
                Log.e(TAG, e.toString());
            }
        }
    } else if (updatesReady) {
        //         Log.d(TAG, "notify updatesReady");
        getContentResolver().notifyChange(Statuses_styles.getContentUri(SonetService.this), null);
    } else {
        AppWidgetManager.getInstance(SonetService.this).updateAppWidget(Integer.parseInt(widget), views);
        buildScrollableWidget(appWidgetId, scrollable, display_profile);
    }
}

From source file:com.shafiq.myfeedle.core.MyfeedleService.java

private void buildWidgetButtons(Integer appWidgetId, boolean updatesReady, int page, boolean hasbuttons,
        int scrollable, int buttons_bg_color, int buttons_color, int buttons_textsize, boolean display_profile,
        int margin) {
    final String widget = Integer.toString(appWidgetId);
    // Push update for this widget to the home screen
    int layout;/* ww w  .ja  v  a2 s  . c om*/
    if (hasbuttons) {
        if (sNativeScrollingSupported) {
            if (margin > 0)
                layout = R.layout.widget_margin_scrollable;
            else
                layout = R.layout.widget_scrollable;
        } else if (display_profile) {
            if (margin > 0)
                layout = R.layout.widget_margin;
            else
                layout = R.layout.widget;
        } else {
            if (margin > 0)
                layout = R.layout.widget_noprofile_margin;
            else
                layout = R.layout.widget_noprofile;
        }
    } else {
        if (sNativeScrollingSupported) {
            if (margin > 0)
                layout = R.layout.widget_nobuttons_margin_scrollable;
            else
                layout = R.layout.widget_nobuttons_scrollable;
        } else if (display_profile) {
            if (margin > 0)
                layout = R.layout.widget_nobuttons_margin;
            else
                layout = R.layout.widget_nobuttons;
        } else {
            if (margin > 0)
                layout = R.layout.widget_nobuttons_noprofile_margin;
            else
                layout = R.layout.widget_nobuttons_noprofile;
        }
    }
    // wrap RemoteViews for backward compatibility
    RemoteViews views = new RemoteViews(getPackageName(), layout);
    if (hasbuttons) {
        Bitmap buttons_bg = Bitmap.createBitmap(1, 1, Config.ARGB_8888);
        Canvas buttons_bg_canvas = new Canvas(buttons_bg);
        buttons_bg_canvas.drawColor(buttons_bg_color);
        views.setImageViewBitmap(R.id.buttons_bg, buttons_bg);
        views.setTextColor(R.id.buttons_bg_clear, buttons_bg_color);
        views.setFloat(R.id.buttons_bg_clear, "setTextSize", buttons_textsize);
        views.setOnClickPendingIntent(R.id.button_post,
                PendingIntent.getActivity(MyfeedleService.this, 0,
                        Myfeedle.getPackageIntent(MyfeedleService.this, MyfeedleCreatePost.class)
                                .setAction(LauncherIntent.Action.ACTION_VIEW_CLICK).setData(Uri
                                        .withAppendedPath(Widgets.getContentUri(MyfeedleService.this), widget)),
                        0));
        views.setTextColor(R.id.button_post, buttons_color);
        views.setFloat(R.id.button_post, "setTextSize", buttons_textsize);
        views.setOnClickPendingIntent(R.id.button_configure, PendingIntent.getActivity(MyfeedleService.this, 0,
                Myfeedle.getPackageIntent(MyfeedleService.this, ManageAccounts.class).setAction(widget), 0));
        views.setTextColor(R.id.button_configure, buttons_color);
        views.setFloat(R.id.button_configure, "setTextSize", buttons_textsize);
        views.setOnClickPendingIntent(R.id.button_refresh, PendingIntent.getService(MyfeedleService.this, 0,
                Myfeedle.getPackageIntent(MyfeedleService.this, MyfeedleService.class).setAction(widget), 0));
        views.setTextColor(R.id.button_refresh, buttons_color);
        views.setFloat(R.id.button_refresh, "setTextSize", buttons_textsize);
        views.setTextColor(R.id.page_up, buttons_color);
        views.setFloat(R.id.page_up, "setTextSize", buttons_textsize);
        views.setTextColor(R.id.page_down, buttons_color);
        views.setFloat(R.id.page_down, "setTextSize", buttons_textsize);
    }
    // set margin
    if (scrollable == 0) {
        final AppWidgetManager mgr = AppWidgetManager.getInstance(MyfeedleService.this);
        // check if native scrolling is supported
        if (sNativeScrollingSupported) {
            // native scrolling
            try {
                final Intent intent = MyfeedleRemoteViewsServiceWrapper
                        .getRemoteAdapterIntent(MyfeedleService.this);
                if (intent != null) {
                    intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
                    intent.putExtra(Widgets.DISPLAY_PROFILE, display_profile);
                    intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)));
                    sSetRemoteAdapter.invoke(views, appWidgetId, R.id.messages, intent);
                    // empty
                    sSetEmptyView.invoke(views, R.id.messages, R.id.empty_messages);
                    // onclick
                    // Bind a click listener template for the contents of the message list
                    final Intent onClickIntent = Myfeedle.getPackageIntent(MyfeedleService.this,
                            MyfeedleWidget.class);
                    onClickIntent.setAction(ACTION_ON_CLICK);
                    onClickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
                    onClickIntent.setData(Uri.parse(onClickIntent.toUri(Intent.URI_INTENT_SCHEME)));
                    final PendingIntent onClickPendingIntent = PendingIntent.getBroadcast(MyfeedleService.this,
                            0, onClickIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                    sSetPendingIntentTemplate.invoke(views, R.id.messages, onClickPendingIntent);
                } else {
                    // fallback on non-scrolling widget
                    sNativeScrollingSupported = false;
                }
            } catch (NumberFormatException e) {
                Log.e(TAG, e.toString());
            } catch (IllegalArgumentException e) {
                Log.e(TAG, e.toString());
            } catch (IllegalAccessException e) {
                Log.e(TAG, e.toString());
            } catch (InvocationTargetException e) {
                Log.e(TAG, e.toString());
            }

        }
        if (!sNativeScrollingSupported) {
            Cursor statuses_styles = getContentResolver().query(
                    Uri.withAppendedPath(Statuses_styles.getContentUri(MyfeedleService.this), widget),
                    new String[] { Statuses_styles._ID, Statuses_styles.FRIEND, Statuses_styles.PROFILE,
                            Statuses_styles.MESSAGE, Statuses_styles.CREATEDTEXT,
                            Statuses_styles.MESSAGES_COLOR, Statuses_styles.FRIEND_COLOR,
                            Statuses_styles.CREATED_COLOR, Statuses_styles.MESSAGES_TEXTSIZE,
                            Statuses_styles.FRIEND_TEXTSIZE, Statuses_styles.CREATED_TEXTSIZE,
                            Statuses_styles.STATUS_BG, Statuses_styles.ICON, Statuses_styles.PROFILE_BG,
                            Statuses_styles.FRIEND_BG, Statuses_styles.IMAGE_BG, Statuses_styles.IMAGE },
                    null, null, Statuses_styles.CREATED + " DESC LIMIT " + page + ",-1");
            if (statuses_styles.moveToFirst()) {
                int count_status = 0;
                views.removeAllViews(R.id.messages);
                while (!statuses_styles.isAfterLast() && (count_status < 16)) {
                    int friend_color = statuses_styles.getInt(6), created_color = statuses_styles.getInt(7),
                            friend_textsize = statuses_styles.getInt(9),
                            created_textsize = statuses_styles.getInt(10),
                            messages_color = statuses_styles.getInt(5),
                            messages_textsize = statuses_styles.getInt(8);
                    // get the item wrapper
                    RemoteViews itemView;
                    if (display_profile) {
                        itemView = new RemoteViews(getPackageName(), R.layout.widget_item);
                        // set profiles background
                        byte[] profile_bg = statuses_styles.getBlob(13);
                        if (profile_bg != null) {
                            Bitmap profile_bgbmp = BitmapFactory.decodeByteArray(profile_bg, 0,
                                    profile_bg.length, sBFOptions);
                            if (profile_bgbmp != null)
                                itemView.setImageViewBitmap(R.id.profile_bg, profile_bgbmp);
                        }
                        byte[] profile = statuses_styles.getBlob(2);
                        if (profile != null) {
                            Bitmap profilebmp = BitmapFactory.decodeByteArray(profile, 0, profile.length,
                                    sBFOptions);
                            if (profilebmp != null)
                                itemView.setImageViewBitmap(R.id.profile, profilebmp);
                        }
                    } else
                        itemView = new RemoteViews(getPackageName(), R.layout.widget_item_noprofile);
                    itemView.setTextViewText(R.id.friend_bg_clear, statuses_styles.getString(1));
                    itemView.setFloat(R.id.friend_bg_clear, "setTextSize", friend_textsize);
                    itemView.setTextViewText(R.id.message_bg_clear, statuses_styles.getString(3));
                    itemView.setFloat(R.id.message_bg_clear, "setTextSize", messages_textsize);
                    // set friends background
                    byte[] friend_bg = statuses_styles.getBlob(14);
                    if (friend_bg != null) {
                        Bitmap friend_bgbmp = BitmapFactory.decodeByteArray(friend_bg, 0, friend_bg.length,
                                sBFOptions);
                        if (friend_bgbmp != null)
                            itemView.setImageViewBitmap(R.id.friend_bg, friend_bgbmp);
                    }
                    // set messages background
                    byte[] status_bg = statuses_styles.getBlob(11);
                    if (status_bg != null) {
                        Bitmap status_bgbmp = BitmapFactory.decodeByteArray(status_bg, 0, status_bg.length,
                                sBFOptions);
                        if (status_bgbmp != null)
                            itemView.setImageViewBitmap(R.id.status_bg, status_bgbmp);
                    }
                    // set an image
                    byte[] image_bg = statuses_styles.getBlob(15);
                    byte[] image = statuses_styles.getBlob(16);
                    if ((image_bg != null) && (image != null)) {
                        Bitmap image_bgBmp = BitmapFactory.decodeByteArray(image_bg, 0, image_bg.length,
                                sBFOptions);
                        if (image_bgBmp != null) {
                            Bitmap imageBmp = BitmapFactory.decodeByteArray(image, 0, image.length, sBFOptions);
                            itemView.setImageViewBitmap(R.id.image_clear, image_bgBmp);
                            itemView.setImageViewBitmap(R.id.image, imageBmp);
                        }
                    }
                    itemView.setTextViewText(R.id.message, statuses_styles.getString(3));
                    itemView.setTextColor(R.id.message, messages_color);
                    itemView.setFloat(R.id.message, "setTextSize", messages_textsize);
                    itemView.setOnClickPendingIntent(R.id.item,
                            PendingIntent.getActivity(MyfeedleService.this, 0,
                                    Myfeedle.getPackageIntent(MyfeedleService.this, StatusDialog.class)
                                            .setData(Uri.withAppendedPath(
                                                    Statuses_styles.getContentUri(MyfeedleService.this),
                                                    Long.toString(statuses_styles.getLong(0)))),
                                    0));
                    itemView.setTextViewText(R.id.friend, statuses_styles.getString(1));
                    itemView.setTextColor(R.id.friend, friend_color);
                    itemView.setFloat(R.id.friend, "setTextSize", friend_textsize);
                    itemView.setTextViewText(R.id.created, statuses_styles.getString(4));
                    itemView.setTextColor(R.id.created, created_color);
                    itemView.setFloat(R.id.created, "setTextSize", created_textsize);
                    // set icons
                    byte[] icon = statuses_styles.getBlob(12);
                    if (icon != null) {
                        Bitmap iconbmp = BitmapFactory.decodeByteArray(icon, 0, icon.length, sBFOptions);
                        if (iconbmp != null)
                            itemView.setImageViewBitmap(R.id.icon, iconbmp);
                    }
                    views.addView(R.id.messages, itemView);
                    count_status++;
                    statuses_styles.moveToNext();
                }
                if (hasbuttons && (page < statuses_styles.getCount())) {
                    // there are more statuses to show, allow paging down
                    views.setOnClickPendingIntent(R.id.page_down, PendingIntent.getService(MyfeedleService.this,
                            0,
                            Myfeedle.getPackageIntent(MyfeedleService.this, MyfeedleService.class)
                                    .setAction(ACTION_PAGE_DOWN)
                                    .setData(Uri.withAppendedPath(Widgets.getContentUri(MyfeedleService.this),
                                            widget))
                                    .putExtra(ACTION_PAGE_DOWN, page + 1),
                            PendingIntent.FLAG_UPDATE_CURRENT));
                }
            }
            statuses_styles.close();
            if (hasbuttons && (page > 0))
                views.setOnClickPendingIntent(R.id.page_up, PendingIntent.getService(MyfeedleService.this, 0,
                        Myfeedle.getPackageIntent(MyfeedleService.this, MyfeedleService.class)
                                .setAction(ACTION_PAGE_UP)
                                .setData(Uri.withAppendedPath(Widgets.getContentUri(MyfeedleService.this),
                                        widget))
                                .putExtra(ACTION_PAGE_UP, page - 1),
                        PendingIntent.FLAG_UPDATE_CURRENT));
        }
        Log.d(TAG, "update native widget: " + appWidgetId);
        mgr.updateAppWidget(appWidgetId, views);
        if (sNativeScrollingSupported) {
            Log.d(TAG, "trigger widget query: " + appWidgetId);
            try {
                // trigger query
                sNotifyAppWidgetViewDataChanged.invoke(mgr, appWidgetId, R.id.messages);
            } catch (NumberFormatException e) {
                Log.e(TAG, e.toString());
            } catch (IllegalArgumentException e) {
                Log.e(TAG, e.toString());
            } catch (IllegalAccessException e) {
                Log.e(TAG, e.toString());
            } catch (InvocationTargetException e) {
                Log.e(TAG, e.toString());
            }
        }
    } else if (updatesReady) {
        //         Log.d(TAG, "notify updatesReady");
        getContentResolver().notifyChange(Statuses_styles.getContentUri(MyfeedleService.this), null);
    } else {
        AppWidgetManager.getInstance(MyfeedleService.this).updateAppWidget(Integer.parseInt(widget), views);
        buildScrollableWidget(appWidgetId, scrollable, display_profile);
    }
}

From source file:org.opendatakit.utilities.test.AbstractODKDatabaseUtilsTest.java

public void testRawQueryWithData_ExpectPass() {
    String tableId = testTable;//from  w w w.j  a v  a2 s .c o  m
    String query = "SELECT * FROM " + tableId;
    List<Column> columns = new ArrayList<Column>();
    columns.add(new Column("col1", "col1", "string", "[]"));
    OrderedColumns orderedColumns = ODKDatabaseImplUtils.get().createOrOpenTableWithColumns(db, tableId,
            columns);

    ODKDatabaseImplUtils.AccessContext accessContext = ODKDatabaseImplUtils.get().getAccessContext(db, tableId,
            activeUser, RoleConsts.ADMIN_ROLES_LIST);

    // Check that the user defined rows are in the table
    Cursor cursor = ODKDatabaseImplUtils.get().rawQuery(db, query, null, null, accessContext);
    Cursor refCursor = db.rawQuery(query, null);

    if (cursor != null && refCursor != null) {
        int index = 0;
        while (cursor.moveToNext() && refCursor.moveToNext()) {
            int testType = cursor.getType(index);
            int refType = refCursor.getType(index);
            assertEquals(testType, refType);

            switch (refType) {
            case Cursor.FIELD_TYPE_BLOB:
                byte[] byteArray = cursor.getBlob(index);
                byte[] refByteArray = refCursor.getBlob(index);
                assertEquals(byteArray, refByteArray);
                break;
            case Cursor.FIELD_TYPE_FLOAT:
                float valueFloat = cursor.getFloat(index);
                float refValueFloat = refCursor.getFloat(index);
                assertEquals(valueFloat, refValueFloat);
                break;
            case Cursor.FIELD_TYPE_INTEGER:
                int valueInt = cursor.getInt(index);
                int refValueInt = refCursor.getInt(index);
                assertEquals(valueInt, refValueInt);
                break;
            case Cursor.FIELD_TYPE_STRING:
                String valueStr = cursor.getString(index);
                String refValueStr = refCursor.getString(index);
                assertEquals(valueStr, refValueStr);
                break;
            case Cursor.FIELD_TYPE_NULL:
            default:
                break;
            }
        }
    }

    // Drop the table now that the test is done
    ODKDatabaseImplUtils.get().deleteTableAndAllData(db, tableId);
}

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

private void sortChannels() {
    ContentResolver cr = getContentResolver();

    StringBuilder where = new StringBuilder(TvBrowserContentProvider.CHANNEL_KEY_SELECTION);
    where.append("=1");

    LinearLayout main = (LinearLayout) getLayoutInflater().inflate(R.layout.channel_sort_list,
            getParentViewGroup(), false);

    Button sortAlphabetically = (Button) main.findViewById(R.id.channel_sort_alpabetically);

    final DynamicListView channelSort = (DynamicListView) main.findViewById(R.id.channel_sort);

    String[] projection = { TvBrowserContentProvider.KEY_ID, TvBrowserContentProvider.CHANNEL_KEY_NAME,
            TvBrowserContentProvider.CHANNEL_KEY_ORDER_NUMBER, TvBrowserContentProvider.CHANNEL_KEY_SELECTION,
            TvBrowserContentProvider.CHANNEL_KEY_LOGO };

    Cursor channels = cr.query(TvBrowserContentProvider.CONTENT_URI_CHANNELS, projection, where.toString(),
            null, TvBrowserContentProvider.CHANNEL_KEY_ORDER_NUMBER);

    final ArrayList<SortInterface> channelSource = new ArrayList<SortInterface>();

    if (channels.moveToFirst()) {
        do {//from   ww w .ja v a 2 s  . co m
            int key = channels.getInt(0);
            String name = channels.getString(1);

            int order = 0;

            if (!channels.isNull(channels.getColumnIndex(TvBrowserContentProvider.CHANNEL_KEY_ORDER_NUMBER))) {
                order = channels
                        .getInt(channels.getColumnIndex(TvBrowserContentProvider.CHANNEL_KEY_ORDER_NUMBER));
            }

            Bitmap channelLogo = UiUtils.createBitmapFromByteArray(
                    channels.getBlob(channels.getColumnIndex(TvBrowserContentProvider.CHANNEL_KEY_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);
            }

            channelSource.add(new ChannelSort(key, name, order, channelLogo));
        } while (channels.moveToNext());

        channels.close();

        final Comparator<SortInterface> sortComparator = new Comparator<SortInterface>() {
            @Override
            public int compare(SortInterface lhs, SortInterface rhs) {
                if (lhs.getSortNumber() < rhs.getSortNumber()) {
                    return -1;
                } else if (lhs.getSortNumber() > rhs.getSortNumber()) {
                    return 1;
                }

                return 0;
            }
        };

        Collections.sort(channelSource, sortComparator);

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

        final StableArrayAdapter<SortInterface> aa = new StableArrayAdapter<SortInterface>(TvBrowser.this,
                R.layout.channel_sort_row, channelSource) {
            public View getView(int position, View convertView, ViewGroup parent) {
                ChannelSort value = (ChannelSort) 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_sort_row, getParentViewGroup(), false);

                    holder.mTextView = (TextView) convertView.findViewById(R.id.row_of_channel_sort_text);
                    holder.mSortNumber = (TextView) convertView.findViewById(R.id.row_of_channel_sort_number);
                    holder.mLogo = (ImageView) convertView.findViewById(R.id.row_of_channel_sort_icon);

                    convertView.setTag(holder);

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

                holder.mTextView.setText(value.getName());

                String sortNumber = String.valueOf(value.getSortNumber());

                if (value.getSortNumber() == 0) {
                    sortNumber = "-";
                }

                sortNumber += ".";

                holder.mSortNumber.setText(sortNumber);

                Bitmap logo = value.getLogo();

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

                return convertView;
            }
        };
        channelSort.setAdapter(aa);
        channelSort.setArrayList(channelSource);
        channelSort.setSortDropListener(new SortDropListener() {
            @Override
            public void dropped(int originalPosition, int position) {
                int startIndex = originalPosition;
                int endIndex = position;

                int droppedPos = position;

                if (originalPosition > position) {
                    startIndex = position;
                    endIndex = originalPosition;
                }

                int previousNumber = 0;

                if (startIndex > 0) {
                    previousNumber = aa.getItem(startIndex - 1).getSortNumber();
                }

                int firstVisible = channelSort.getFirstVisiblePosition();

                for (int i = startIndex; i <= endIndex; i++) {
                    if (i == droppedPos || aa.getItem(i).getSortNumber() != 0) {
                        aa.getItem(i).setSortNumber(++previousNumber);

                        if (i >= firstVisible) {
                            View line = channelSort.getChildAt(i - firstVisible);

                            if (line != null) {
                                ((TextView) line.findViewById(R.id.row_of_channel_sort_number))
                                        .setText(String.valueOf(previousNumber) + ".");
                            }
                        }
                    }
                }

            }
        });

        channelSort.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(final AdapterView<?> adapterView, final View view, final int position,
                    long id) {
                AlertDialog.Builder builder = new AlertDialog.Builder(TvBrowser.this);

                LinearLayout numberSelection = (LinearLayout) getLayoutInflater()
                        .inflate(R.layout.sort_number_selection, getParentViewGroup(), false);

                mSelectionNumberChanged = false;

                final NumberPicker number = (NumberPicker) numberSelection.findViewById(R.id.sort_picker);
                number.setMinValue(1);
                number.setMaxValue(channelSource.size());
                number.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
                number.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
                    @Override
                    public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                        mSelectionNumberChanged = true;
                    }
                });

                final EditText numberAlternative = (EditText) numberSelection
                        .findViewById(R.id.sort_entered_number);

                builder.setView(numberSelection);

                final ChannelSort selection = (ChannelSort) channelSource.get(position);

                TextView name = (TextView) numberSelection.findViewById(R.id.sort_picker_channel_name);
                name.setText(selection.getName());

                if (selection.getSortNumber() > 0) {
                    if (selection.getSortNumber() < channelSource.size() + 1) {
                        number.setValue(selection.getSortNumber());
                    } else {
                        numberAlternative.setText(String.valueOf(selection.getSortNumber()));
                    }
                }

                builder.setPositiveButton(android.R.string.ok, new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String test = numberAlternative.getText().toString().trim();

                        if (test.length() == 0 || mSelectionNumberChanged) {
                            selection.setSortNumber(number.getValue());
                        } else {
                            try {
                                selection.setSortNumber(Integer.parseInt(test));
                            } catch (NumberFormatException e1) {
                            }
                        }

                        Collections.sort(channelSource, sortComparator);
                        aa.notifyDataSetChanged();
                    }
                });

                builder.setNegativeButton(android.R.string.cancel, null);

                builder.show();
            }
        });

        sortAlphabetically.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Collections.sort(channelSource, new Comparator<SortInterface>() {
                    @Override
                    public int compare(SortInterface lhs, SortInterface rhs) {
                        return lhs.getName().compareToIgnoreCase(rhs.getName());
                    }
                });

                for (int i = 0; i < channelSource.size(); i++) {
                    channelSource.get(i).setSortNumber(i + 1);
                }

                aa.notifyDataSetChanged();
            }
        });

        AlertDialog.Builder builder = new AlertDialog.Builder(TvBrowser.this);

        builder.setTitle(R.string.action_sort_channels);
        builder.setView(main);

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

                for (SortInterface selection : channelSource) {
                    if (((ChannelSort) selection).wasChanged()) {
                        somethingChanged = true;

                        ContentValues values = new ContentValues();
                        values.put(TvBrowserContentProvider.CHANNEL_KEY_ORDER_NUMBER,
                                selection.getSortNumber());

                        getContentResolver().update(
                                ContentUris.withAppendedId(TvBrowserContentProvider.CONTENT_URI_CHANNELS,
                                        ((ChannelSort) selection).getKey()),
                                values, null, null);
                    }
                }

                if (somethingChanged) {
                    updateProgramListChannelBar();
                }
            }
        });
        builder.setNegativeButton(android.R.string.cancel, new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });

        builder.show();
    }
}

From source file:org.opendatakit.utilities.test.AbstractODKDatabaseUtilsTest.java

public void testQueryWithData_ExpectPass() {
    String tableId = testTable;/* w  w w . j a  v  a  2  s.c o m*/
    List<Column> columns = new ArrayList<Column>();
    columns.add(new Column("col1", "col1", "string", "[]"));
    OrderedColumns orderedColumns = ODKDatabaseImplUtils.get().createOrOpenTableWithColumns(db, tableId,
            columns);

    // Check that the user defined rows are in the table
    Cursor cursor = ODKDatabaseImplUtils.get().queryForTest(db, tableId, null, null, null, null, null, null,
            null);
    Cursor refCursor = db.query(tableId, null, null, null, null, null, null, null);

    if (cursor != null && refCursor != null) {
        int index = 0;
        while (cursor.moveToNext() && refCursor.moveToNext()) {
            int testType = cursor.getType(index);
            int refType = refCursor.getType(index);
            assertEquals(testType, refType);

            switch (refType) {
            case Cursor.FIELD_TYPE_BLOB:
                byte[] byteArray = cursor.getBlob(index);
                byte[] refByteArray = refCursor.getBlob(index);
                assertEquals(byteArray, refByteArray);
                break;
            case Cursor.FIELD_TYPE_FLOAT:
                float valueFloat = cursor.getFloat(index);
                float refValueFloat = refCursor.getFloat(index);
                assertEquals(valueFloat, refValueFloat);
                break;
            case Cursor.FIELD_TYPE_INTEGER:
                int valueInt = cursor.getInt(index);
                int refValueInt = refCursor.getInt(index);
                assertEquals(valueInt, refValueInt);
                break;
            case Cursor.FIELD_TYPE_STRING:
                String valueStr = cursor.getString(index);
                String refValueStr = refCursor.getString(index);
                assertEquals(valueStr, refValueStr);
                break;
            case Cursor.FIELD_TYPE_NULL:
            default:
                break;
            }
        }
    }

    // Drop the table now that the test is done
    ODKDatabaseImplUtils.get().deleteTableAndAllData(db, tableId);
}

From source file:org.opendatakit.utilities.AbstractODKDatabaseUtilsTest.java

@Test
public void testRawQueryWithData_ExpectPass() {
    String tableId = testTable;/*from w w w . j ava 2 s  . c  om*/
    String query = "SELECT * FROM " + tableId;
    List<Column> columns = new ArrayList<Column>();
    columns.add(new Column("col1", "col1", "string", "[]"));
    OrderedColumns orderedColumns = ODKDatabaseImplUtils.get().createOrOpenTableWithColumns(db, tableId,
            columns);

    ODKDatabaseImplUtils.AccessContext accessContext = ODKDatabaseImplUtils.get().getAccessContext(db, tableId,
            activeUser, RoleConsts.ADMIN_ROLES_LIST);

    // Check that the user defined rows are in the table
    Cursor cursor = ODKDatabaseImplUtils.get().rawQuery(db, query, null, null, accessContext);
    Cursor refCursor = db.rawQuery(query, null);

    if (cursor != null && refCursor != null) {
        int index = 0;
        while (cursor.moveToNext() && refCursor.moveToNext()) {
            int testType = cursor.getType(index);
            int refType = refCursor.getType(index);
            assertEquals(testType, refType);

            switch (refType) {
            case Cursor.FIELD_TYPE_BLOB:
                byte[] byteArray = cursor.getBlob(index);
                byte[] refByteArray = refCursor.getBlob(index);
                assertEquals(byteArray, refByteArray);
                break;
            case Cursor.FIELD_TYPE_FLOAT:
                float valueFloat = cursor.getFloat(index);
                float refValueFloat = refCursor.getFloat(index);
                assertEquals(valueFloat, refValueFloat, 0.0);
                break;
            case Cursor.FIELD_TYPE_INTEGER:
                int valueInt = cursor.getInt(index);
                int refValueInt = refCursor.getInt(index);
                assertEquals(valueInt, refValueInt);
                break;
            case Cursor.FIELD_TYPE_STRING:
                String valueStr = cursor.getString(index);
                String refValueStr = refCursor.getString(index);
                assertEquals(valueStr, refValueStr);
                break;
            case Cursor.FIELD_TYPE_NULL:
            default:
                break;
            }
        }
    }

    // Drop the table now that the test is done
    ODKDatabaseImplUtils.get().deleteTableAndAllData(db, tableId);
}

From source file:org.opendatakit.utilities.AbstractODKDatabaseUtilsTest.java

@Test
public void testQueryWithData_ExpectPass() {
    String tableId = testTable;/*from ww w .  ja v  a2 s .  c o m*/
    List<Column> columns = new ArrayList<Column>();
    columns.add(new Column("col1", "col1", "string", "[]"));
    OrderedColumns orderedColumns = ODKDatabaseImplUtils.get().createOrOpenTableWithColumns(db, tableId,
            columns);

    // Check that the user defined rows are in the table
    Cursor cursor = ODKDatabaseImplUtils.get().queryForTest(db, tableId, null, null, null, null, null, null,
            null);
    Cursor refCursor = db.query(tableId, null, null, null, null, null, null, null);

    if (cursor != null && refCursor != null) {
        int index = 0;
        while (cursor.moveToNext() && refCursor.moveToNext()) {
            int testType = cursor.getType(index);
            int refType = refCursor.getType(index);
            assertEquals(testType, refType);

            switch (refType) {
            case Cursor.FIELD_TYPE_BLOB:
                byte[] byteArray = cursor.getBlob(index);
                byte[] refByteArray = refCursor.getBlob(index);
                assertEquals(byteArray, refByteArray);
                break;
            case Cursor.FIELD_TYPE_FLOAT:
                float valueFloat = cursor.getFloat(index);
                float refValueFloat = refCursor.getFloat(index);
                assertEquals(valueFloat, refValueFloat, 0.0);
                break;
            case Cursor.FIELD_TYPE_INTEGER:
                int valueInt = cursor.getInt(index);
                int refValueInt = refCursor.getInt(index);
                assertEquals(valueInt, refValueInt);
                break;
            case Cursor.FIELD_TYPE_STRING:
                String valueStr = cursor.getString(index);
                String refValueStr = refCursor.getString(index);
                assertEquals(valueStr, refValueStr);
                break;
            case Cursor.FIELD_TYPE_NULL:
            default:
                break;
            }
        }
    }

    // Drop the table now that the test is done
    ODKDatabaseImplUtils.get().deleteTableAndAllData(db, tableId);
}