List of usage examples for android.database Cursor getColumnIndexOrThrow
int getColumnIndexOrThrow(String columnName) throws IllegalArgumentException;
From source file:com.android.providers.contacts.ContactsSyncAdapter.java
private static void cursorToBaseEntry(Entry entry, String account, Cursor c) { String feedUrl;/* w w w . j a v a2s. co m*/ if (entry instanceof ContactEntry) { feedUrl = getContactsFeedForAccount(account); } else if (entry instanceof GroupEntry) { feedUrl = getGroupsFeedForAccount(account); } else if (entry instanceof MediaEntry) { feedUrl = getPhotosFeedForAccount(account); } else { throw new IllegalArgumentException("bad entry type: " + entry.getClass().getName()); } String syncId = c.getString(c.getColumnIndexOrThrow(SyncConstValue._SYNC_ID)); if (syncId != null) { String syncVersion = c.getString(c.getColumnIndexOrThrow(SyncConstValue._SYNC_VERSION)); entry.setId(feedUrl + "/" + syncId); entry.setEditUri(entry.getId() + "/" + syncVersion); } }
From source file:com.cattle.util.CursorPagerAdapter.java
void init(Context context, Cursor c, int flags) { if ((flags & FLAG_AUTO_REQUERY) == FLAG_AUTO_REQUERY) { flags |= FLAG_REGISTER_CONTENT_OBSERVER; mAutoRequery = true;//from w w w. j av a 2 s . c o m } else { mAutoRequery = false; } boolean cursorPresent = c != null; mCursor = c; mDataValid = cursorPresent; mContext = context; mRowIDColumn = cursorPresent ? c.getColumnIndexOrThrow("_id") : -1; if ((flags & FLAG_REGISTER_CONTENT_OBSERVER) == FLAG_REGISTER_CONTENT_OBSERVER) { mChangeObserver = new ChangeObserver(); mDataSetObserver = new MyDataSetObserver(); } else { mChangeObserver = null; mDataSetObserver = null; } if (cursorPresent) { if (mChangeObserver != null) { c.registerContentObserver(mChangeObserver); } if (mDataSetObserver != null) { c.registerDataSetObserver(mDataSetObserver); } } }
From source file:com.amytech.android.library.views.imagechooser.threads.MediaProcessorThread.java
@SuppressLint("NewApi") protected String getAbsoluteImagePathFromUri(Uri imageUri) { String[] proj = { MediaColumns.DATA, MediaColumns.DISPLAY_NAME }; if (BuildConfig.DEBUG) { Log.i(TAG, "Image Uri: " + imageUri.toString()); }/*from www .j a v a 2s. c o m*/ if (imageUri.toString().startsWith("content://com.android.gallery3d.provider")) { imageUri = Uri .parse(imageUri.toString().replace("com.android.gallery3d", "com.google.android.gallery3d")); } String filePath = ""; String imageUriString = imageUri.toString(); if (imageUriString.startsWith("content://com.google.android.gallery3d") || imageUriString.startsWith("content://com.google.android.apps.photos.content") || imageUriString.startsWith("content://com.android.providers.media.documents") || imageUriString.startsWith("content://com.google.android.apps.docs.storage") || imageUriString.startsWith("content://com.microsoft.skydrive.content.external")) { filePath = imageUri.toString(); } else { Cursor cursor = context.getContentResolver().query(imageUri, proj, null, null, null); cursor.moveToFirst(); filePath = cursor.getString(cursor.getColumnIndexOrThrow(MediaColumns.DATA)); cursor.close(); } if (filePath == null && isDownloadsDocument(imageUri)) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) filePath = getPath(context, imageUri); } return filePath; }
From source file:com.parking.billing.ParkingPayment.java
/** * Reads the set of purchased items from the database in a background thread * and then adds those items to the set of owned items in the main UI * thread./*from ww w .j av a2 s.c o m*/ */ private void doInitializeOwnedItems() { Cursor cursor = mPurchaseDatabase.queryAllPurchasedItems(); if (cursor == null) { return; } final Set<String> ownedItems = new HashSet<String>(); try { int productIdCol = cursor.getColumnIndexOrThrow(PurchaseDatabase.PURCHASED_PRODUCT_ID_COL); while (cursor.moveToNext()) { String productId = cursor.getString(productIdCol); ownedItems.add(productId); } } finally { cursor.close(); } // We will add the set of owned items in a new Runnable that runs on // the UI thread so that we don't need to synchronize access to // mOwnedItems. mHandler.post(new Runnable() { public void run() { mOwnedItems.addAll(ownedItems); mCatalogAdapter.setOwnedItems(mOwnedItems); } }); }
From source file:com.armtimes.drawer.CommonFragment.java
@Override public void onListItemClick(ListView l, View v, int position, long id) { // Get current selected item. Cursor cursor = ((FragmentAdapter) l.getAdapter()).getCursor(); cursor.moveToPosition(position);//from www . j a v a 2 s .c o m // Create new intent to send to News Reader Activity. Intent intent = new Intent(getActivity(), SingleArticlePreviewActivity.class); intent.putExtra(SingleArticlePreviewActivity.EXTRA_CATEGORY_TITLE_ID, mCategoryTitleId); intent.putExtra(SingleArticlePreviewActivity.EXTRA_TITLE, cursor.getString(cursor.getColumnIndexOrThrow(NewsContract.COL_NAME_NEWS_TITLE))); intent.putExtra(SingleArticlePreviewActivity.EXTRA_DESCRIPTION, cursor.getString(cursor.getColumnIndexOrThrow(NewsContract.COL_NAME_NEWS_DESC_LONG))); intent.putExtra(SingleArticlePreviewActivity.EXTRA_URL, cursor.getString(cursor.getColumnIndexOrThrow(NewsContract.COL_NAME_NEWS_URL))); intent.putExtra(SingleArticlePreviewActivity.EXTRA_IMAGE_PATH, cursor.getString(cursor.getColumnIndexOrThrow(NewsContract.COL_NAME_NEWS_MAIN_IMAGE_PATH))); intent.putExtra(SingleArticlePreviewActivity.EXTRA_IMAGE_LINK, cursor.getString(cursor.getColumnIndexOrThrow(NewsContract.COL_NAME_NEWS_IMAGE_URL))); intent.putExtra(SingleArticlePreviewActivity.EXTRA_SHORT_DESC, cursor.getString(cursor.getColumnIndexOrThrow(NewsContract.COL_NAME_NEWS_DESC_SHORT))); intent.putExtra(SingleArticlePreviewActivity.EXTRA_CATEGORY, mCategory); // Start News Reader Activity. startActivityForResult(intent, 0); }
From source file:net.olejon.mdapp.BarcodeScannerActivity.java
@Override public void handleResult(Result result) { mTools.showToast(getString(R.string.barcode_scanner_wait), 0); String barcode = result.getText(); RequestQueue requestQueue = Volley.newRequestQueue(mContext); JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, getString(R.string.project_website_uri) + "api/1/barcode/?search=" + barcode, new Response.Listener<JSONObject>() { @Override//from w ww .j ava 2s. co m public void onResponse(JSONObject response) { try { String medicationName = response.getString("name"); if (medicationName.equals("")) { mTools.showToast(getString(R.string.barcode_scanner_no_results), 1); finish(); } else { SQLiteDatabase sqLiteDatabase = new SlDataSQLiteHelper(mContext) .getReadableDatabase(); String[] queryColumns = { SlDataSQLiteHelper.MEDICATIONS_COLUMN_ID }; Cursor cursor = sqLiteDatabase.query(SlDataSQLiteHelper.TABLE_MEDICATIONS, queryColumns, SlDataSQLiteHelper.MEDICATIONS_COLUMN_NAME + " LIKE " + mTools.sqe("%" + medicationName + "%") + " COLLATE NOCASE", null, null, null, null); if (cursor.moveToFirst()) { long id = cursor.getLong( cursor.getColumnIndexOrThrow(SlDataSQLiteHelper.MEDICATIONS_COLUMN_ID)); Intent intent = new Intent(mContext, MedicationActivity.class); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { if (mTools.getDefaultSharedPreferencesBoolean( "MEDICATION_MULTIPLE_DOCUMENTS")) intent.setFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK | Intent.FLAG_ACTIVITY_NEW_DOCUMENT); } intent.putExtra("id", id); startActivity(intent); } cursor.close(); sqLiteDatabase.close(); finish(); } } catch (Exception e) { mTools.showToast(getString(R.string.barcode_scanner_no_results), 1); Log.e("BarcodeScannerActivity", Log.getStackTraceString(e)); finish(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e("FelleskatalogenService", error.toString()); } }); jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); requestQueue.add(jsonObjectRequest); }
From source file:de.baumann.hhsmoodle.data_random.Random_Fragment.java
private void setRandomList() { if (isFABOpen) { closeFABMenu();/* w ww. j ava2 s. c om*/ } //display data final int layoutstyle = R.layout.list_item_notes; int[] xml_id = new int[] { R.id.textView_title_notes, R.id.textView_des_notes, R.id.textView_create_notes }; String[] column = new String[] { "random_title", "random_content", "random_creation" }; final Cursor row = db.fetchAllData(); SimpleCursorAdapter adapter = new SimpleCursorAdapter(getActivity(), layoutstyle, row, column, xml_id, 0) { @Override public View getView(final int position, View convertView, ViewGroup parent) { View v = super.getView(position, convertView, parent); ImageView iv_icon = (ImageView) v.findViewById(R.id.icon_notes); iv_icon.setVisibility(View.GONE); return v; } }; lv.setAdapter(adapter); //onClick function lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterview, View view, int position, long id) { if (isFABOpen) { closeFABMenu(); } Cursor row2 = (Cursor) lv.getItemAtPosition(position); final String random_content = row2.getString(row2.getColumnIndexOrThrow("random_content")); final String random_title = row2.getString(row2.getColumnIndexOrThrow("random_title")); if (random_content.isEmpty()) { Snackbar.make(lv, getActivity().getString(R.string.number_enterData), Snackbar.LENGTH_LONG) .show(); } else { getActivity().setTitle(random_title); lv.setVisibility(View.GONE); lvItems.setVisibility(View.VISIBLE); try { FileOutputStream fOut = new FileOutputStream(newFile()); OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut); myOutWriter.append(random_content); myOutWriter.close(); fOut.flush(); fOut.close(); } catch (IOException e) { Log.e("Exception", "File write failed: " + e.toString()); } items = new ArrayList<>(); readItems(); setAdapter(1000); fab.setVisibility(View.GONE); fab_dice.setVisibility(View.VISIBLE); } } }); lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { if (isFABOpen) { closeFABMenu(); } Cursor row2 = (Cursor) lv.getItemAtPosition(position); final String _id = row2.getString(row2.getColumnIndexOrThrow("_id")); final String random_title = row2.getString(row2.getColumnIndexOrThrow("random_title")); final String random_content = row2.getString(row2.getColumnIndexOrThrow("random_content")); final String random_icon = row2.getString(row2.getColumnIndexOrThrow("random_icon")); final String random_attachment = row2.getString(row2.getColumnIndexOrThrow("random_attachment")); final String random_creation = row2.getString(row2.getColumnIndexOrThrow("random_creation")); final CharSequence[] options = { getString(R.string.number_edit_entry), getString(R.string.bookmark_remove_bookmark) }; new android.app.AlertDialog.Builder(getActivity()) .setPositiveButton(R.string.toast_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.cancel(); } }).setItems(options, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int item) { if (options[item].equals(getString(R.string.number_edit_entry))) { android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder( getActivity()); View dialogView = View.inflate(getActivity(), R.layout.dialog_edit_entry, null); final EditText edit_title = (EditText) dialogView .findViewById(R.id.note_title_input); edit_title.setHint(R.string.title_hint); edit_title.setText(random_title); final EditText edit_cont = (EditText) dialogView .findViewById(R.id.note_text_input); edit_cont.setHint(R.string.text_hint); edit_cont.setText(random_content); builder.setView(dialogView); builder.setTitle(R.string.number_edit_entry); builder.setPositiveButton(R.string.toast_yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String inputTitle = edit_title.getText().toString().trim(); String inputCont = edit_cont.getText().toString().trim(); db.update(Integer.parseInt(_id), inputTitle, inputCont, random_icon, random_attachment, random_creation); setRandomList(); Snackbar.make(lv, R.string.bookmark_added, Snackbar.LENGTH_SHORT).show(); } }); builder.setNegativeButton(R.string.toast_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.cancel(); } }); final android.app.AlertDialog dialog2 = builder.create(); // Display the custom alert dialog on interface dialog2.show(); helper_main.showKeyboard(getActivity(), edit_title); } if (options[item].equals(getString(R.string.bookmark_remove_bookmark))) { Snackbar snackbar = Snackbar .make(lv, R.string.note_remove_confirmation, Snackbar.LENGTH_LONG) .setAction(R.string.toast_yes, new View.OnClickListener() { @Override public void onClick(View view) { db.delete(Integer.parseInt(_id)); setRandomList(); } }); snackbar.show(); } } }).show(); return true; } }); }
From source file:com.photon.phresco.nativeapp.eshop.activity.CategoryListActivity.java
/** * Update the Category VersionNo in local database, if already exists * * @param appConf// ww w . j av a 2 s . com * @param searchCategoryVersionRow * @throws IllegalArgumentException * @throws NumberFormatException */ private void updateCategoryVersionNoInLocalDatabase(AppConfiguration appConf, Cursor searchCategoryVersionRow) { try { searchCategoryVersionRow.moveToFirst(); // Get the row id of current categoryVersionNo from SQLite db long currentRowId = searchCategoryVersionRow .getLong(searchCategoryVersionRow.getColumnIndexOrThrow(AppConfiguration.KEY_ROWID)); // Get the current categoryVersionNo from SQLite db String categoryVersionNo = searchCategoryVersionRow .getString(searchCategoryVersionRow.getColumnIndex(AppConfiguration.KEY_META_VALUE)); PhrescoLogger.info(TAG + " - Existing CategoryVersion = " + categoryVersionNo + " in local database"); PhrescoLogger.info(TAG + " - appConfigJSONObj.appVersionInfo.configVersionn = " + getAppConfigJSONObj().getAppVersionInfo().getConfigVersion()); if (Integer.parseInt(getAppConfigJSONObj().getAppVersionInfo().getConfigVersion()) != Integer .parseInt(categoryVersionNo)) { Utility.deleteDir(new File(Constants.CATEGORIES_FOLDER_PATH)); Utility.createDirectory(new File(Constants.CATEGORIES_FOLDER_PATH)); downloadCategoryImages(); appConf.updateRow(currentRowId, "category_version", String.valueOf(getAppConfigJSONObj().getAppVersionInfo().getConfigVersion())); PhrescoLogger.info(TAG + " - UPDATE CategoryVersion = " + getAppConfigJSONObj().getAppVersionInfo().getConfigVersion() + " in local database"); } searchCategoryVersionRow.close(); } catch (Exception ex) { PhrescoLogger.info(TAG + "updateCategoryVersionNoInLocalDatabase - Exception : " + ex.toString()); PhrescoLogger.warning(ex); } }
From source file:fi.mikuz.boarder.gui.internet.InternetMenu.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.internet_menu); setTitle("Internet Menu"); this.setVolumeControlStream(AudioManager.STREAM_MUSIC); mWaitDialog = new TimeoutProgressDialog(this, "Waiting for response", TAG, true); mInternetDownload = (Button) findViewById(R.id.internet_download); mInternetRegisterSettings = (Button) findViewById(R.id.internet_register_settings); mInternetLoginLogout = (Button) findViewById(R.id.internet_login_logout); mInternetUploads = (Button) findViewById(R.id.internet_uploads); mInternetFavorites = (Button) findViewById(R.id.internet_favorites); mAccountMessage = (TextView) findViewById(R.id.account_message_text); mDbHelper = new LoginDbAdapter(this); mDbHelper.open();// w w w . j a v a2 s . com mGlobalVariableDbHelper = new GlobalVariablesDbAdapter(this); mGlobalVariableDbHelper.open(); int dbTosVersion = 0; try { Cursor variableCursor = mGlobalVariableDbHelper.fetchVariable(GlobalVariablesDbAdapter.TOS_VERSION_KEY); startManagingCursor(variableCursor); dbTosVersion = variableCursor.getInt(variableCursor.getColumnIndexOrThrow(LoginDbAdapter.KEY_DATA)); } catch (SQLException e) { mGlobalVariableDbHelper.createIntVariable(GlobalVariablesDbAdapter.TOS_VERSION_KEY, 0); Log.d(TAG, "Couldn't get tosVersion", e); } catch (CursorIndexOutOfBoundsException e) { mGlobalVariableDbHelper.createIntVariable(GlobalVariablesDbAdapter.TOS_VERSION_KEY, 0); Log.d(TAG, "Couldn't get tosVersion", e); } if (dbTosVersion < mTosVersion) { AlertDialog.Builder builder = new AlertDialog.Builder(InternetMenu.this); builder.setTitle("Terms of service"); builder.setMessage("Excited to get your hands on those sweet boards? - Good.\n\n" + "There are some terms you must agree to and follow to get things rolling smoothly;\n\n" + "You may only communicate in English in the Boarder Internet service.\n\n" + "An uploaded board may contain any languages. However, if the board is not 'in English' that must be visibly stated in the description.\n\n" + "You agree to always follow applicable laws when using Boarder.\n\n" + "Pornographic and other adult only material is not allowed.\n\n" + "You must be at least 13 years old to register to the Boarder Internet service.\n\n" + "You may never transmit anything or communicate a way that can be deemed offensive.\n\n" + "Don't make cheap copies of another users boards.\n\n" + "We can use material(s) publicly shared by you as promotional material.\n\n" + "We will suspend your Boarder releated accounts and/or remove your material from the Boarder service if you behave badly."); builder.setPositiveButton("Agree", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { mGlobalVariableDbHelper.updateIntVariable(GlobalVariablesDbAdapter.TOS_VERSION_KEY, mTosVersion); } }); builder.setNegativeButton("Disagree", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { InternetMenu.this.finish(); } }); builder.setCancelable(false); builder.show(); } if (mLoginInfo == null) { try { String userId; String sessionToken; Cursor loginCursor = mDbHelper.fetchLogin(USER_ID_KEY); startManagingCursor(loginCursor); userId = loginCursor.getString(loginCursor.getColumnIndexOrThrow(LoginDbAdapter.KEY_DATA)); loginCursor = mDbHelper.fetchLogin(SESSION_TOKEN_KEY); startManagingCursor(loginCursor); sessionToken = loginCursor.getString(loginCursor.getColumnIndexOrThrow(LoginDbAdapter.KEY_DATA)); mLoginInfo = new HashMap<String, String>(); mLoginInfo.put(USER_ID_KEY, userId); mLoginInfo.put(SESSION_TOKEN_KEY, sessionToken); sendDonationInfo(); mSessionValidityChecked = false; checkSessionValidity(); } catch (CursorIndexOutOfBoundsException e) { Log.d(TAG, "Couldn't get database session info", e); mSessionValidityChecked = true; } } getVersionInfo(); // Keep under login stuff mInternetDownload.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent i = new Intent(InternetMenu.this, DownloadBoardList.class); i.putExtra(LOGIN_KEY, mLoginInfo); startActivity(i); } }); mInternetRegisterSettings.setOnClickListener(new OnClickListener() { public void onClick(View v) { if (mInternetRegisterSettings.getText().toString().equals(SETTINGS_TEXT)) { Intent i = new Intent(InternetMenu.this, Settings.class); i.putExtra(LOGIN_KEY, mLoginInfo); startActivityForResult(i, LOGIN_RETURN); } else { Intent i = new Intent(InternetMenu.this, Register.class); startActivity(i); } } }); mInternetLoginLogout.setOnClickListener(new OnClickListener() { public void onClick(View v) { startLogin(); } }); mInternetUploads.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent i = new Intent(InternetMenu.this, Uploads.class); i.putExtra(LOGIN_KEY, mLoginInfo); startActivityForResult(i, LOGIN_RETURN); } }); mInternetFavorites.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent i = new Intent(InternetMenu.this, Favorites.class); i.putExtra(LOGIN_KEY, mLoginInfo); startActivityForResult(i, LOGIN_RETURN); } }); }
From source file:com.andrew.apollo.utils.MusicUtils.java
/** * @param cursor The {@link Cursor} used to gather the list in our favorites * database/* w w w . j ava2s . c o m*/ * @return The song list for the favorite playlist */ public static long[] getSongListForFavoritesCursor(Cursor cursor) { if (cursor == null) { return sEmptyList; } final int len = cursor.getCount(); final long[] list = new long[len]; cursor.moveToFirst(); int colidx = -1; try { colidx = cursor.getColumnIndexOrThrow(FavoriteColumns.ID); } catch (final Exception ignored) { } for (int i = 0; i < len; i++) { list[i] = cursor.getLong(colidx); cursor.moveToNext(); } cursor.close(); return list; }