Example usage for android.provider BaseColumns _ID

List of usage examples for android.provider BaseColumns _ID

Introduction

In this page you can find the example usage for android.provider BaseColumns _ID.

Prototype

String _ID

To view the source code for android.provider BaseColumns _ID.

Click Source Link

Document

The unique ID for a row.

Usage

From source file:ru.valle.safetrade.SellActivity.java

private void savePrivateKey(final String encryptedPrivateKey) {
    final String password = tradeInfo.password;
    final long id = rowId;
    privateKeyDecodingTask = new AsyncTask<Void, String, KeyPair>() {
        public ProgressDialog progressDialog;

        @Override//  ww w. jav a  2s.co  m
        protected void onPreExecute() {
            final CharSequence oldEnteredValue = privateKeyView.getText();
            privateKeyView.setText(encryptedPrivateKey);
            progressDialog = ProgressDialog.show(SellActivity.this, null,
                    getString(R.string.decrypting_private_key), true);
            progressDialog.setCancelable(true);
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    privateKeyView.setText(oldEnteredValue);
                    privateKeyDecodingTask.cancel(true);
                    if (rowId != -1) {
                        loadState(rowId);
                    }
                }
            });
        }

        @Override
        protected void onProgressUpdate(String... values) {
            try {
                progressDialog.setMessage(values[0]);
            } catch (Exception ignored) {
            }
        }

        @Override
        protected KeyPair doInBackground(Void... params) {
            try {
                KeyPair keyPair = BTCUtils.bip38Decrypt(encryptedPrivateKey, password);
                if (keyPair != null) {
                    SQLiteDatabase db = DatabaseHelper.getInstance(SellActivity.this).getWritableDatabase();
                    if (db != null) {
                        ContentValues cv = new ContentValues();
                        cv.put(DatabaseHelper.COLUMN_ADDRESS, keyPair.address);
                        cv.put(DatabaseHelper.COLUMN_ENCRYPTED_PRIVATE_KEY, encryptedPrivateKey);
                        cv.put(DatabaseHelper.COLUMN_PRIVATE_KEY,
                                BTCUtils.encodeWifKey(keyPair.privateKey.isPublicKeyCompressed,
                                        BTCUtils.getPrivateKeyBytes(keyPair.privateKey.privateKeyDecoded)));
                        db.update(DatabaseHelper.TABLE_HISTORY, cv, BaseColumns._ID + "=?",
                                new String[] { String.valueOf(id) });
                    }
                }
                return keyPair;
            } catch (InterruptedException e) {
                Log.v(TAG, "pk decrypt interrupted");
                return null;
            } catch (Throwable e) {
                Log.e(TAG, "pk decrypt", e);
                return null;
            }
        }

        @Override
        protected void onPostExecute(final KeyPair keyPair) {
            try {
                progressDialog.dismiss();
            } catch (Exception ignored) {
            }
            privateKeyDecodingTask = null;
            showAlert(keyPair != null ? getString(R.string.private_key_decrypted, keyPair.address)
                    : getString(R.string.unable_to_decrypt_private_key));
            loadState(rowId);
        }
    }.execute();

}

From source file:com.bt.download.android.gui.Librarian.java

private Pair<List<Integer>, List<String>> getAllFiles(byte fileType) {
    Pair<List<Integer>, List<String>> result = new Pair<List<Integer>, List<String>>(new ArrayList<Integer>(),
            new ArrayList<String>());

    Cursor c = null;//from  www  . j  av a  2s .c  o m

    try {
        TableFetcher fetcher = TableFetchers.getFetcher(fileType);

        ContentResolver cr = context.getContentResolver();

        c = cr.query(fetcher.getContentUri(), new String[] { BaseColumns._ID, MediaColumns.DATA }, null, null,
                BaseColumns._ID);

        if (c != null) {
            while (c.moveToNext()) {
                result.first.add(c.getInt(0));
                result.second.add(c.getString(1));
            }
        }
    } catch (Throwable e) {
        Log.e(TAG, "General failure getting all files", e);
    } finally {
        if (c != null) {
            c.close();
        }
    }

    return result;
}

From source file:com.application.akscorp.yandextranslator2017.TranslateScreen.java

/**
 * @param JSONResult json translate answer from server
 * @param input      text from EditTextInputForTranslate
 * @param type       language pair form "ru-en" and etc.
 * @return record which was added in database
 * @throws Exception//from   w  w  w . j  a  v  a  2  s  .co  m
 */
private ArrayList<String> AddTranslateToHistory(String JSONResult, String input, String type) throws Exception {
    try {
        MyPair<String, String> data = new MyPair<String, String>();
        JSONObject jsonResponse = new JSONObject(JSONResult);

        String db_name = "Cache";
        String TableName = "History";
        String Create_query = "create table " + TableName + " (" + BaseColumns._ID
                + " integer primary key autoincrement, " + "Translate" + " text not null, " + "Input "
                + "text not null, " + "Type " + "text not null, " + "CreateTime " + "text not null, "
                + "Favourite " + "text not null" + ");";

        ArrayList<MyPair<String, String>> cc = new ArrayList<>();

        String Translate = (String) jsonResponse.getJSONArray("text").get(0);
        String time = String.valueOf(GetUnixTime());
        cc.add(data.mp("Translate", Translate));
        cc.add(data.mp("Input", input));
        cc.add(data.mp("Type", type));

        cc.add(data.mp("CreateTime", time));
        cc.add(data.mp("Favourite", "0"));

        if (!db.isTableExists(db_name, TableName))
            db.CreateDatabase(db_name, Create_query);
        long id = 0;
        id = db.InsertDataInTable(db_name, TableName, cc);
        ArrayList<ArrayList<String>> Data = db.GetRecordFromDatabase(db_name, TableName,
                "_id = " + String.valueOf(id), -1, "");
        myApp.getHistoryAndFavouriteScreen().HistoryData.add(0, Data.get(0));
        return Data.get(0);
    } catch (Exception e) {
        Logs.SaveLog(context, e);
        throw e;
    }
}

From source file:org.catnut.fragment.ProfileFragment.java

private void toggleFollow(final boolean follow) {
    mApp.getRequestQueue()// w  w  w. ja v  a  2  s .  c  o  m
            .add(new CatnutRequest(getActivity(),
                    follow ? FriendshipsAPI.create(mScreenName, null) : FriendshipsAPI.destroy(mScreenName),
                    new UserProcessor.UserProfileProcessor(), new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject response) {
                            Toast.makeText(getActivity(),
                                    getString(follow ? R.string.follow_success : R.string.unfollow_success),
                                    Toast.LENGTH_SHORT).show();
                            if (follow) {
                                mMenu.removeItem(R.id.action_follow);
                                mMenu.add(Menu.NONE, R.id.action_follow, Menu.NONE, R.string.unfollow)
                                        .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
                            } else {
                                mMenu.removeItem(R.id.action_unfollow);
                                mMenu.add(Menu.NONE, R.id.action_follow, Menu.NONE, R.string.follow)
                                        .setIcon(R.drawable.ic_title_follow)
                                        .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
                            }
                            mFollowing = !mFollowing;
                            // ?
                            final String str = follow ? "+1" : "-1";
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    long uid = mApp.getAccessToken().uid;
                                    String update = "update " + User.TABLE + " SET " + User.friends_count + "="
                                            + User.friends_count + str + " WHERE " + BaseColumns._ID + "="
                                            + uid;
                                    getActivity().getContentResolver().update(
                                            CatnutProvider.parse(User.MULTIPLE, uid), null, update, null);
                                }
                            }).start();
                        }
                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(getActivity(), error.getLocalizedMessage(), Toast.LENGTH_SHORT)
                                    .show();
                        }
                    }));
}

From source file:com.andrew.apollo.utils.MusicUtils.java

/**
 * Returns The ID for a playlist.//from   w w  w .java  2  s .com
 *
 * @param context The {@link Context} to use.
 * @param name The name of the playlist.
 * @return The ID for a playlist.
 */
public static long getIdForPlaylist(final Context context, final String name) {
    Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI,
            new String[] { BaseColumns._ID }, PlaylistsColumns.NAME + "=?", new String[] { name },
            PlaylistsColumns.NAME);
    return getFirstId(cursor, -1);
}

From source file:com.google.android.apps.muzei.provider.MuzeiProvider.java

private Uri insertArtwork(@NonNull final Uri uri, final ContentValues values) {
    Context context = getContext();
    if (context == null) {
        return null;
    }//from  w  w w  .j ava 2s .co  m
    if (values == null) {
        throw new IllegalArgumentException("Invalid ContentValues: must not be null");
    }
    if (!values.containsKey(MuzeiContract.Artwork.COLUMN_NAME_SOURCE_COMPONENT_NAME)
            || TextUtils.isEmpty(values.getAsString(MuzeiContract.Artwork.COLUMN_NAME_SOURCE_COMPONENT_NAME))) {
        throw new IllegalArgumentException("Initial values must contain component name: " + values);
    }

    // Check to make sure the component name is valid
    ComponentName componentName = ComponentName
            .unflattenFromString(values.getAsString(MuzeiContract.Artwork.COLUMN_NAME_SOURCE_COMPONENT_NAME));
    if (componentName == null) {
        throw new IllegalArgumentException("Invalid component name: "
                + values.getAsString(MuzeiContract.Artwork.COLUMN_NAME_SOURCE_COMPONENT_NAME));
    }
    // Make sure they are using the short string format
    values.put(MuzeiContract.Artwork.COLUMN_NAME_SOURCE_COMPONENT_NAME, componentName.flattenToShortString());

    // Ensure the app inserting the artwork is either Muzei or the same app as the source
    String callingPackageName = getCallingPackage();
    if (!context.getPackageName().equals(callingPackageName)
            && !TextUtils.equals(callingPackageName, componentName.getPackageName())) {
        throw new IllegalArgumentException("Calling package name (" + callingPackageName
                + ") must match the source's package name (" + componentName.getPackageName() + ")");
    }

    if (values.containsKey(MuzeiContract.Artwork.COLUMN_NAME_VIEW_INTENT)) {
        String viewIntentString = values.getAsString(MuzeiContract.Artwork.COLUMN_NAME_VIEW_INTENT);
        Intent viewIntent;
        try {
            if (!TextUtils.isEmpty(viewIntentString)) {
                // Make sure it is a valid Intent URI
                viewIntent = Intent.parseUri(viewIntentString, Intent.URI_INTENT_SCHEME);
                // Make sure we can construct a PendingIntent for the Intent
                PendingIntent.getActivity(context, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            }
        } catch (URISyntaxException e) {
            Log.w(TAG, "Removing invalid View Intent: " + viewIntentString, e);
            values.remove(MuzeiContract.Artwork.COLUMN_NAME_VIEW_INTENT);
        } catch (RuntimeException e) {
            // This is actually meant to catch a FileUriExposedException, but you can't
            // have catch statements for exceptions that don't exist at your minSdkVersion
            Log.w(TAG, "Removing invalid View Intent that contains a file:// URI: " + viewIntentString, e);
            values.remove(MuzeiContract.Artwork.COLUMN_NAME_VIEW_INTENT);
        }
    }

    // Ensure the related source has been added to the database.
    // This should be true in 99.9% of cases, but the insert will fail if this isn't true
    Cursor sourceQuery = querySource(MuzeiContract.Sources.CONTENT_URI, new String[] { BaseColumns._ID },
            MuzeiContract.Sources.COLUMN_NAME_COMPONENT_NAME + "=?",
            new String[] { componentName.flattenToShortString() }, null);
    if (sourceQuery == null || sourceQuery.getCount() == 0) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(MuzeiContract.Sources.COLUMN_NAME_COMPONENT_NAME,
                componentName.flattenToShortString());
        insertSource(MuzeiContract.Sources.CONTENT_URI, initialValues);
    }
    if (sourceQuery != null) {
        sourceQuery.close();
    }

    values.put(MuzeiContract.Artwork.COLUMN_NAME_DATE_ADDED, System.currentTimeMillis());
    final SQLiteDatabase db = databaseHelper.getWritableDatabase();
    long rowId = db.insert(MuzeiContract.Artwork.TABLE_NAME, MuzeiContract.Artwork.COLUMN_NAME_IMAGE_URI,
            values);
    // If the insert succeeded, the row ID exists.
    if (rowId > 0) {
        // Creates a URI with the artwork ID pattern and the new row ID appended to it.
        final Uri artworkUri = ContentUris.withAppendedId(MuzeiContract.Artwork.CONTENT_URI, rowId);
        File artwork = getCacheFileForArtworkUri(artworkUri);
        if (artwork != null && artwork.exists()) {
            // The image already exists so we'll notifyChange() to say the new artwork is ready
            // Otherwise, this will be called when the file is written with openFile()
            // using this Uri and the actual artwork is written successfully
            notifyChange(artworkUri);
        }
        return artworkUri;
    }
    // If the insert didn't succeed, then the rowID is <= 0
    throw new SQLException("Failed to insert row into " + uri);
}

From source file:org.codarama.haxsync.services.ContactsSyncAdapterService.java

@SuppressWarnings("unused")
private static void performSync(Context context, Account account, Bundle extras, String authority,
        ContentProviderClient provider, SyncResult syncResult) throws OperationCanceledException {
    SharedPreferences prefs = context.getSharedPreferences(context.getPackageName() + "_preferences",
            MODE_MULTI_PROCESS);// w  ww  .  java  2 s  .  c om

    mContentResolver = context.getContentResolver();

    FacebookUtil.refreshPermissions(context);

    //TODO: Clean up stuff that isn't needed anymore since Graph API
    boolean cropPhotos = true;
    boolean sync = prefs.getBoolean("sync_status", true);
    boolean syncNew = prefs.getBoolean("status_new", true);
    boolean syncLocation = prefs.getBoolean("sync_location", true);
    boolean syncSelf = prefs.getBoolean("sync_self", false);
    boolean imageDefault = prefs.getBoolean("image_primary", true);

    boolean oldStatus = sync && (!syncNew || (Build.VERSION.SDK_INT < 15));
    boolean faceDetect = true;

    boolean root = prefs.getBoolean("root_enabled", false);
    int rootSize = 512;

    if (FacebookUtil.authorize(context, account)) {

        HashMap<String, SyncEntry> localContacts = getLocalContacts(account);
        HashMap<String, Long> names = loadPhoneContacts(context);
        HashMap<String, Long> uids = loadHTCData(context);
        //Log.i("CONTACTS", names.toString());
        boolean phoneOnly = prefs.getBoolean("phone_only", true);
        /*if (phoneOnly){
           names = loadPhoneContacts(context);
        }*/
        boolean wifiOnly = prefs.getBoolean("wifi_only", false);
        boolean syncEmail = prefs.getBoolean("sync_facebook_email", false);
        boolean syncBirthday = prefs.getBoolean("sync_contact_birthday", true);
        boolean force = prefs.getBoolean("force_dl", false);
        boolean google = prefs.getBoolean("update_google_photos", false);
        boolean ignoreMiddleaNames = prefs.getBoolean("ignore_middle_names", false);
        boolean addMeToFriends = prefs.getBoolean("add_me_to_friends", false);
        Log.i("google", String.valueOf(google));
        int fuzziness = Integer.parseInt(prefs.getString("fuzziness", "2"));
        Set<String> addFriends = prefs.getStringSet("add_friends", new HashSet<String>());
        Log.i(TAG, "phone_only: " + Boolean.toString(phoneOnly));
        Log.i(TAG, "wifi_only: " + Boolean.toString(wifiOnly));
        Log.i(TAG, "is wifi: " + Boolean.toString(DeviceUtil.isWifi(context)));
        Log.i(TAG, "phone contacts: " + names.toString());
        Log.i(TAG, "using old status api: " + String.valueOf(oldStatus));
        Log.i(TAG, "ignoring middle names : " + String.valueOf(ignoreMiddleaNames));
        Log.i(TAG, "add me to friends : " + String.valueOf(addMeToFriends));
        boolean chargingOnly = prefs.getBoolean("charging_only", false);
        int maxsize = BitmapUtil.getMaxSize(context.getContentResolver());
        File cacheDir = context.getCacheDir();
        Log.i("CACHE DIR", cacheDir.getAbsolutePath());
        Log.i("MAX IMAGE SIZE", String.valueOf(maxsize));
        if (!((wifiOnly && !DeviceUtil.isWifi(context)) || (chargingOnly && !DeviceUtil.isCharging(context)))) {
            try {
                if (syncSelf) {
                    addSelfContact(account, maxsize, cropPhotos, faceDetect, force, root, rootSize, cacheDir,
                            google);
                }
                List<FacebookGraphFriend> friends = FacebookUtil.getFriends(maxsize, addMeToFriends);
                for (FacebookGraphFriend friend : friends) {
                    String uid = friend.getUserName();
                    String friendName = friend.getName(ignoreMiddleaNames);
                    if (friendName != null && uid != null) {
                        String match = matches(names.keySet(), friendName, fuzziness);

                        if (!(phoneOnly && (match == null) && !uids.containsKey(uid))
                                || addFriends.contains(friendName)) {
                            // STEP 1. Add contact - if the contact is not part of the HTCData records and does not match any
                            // of the fuzziness names we add them to the list of contacts with the intention to make them available
                            // for manual merge (I guess)
                            if (localContacts.get(uid) == null) {
                                //String name = friend.getString("name");
                                //Log.i(TAG, name + " already on phone: " + Boolean.toString(names.contains(name)));

                                addContact(account, friendName, uid);

                                SyncEntry entry = new SyncEntry();
                                Uri rawContactUr = RawContacts.CONTENT_URI.buildUpon()
                                        .appendQueryParameter(RawContacts.ACCOUNT_NAME, account.name)
                                        .appendQueryParameter(RawContacts.ACCOUNT_TYPE, account.type)
                                        .appendQueryParameter(RawContacts.Data.DATA1, uid).build();
                                Cursor c = mContentResolver.query(rawContactUr,
                                        new String[] { BaseColumns._ID }, null, null, null);
                                c.moveToLast();
                                long id = c.getLong(c.getColumnIndex(BaseColumns._ID));
                                c.close();
                                //   Log.i("ID", Long.toString(id));
                                entry.raw_id = id;
                                localContacts.put(uid, entry);
                                if (uids.containsKey(uid)) {
                                    ContactUtil.merge(context, uids.get(uid), id);
                                } else if (names.containsKey(match)) {
                                    ContactUtil.merge(context, names.get(match), id);
                                }
                                //localContacts = loadContacts(accounts, context);
                            }

                            // STEP 2. Set contact photo

                            SyncEntry contact = localContacts.get(uid);

                            updateContactPhoto(contact.raw_id, friend.getPicTimestamp(), maxsize, cropPhotos,
                                    friend.getPicURL(), faceDetect, force, root, rootSize, cacheDir, google,
                                    imageDefault);

                            if (syncEmail && !FacebookUtil.RESPECT_FACEBOOK_POLICY)
                                ContactUtil.addEmail(context, contact.raw_id, friend.getEmail());

                            if (syncLocation && !FacebookUtil.RESPECT_FACEBOOK_POLICY) {
                                ContactUtil.updateContactLocation(contact.raw_id, friend.getLocation());
                            }

                            if (oldStatus && !FacebookUtil.RESPECT_FACEBOOK_POLICY) {
                                ArrayList<Status> statuses = friend.getStatuses();
                                if (statuses.size() >= 1) {
                                    updateContactStatus(contact.raw_id, statuses.get(0).getMessage(),
                                            statuses.get(0).getTimestamp());
                                }

                            }
                            if (syncBirthday && !FacebookUtil.RESPECT_FACEBOOK_POLICY) {
                                String birthday = friend.getBirthday();

                                if (birthday != null) {
                                    ContactUtil.addBirthday(contact.raw_id, birthday);
                                }
                            }

                        }
                    }
                }
            } catch (Exception e) {
                // FIXME catching the generic Exception class is not hte best thing to do
                Log.e("ERROR", e.toString());
            }

            if (root) {
                try {
                    RootUtil.refreshContacts();
                } catch (ShellException e) {
                    Log.e("Error", e.getLocalizedMessage());
                }
            }
            if (force) {
                SharedPreferences.Editor editor = prefs.edit();
                editor.putBoolean("force_dl", false);
                editor.commit();

            }

        } else {
            SharedPreferences.Editor editor = prefs.edit();
            editor.putBoolean("missed_contact_sync", true);
            editor.commit();
        }
    }
}

From source file:com.andrew.apollo.utils.MusicUtils.java

/**
 * Returns the Id for an artist./*from   ww  w . ja va2s  .co  m*/
 *
 * @param context The {@link Context} to use.
 * @param name The name of the artist.
 * @return The ID for an artist.
 */
public static long getIdForArtist(final Context context, final String name) {
    Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Artists.EXTERNAL_CONTENT_URI,
            new String[] { BaseColumns._ID }, ArtistColumns.ARTIST + "=?", new String[] { name },
            ArtistColumns.ARTIST);
    return getFirstId(cursor, -1);
}

From source file:saschpe.birthdays.service.CalendarSyncService.java

/**
 * Returns birthday calendar ID.//w ww. j  a v a2s  .  com
 *
 * If no calendar is present, a new one is created.
 *
 * @return calendar id
 */
public static long getCalendar(Context context) {
    final Uri calenderUri = getCalendarUri(context, CalendarContract.Calendars.CONTENT_URI);

    final String selection = CalendarContract.Calendars.ACCOUNT_NAME + " = ? AND "
            + CalendarContract.Calendars.ACCOUNT_TYPE + " = ? AND " + CalendarContract.Calendars.NAME + " = ?";
    final String calendarName = context.getString(R.string.calendar_name);

    ContentResolver cr = context.getContentResolver();
    Cursor cursor = cr.query(calenderUri, new String[] { BaseColumns._ID }, selection, new String[] {
            context.getString(R.string.app_name), context.getString(R.string.account_type), calendarName },
            null);

    if (cursor != null && cursor.moveToNext()) {
        // Yay, calendar exists already. Just return it's id.
        long calendarId = cursor.getLong(0);
        cursor.close();
        return calendarId;
    } else {
        if (cursor != null) {
            cursor.close();
        }

        // So we've got to create a calendar first before we can return it's id.
        ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(calenderUri);
        builder.withValue(CalendarContract.Calendars.ACCOUNT_NAME, context.getString(R.string.app_name));
        builder.withValue(CalendarContract.Calendars.ACCOUNT_TYPE, context.getString(R.string.account_type));
        builder.withValue(CalendarContract.Calendars.NAME, calendarName);
        builder.withValue(CalendarContract.Calendars.CALENDAR_DISPLAY_NAME,
                context.getString(R.string.birthdays_and_anniversaries));
        builder.withValue(CalendarContract.Calendars.CALENDAR_COLOR,
                PreferencesHelper.getCalendarColor(context));
        builder.withValue(CalendarContract.Calendars.SYNC_EVENTS, PreferencesHelper.isCalendarSynced(context));
        builder.withValue(CalendarContract.Calendars.VISIBLE, 1);
        if (BuildConfig.DEBUG) {
            builder.withValue(CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL,
                    CalendarContract.Calendars.CAL_ACCESS_EDITOR);
        } else {
            builder.withValue(CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL,
                    CalendarContract.Calendars.CAL_ACCESS_READ);
        }
        builder.withValue(CalendarContract.Calendars.OWNER_ACCOUNT, context.getString(R.string.app_name));

        ArrayList<ContentProviderOperation> operations = new ArrayList<>();
        operations.add(builder.build());
        try {
            cr.applyBatch(CalendarContract.AUTHORITY, operations);
            Log.d(TAG, "Created calendar " + calendarName);
        } catch (RemoteException e) {
            Log.e(TAG, "Unable to create new calendar!", e);
            return -1;
        } catch (OperationApplicationException e) {
            Log.e(TAG, "Unable to create new calendar!", e);
            return -2;
        }

        // Try once again, this time we should find something in the database
        return getCalendar(context);
    }
}

From source file:uk.co.droidinactu.ebooklauncher.EBookLauncherActivity.java

private void setupList(final HorizontialListView listview, final SimpleCursorAdapter listAdapter,
        final Cursor cursr) {
    if (cursr == null || cursr != null && cursr.getCount() == 0) {
        Toast.makeText(getApplication(), "No books available", Toast.LENGTH_LONG);
    } else {//from  w  ww. ja  v a2  s  . c  o  m
        listview.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
            @Override
            public void onCreateContextMenu(final ContextMenu conMenu, final View v,
                    final ContextMenuInfo menuInfo) {
                final LinearLayout ll = (LinearLayout) ((HorizontialListView) v)
                        .getChildAt(((AdapterContextMenuInfo) menuInfo).position);
                final Drawable bookCover = ((ImageView) ll.getChildAt(0)).getDrawable();
                final String bookTitle = ((TextView) ll.getChildAt(1)).getText().toString();
                conMenu.setHeaderIcon(bookCover); // set to book cover
                conMenu.setHeaderTitle(bookTitle); // set to book title
                conMenu.add(0, EBookLauncherActivity.CONTEXTMENU_VIEW_DETAILS, 0,
                        R.string.book_grid_context_item_view_book_details);
                conMenu.add(0, EBookLauncherActivity.CONTEXTMENU_OPEN_BOOK, 1,
                        R.string.book_grid_context_item_open_book);
                conMenu.add(0, EBookLauncherActivity.CONTEXTMENU_DELETE_BOOK, 2,
                        R.string.book_grid_context_item_delete_book);
            }
        });
        listview.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(final AdapterView<?> av, final View v, final int pos, final long id) {
                myApp.dataMdl.launchBook(EBookLauncherActivity.this, id);
            }

            @Override
            public void onNothingSelected(final AdapterView<?> arg0) {
            }
        });
        listAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
            @Override
            public boolean setViewValue(final View view, final Cursor cursor, final int columnIndex) {
                boolean retval = false;
                final int idColIndex = cursor.getColumnIndexOrThrow(BaseColumns._ID);
                final int thumbColIndex = cursor.getColumnIndexOrThrow(DeviceFactory.getCoverImgColumnName());

                if (columnIndex == idColIndex) {
                    try {
                        final ImageView coverImg = (ImageView) view;
                        final String thumbnailFilename = cursor.getString(thumbColIndex);
                        final Bitmap bitmap = myApp.dataMdl.getBookCoverImg(EBookLauncherActivity.this,
                                thumbnailFilename);
                        coverImg.setImageDrawable(new BitmapDrawable(bitmap));
                        retval = true;
                    } catch (final Exception e) {
                        Log.e(EBookLauncherApplication.LOG_TAG, EBookLauncherActivity.LOG_TAG + "Exception ",
                                e);
                    }
                    retval = true;
                }
                return retval;
            }
        });
        listview.setAdapter(listAdapter);
        registerForContextMenu(listview);
        startManagingCursor(cursr);
    }
}