List of usage examples for android.database Cursor isNull
boolean isNull(int columnIndex);
true
if the value in the indicated column is null. From source file:org.lastmilehealth.collect.android.tasks.BluetoothService.java
private void instancesProcessing() { //fill db with new values String dbpath = Collect.TMP_PATH + "/instances.db"; SQLiteDatabase db = SQLiteDatabase.openDatabase(dbpath, null, SQLiteDatabase.OPEN_READONLY); Cursor cursor = db.query(InstanceProvider.INSTANCES_TABLE_NAME, null, null, null, null, null, null); Log.d("~", "cursor.getCount(): " + cursor.getCount()); cursor.moveToPosition(-1);//ww w. j a va 2 s .c om while (cursor.moveToNext()) { String newInstanceName = cursor .getString(cursor.getColumnIndex(InstanceProviderAPI.InstanceColumns.DISPLAY_NAME)); String instanceFilePath = cursor .getString(cursor.getColumnIndex(InstanceProviderAPI.InstanceColumns.INSTANCE_FILE_PATH)); String newFilePath; if (new File(instanceFilePath).exists()) { //instance with this path already exist, rare case but not impossible newFilePath = getInstanceFilePath(instanceFilePath, 1); Log.d(TAG, "instance already exists, new path: " + newFilePath); String num = newFilePath.substring(newFilePath.lastIndexOf("(") + 1, newFilePath.lastIndexOf(")")); newInstanceName += "(" + num + ")"; //Log.d(TAG, "newInstanceName: "+newInstanceName); final String fromName = instanceFilePath.substring(instanceFilePath.lastIndexOf("instances/") + 10); final String toName = newFilePath.substring(instanceFilePath.lastIndexOf("instances/") + 10); //raname file in tmp folder to prepare for copy direcory try { Log.d(TAG, "rename " + fromName + " to " + toName); org.apache.commons.io.FileUtils.copyFile(new File(Collect.TMP_PATH, fromName), new File(Collect.TMP_PATH, toName)); org.apache.commons.io.FileUtils.deleteQuietly(new File(Collect.TMP_PATH, fromName)); } catch (Exception e) { } } else { newFilePath = new File(Collect.INSTANCES_PATH, instanceFilePath.substring(instanceFilePath.lastIndexOf("/"))).getAbsolutePath(); Log.d(TAG, "not exist, new path " + newFilePath); } String submissionUri = null; if (!cursor.isNull(cursor.getColumnIndex(InstanceProviderAPI.InstanceColumns.SUBMISSION_URI))) { submissionUri = cursor .getString(cursor.getColumnIndex(InstanceProviderAPI.InstanceColumns.SUBMISSION_URI)); } //add to db with new name, it it was duplicated ContentValues values = new ContentValues(); values.put(InstanceProviderAPI.InstanceColumns.DISPLAY_NAME, newInstanceName); values.put(InstanceProviderAPI.InstanceColumns.SUBMISSION_URI, submissionUri); values.put(InstanceProviderAPI.InstanceColumns.INSTANCE_FILE_PATH, newFilePath); values.put(InstanceProviderAPI.InstanceColumns.JR_FORM_ID, cursor.getString(cursor.getColumnIndex(InstanceProviderAPI.InstanceColumns.JR_FORM_ID))); values.put(InstanceProviderAPI.InstanceColumns.JR_VERSION, cursor.getString(cursor.getColumnIndex(InstanceProviderAPI.InstanceColumns.JR_VERSION))); values.put(InstanceProviderAPI.InstanceColumns.STATUS, cursor.getString(cursor.getColumnIndex(InstanceProviderAPI.InstanceColumns.STATUS))); values.put(InstanceProviderAPI.InstanceColumns.CAN_EDIT_WHEN_COMPLETE, cursor .getString(cursor.getColumnIndex(InstanceProviderAPI.InstanceColumns.CAN_EDIT_WHEN_COMPLETE))); Log.d(TAG, "insert new instance record: " + newInstanceName + " with path :" + newFilePath); Collect.getInstance().getContentResolver().insert(InstanceProviderAPI.InstanceColumns.CONTENT_URI, values); } cursor.close(); db.close(); //copy directory after deleting metadata, clear all temporary data org.apache.commons.io.FileUtils.deleteQuietly(new File(Collect.TMP_PATH, "instances.db")); org.apache.commons.io.FileUtils.deleteQuietly(new File(Collect.ZIP_PATH)); try { org.apache.commons.io.FileUtils.copyDirectory(new File(Collect.TMP_PATH), new File(Collect.INSTANCES_PATH)); org.apache.commons.io.FileUtils.deleteDirectory(new File(Collect.TMP_PATH)); } catch (Exception e) { } }
From source file:org.totschnig.myexpenses.activity.ExpenseEdit.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.one_expense); mDateFormat = android.text.format.DateFormat.getDateFormat(this); mTimeFormat = android.text.format.DateFormat.getTimeFormat(this); setupToolbar();//from w w w . java2 s . co m mManager = getSupportLoaderManager(); //we enable it only after accountcursor has been loaded, preventing NPE when user clicks on it early configTypeButton(); mTypeButton.setEnabled(false); mCommentText = (EditText) findViewById(R.id.Comment); mTitleText = (EditText) findViewById(R.id.Title); mReferenceNumberText = (EditText) findViewById(R.id.Number); mDateButton = (Button) findViewById(R.id.DateButton); mAttachPictureButton = (ImageView) findViewById(R.id.AttachImage); mPictureViewContainer = (FrameLayout) findViewById(R.id.picture_container); mTimeButton = (Button) findViewById(R.id.TimeButton); mPayeeLabel = (TextView) findViewById(R.id.PayeeLabel); mPayeeText = (AutoCompleteTextView) findViewById(R.id.Payee); mTransferAmountText = (AmountEditText) findViewById(R.id.TranferAmount); mExchangeRate1Text = (AmountEditText) findViewById(R.id.ExchangeRate_1); mExchangeRate1Text.setFractionDigits(EXCHANGE_RATE_FRACTION_DIGITS); mExchangeRate1Text.addTextChangedListener(new LinkedExchangeRateTextWatchter(true)); mExchangeRate2Text = (AmountEditText) findViewById(R.id.ExchangeRate_2); mExchangeRate2Text.setFractionDigits(EXCHANGE_RATE_FRACTION_DIGITS); mExchangeRate2Text.addTextChangedListener(new LinkedExchangeRateTextWatchter(false)); mPayeeAdapter = new SimpleCursorAdapter(this, R.layout.support_simple_spinner_dropdown_item, null, new String[] { KEY_PAYEE_NAME }, new int[] { android.R.id.text1 }, 0); mPayeeText.setAdapter(mPayeeAdapter); mPayeeAdapter.setFilterQueryProvider(new FilterQueryProvider() { @SuppressLint("NewApi") public Cursor runQuery(CharSequence str) { if (str == null) { return null; } String search = Utils.esacapeSqlLikeExpression(Utils.normalize(str.toString())); //we accept the string at the beginning of a word String selection = KEY_PAYEE_NAME_NORMALIZED + " LIKE ? OR " + KEY_PAYEE_NAME_NORMALIZED + " LIKE ? OR " + KEY_PAYEE_NAME_NORMALIZED + " LIKE ?"; String[] selectArgs = { search + "%", "% " + search + "%", "%." + search + "%" }; return getContentResolver().query(TransactionProvider.PAYEES_URI, new String[] { KEY_ROWID, KEY_PAYEE_NAME, "(SELECT max(" + KEY_ROWID + ") FROM " + TABLE_TRANSACTIONS + " WHERE " + WHERE_NOT_SPLIT + " AND " + KEY_PAYEEID + " = " + TABLE_PAYEES + "." + KEY_ROWID + ")" }, selection, selectArgs, null); } }); mPayeeAdapter.setCursorToStringConverter(new CursorToStringConverter() { public CharSequence convertToString(Cursor cur) { return cur.getString(1); } }); mPayeeText.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Cursor c = (Cursor) mPayeeAdapter.getItem(position); if (c.moveToPosition(position)) { mTransaction.updatePayeeWithId(c.getString(1), c.getLong(0)); if (mNewInstance && mTransaction != null && !(mTransaction instanceof Template || mTransaction instanceof SplitTransaction)) { //moveToPosition should not be necessary, //but has been reported to not be positioned correctly on samsung GT-I8190N if (!c.isNull(2)) { if (PrefKey.AUTO_FILL_HINT_SHOWN.getBoolean(false)) { if (PrefKey.AUTO_FILL.getBoolean(true)) { startAutoFill(c.getLong(2)); } } else { Bundle b = new Bundle(); b.putLong(KEY_ROWID, c.getLong(2)); b.putInt(ConfirmationDialogFragment.KEY_TITLE, R.string.dialog_title_information); b.putString(ConfirmationDialogFragment.KEY_MESSAGE, getString(R.string.hint_auto_fill)); b.putInt(ConfirmationDialogFragment.KEY_COMMAND_POSITIVE, R.id.AUTO_FILL_COMMAND); b.putString(ConfirmationDialogFragment.KEY_PREFKEY, PrefKey.AUTO_FILL_HINT_SHOWN.getKey()); b.putInt(ConfirmationDialogFragment.KEY_POSITIVE_BUTTON_LABEL, R.string.yes); b.putInt(ConfirmationDialogFragment.KEY_NEGATIVE_BUTTON_LABEL, R.string.no); ConfirmationDialogFragment.newInstance(b).show(getSupportFragmentManager(), "AUTO_FILL_HINT"); } } } } } }); mCategoryButton = (Button) findViewById(R.id.Category); mPlanButton = (Button) findViewById(R.id.Plan); mMethodSpinner = (Spinner) findViewById(R.id.Method); mAccountSpinner = new SpinnerHelper(findViewById(R.id.Account)); mTransferAccountSpinner = new SpinnerHelper(findViewById(R.id.TransferAccount)); mTransferAccountSpinner.setOnItemSelectedListener(this); mStatusSpinner = new SpinnerHelper(findViewById(R.id.Status)); mReccurenceSpinner = new SpinnerHelper(findViewById(R.id.Recurrence)); mPlanToggleButton = (ToggleButton) findViewById(R.id.PlanExecutionAutomatic); TextPaint paint = mPlanToggleButton.getPaint(); int automatic = (int) paint.measureText(getString(R.string.plan_automatic)); int manual = (int) paint.measureText(getString(R.string.plan_manual)); mPlanToggleButton.setWidth((automatic > manual ? automatic : manual) + +mPlanToggleButton.getPaddingLeft() + mPlanToggleButton.getPaddingRight()); mRowId = Utils.getFromExtra(getIntent().getExtras(), KEY_ROWID, 0); //upon orientation change stored in instance state, since new splitTransactions are immediately persisted to DB if (savedInstanceState != null) { mSavedInstance = true; mRowId = savedInstanceState.getLong(KEY_ROWID); mPictureUri = savedInstanceState.getParcelable(KEY_PICTURE_URI); mPictureUriTemp = savedInstanceState.getParcelable(KEY_PICTURE_URI_TMP); setPicture(); mCalendar = (Calendar) savedInstanceState.getSerializable(KEY_CALENDAR); mLabel = savedInstanceState.getString(KEY_LABEL); if ((mCatId = savedInstanceState.getLong(KEY_CATID)) == 0L) { mCatId = null; } if ((mMethodId = savedInstanceState.getLong(KEY_METHODID)) == 0L) mMethodId = null; if ((mAccountId = savedInstanceState.getLong(KEY_ACCOUNTID)) == 0L) { mAccountId = null; } else { //once user has selected account, we no longer want //the passed in KEY_CURRENCY to override it in onLoadFinished getIntent().removeExtra(KEY_CURRENCY); } if ((mTransferAccountId = savedInstanceState.getLong(KEY_TRANSFER_ACCOUNT)) == 0L) mTransferAccountId = null; } mTemplateId = getIntent().getLongExtra(KEY_TEMPLATEID, 0); //were we called from a notification int notificationId = getIntent().getIntExtra(MyApplication.KEY_NOTIFICATION_ID, 0); if (notificationId > 0) { ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).cancel(notificationId); } CrStatusAdapter sAdapter = new CrStatusAdapter(this) { @Override public boolean isEnabled(int position) { //if the transaction is reconciled, the status can not be changed //otherwise only unreconciled and cleared can be set return mTransaction != null && mTransaction.crStatus != CrStatus.RECONCILED && position != CrStatus.RECONCILED.ordinal(); } }; mStatusSpinner.setAdapter(sAdapter); //1. fetch the transaction or create a new instance if (mRowId != 0 || mTemplateId != 0) { mNewInstance = false; int taskId; Serializable extra = null; Long objectId; if (mRowId != 0) { taskId = TaskExecutionFragment.TASK_INSTANTIATE_TRANSACTION; //if called with extra KEY_CLONE, we ask the task to clone, but no longer after orientation change extra = getIntent().getBooleanExtra(KEY_CLONE, false) && savedInstanceState == null; objectId = mRowId; } else { objectId = mTemplateId; //are we editing the template or instantiating a new one if ((mPlanInstanceId = getIntent().getLongExtra(KEY_INSTANCEID, 0)) != 0L) { taskId = TaskExecutionFragment.TASK_INSTANTIATE_TRANSACTION_FROM_TEMPLATE; mPlanInstanceDate = getIntent().getLongExtra(KEY_DATE, 0); mRecordTemplateWidget = getIntent().getBooleanExtra(AbstractWidget.EXTRA_START_FROM_WIDGET, false) && !ContribFeature.TEMPLATE_WIDGET.hasAccess(); } else { taskId = TaskExecutionFragment.TASK_INSTANTIATE_TEMPLATE; } } FragmentManager fm = getSupportFragmentManager(); if (fm.findFragmentByTag(ProtectionDelegate.ASYNC_TAG) == null) { startTaskExecution(taskId, new Long[] { objectId }, extra, R.string.progress_dialog_loading); } } else { mOperationType = getIntent().getIntExtra(MyApplication.KEY_OPERATION_TYPE, MyExpenses.TYPE_TRANSACTION); if (!isValidType(mOperationType)) { mOperationType = MyExpenses.TYPE_TRANSACTION; } if (mOperationType == MyExpenses.TYPE_SPLIT && !ContribFeature.SPLIT_TRANSACTION.hasAccess() && ContribFeature.SPLIT_TRANSACTION.usagesLeft() < 1) { Toast.makeText(this, ContribFeature.SPLIT_TRANSACTION.buildRequiresString(this), Toast.LENGTH_LONG) .show(); finish(); return; } final Long parentId = getIntent().getLongExtra(KEY_PARENTID, 0); final boolean isNewTemplate = getIntent().getBooleanExtra(KEY_NEW_TEMPLATE, false); getSupportActionBar().setDisplayShowTitleEnabled(false); View spinner = findViewById(R.id.OperationType); mOperationTypeSpinner = new SpinnerHelper(spinner); spinner.setVisibility(View.VISIBLE); List<Integer> allowedOperationTypes = new ArrayList<>(); allowedOperationTypes.add(MyExpenses.TYPE_TRANSACTION); allowedOperationTypes.add(MyExpenses.TYPE_TRANSFER); if (!isNewTemplate && parentId == 0) { allowedOperationTypes.add(MyExpenses.TYPE_SPLIT); } mOperationTypeAdapter = new OperationTypeAdapter(this, allowedOperationTypes, isNewTemplate, parentId != 0); mOperationTypeSpinner.setAdapter(mOperationTypeAdapter); resetOperationType(); mOperationTypeSpinner.setOnItemSelectedListener(this); Long accountId = getIntent().getLongExtra(KEY_ACCOUNTID, 0); if (isNewTemplate) { mTransaction = Template.getTypedNewInstance(mOperationType, accountId); } else { switch (mOperationType) { case MyExpenses.TYPE_TRANSACTION: if (accountId == 0L) { accountId = MyApplication.getInstance().getSettings() .getLong(PREFKEY_TRANSACTION_LAST_ACCOUNT_FROM_WIDGET, 0L); } mTransaction = parentId == 0L ? Transaction.getNewInstance(accountId) : SplitPartCategory.getNewInstance(accountId, parentId); break; case MyExpenses.TYPE_TRANSFER: Long transfer_account = 0L; if (accountId == 0L) { accountId = MyApplication.getInstance().getSettings() .getLong(PREFKEY_TRANSFER_LAST_ACCOUNT_FROM_WIDGET, 0L); transfer_account = MyApplication.getInstance().getSettings() .getLong(PREFKEY_TRANSFER_LAST_TRANSFER_ACCOUNT_FROM_WIDGET, 0L); } mTransaction = parentId == 0L ? Transfer.getNewInstance(accountId, transfer_account) : SplitPartTransfer.getNewInstance(accountId, parentId, transfer_account); break; case MyExpenses.TYPE_SPLIT: if (accountId == 0L) { accountId = MyApplication.getInstance().getSettings() .getLong(PREFKEY_SPLIT_LAST_ACCOUNT_FROM_WIDGET, 0L); } mTransaction = SplitTransaction.getNewInstance(accountId); //Split transactions are returned persisted to db and already have an id if (mTransaction != null) { mRowId = mTransaction.getId(); } break; } } if (mTransaction == null) { String errMsg = "Error instantiating transaction for account " + accountId; AcraHelper.report(new IllegalStateException(errMsg), "Extras", getIntent().getExtras().toString()); Toast.makeText(this, errMsg, Toast.LENGTH_SHORT).show(); finish(); return; } if (!mSavedInstance) { //processing data from user switching operation type Transaction cached = (Transaction) getIntent().getSerializableExtra(KEY_CACHED_DATA); if (cached != null) { mTransaction.accountId = cached.accountId; mCalendar.setTime(cached.getDate()); mPictureUri = getIntent().getParcelableExtra(KEY_CACHED_PICTURE_URI); setPicture(); mTransaction.methodId = cached.methodId; } } setup(); } }
From source file:org.opendatakit.services.forms.provider.FormsProvider.java
@Override public synchronized int update(@NonNull Uri uri, ContentValues values, String where, String[] whereArgs) { possiblyWaitForContentProviderDebugger(); List<String> segments = uri.getPathSegments(); PatchedFilter pf = extractUriFeatures(uri, segments, where, whereArgs); WebLoggerIf logger = WebLogger.getLogger(pf.appName); /*/*w w w . j a va2s. c o m*/ * First, find out what records match this query. Replicate the * ContentValues if there are multiple tableIds/formIds involved * and the contentValues do not have formId and tableId specified. * * Otherwise, it is an error to specify the tableId or formId in * the ContentValues and have those not match the where results. * */ String contentTableId = (values != null && values.containsKey(FormsColumns.TABLE_ID)) ? values.getAsString(FormsColumns.TABLE_ID) : null; String contentFormId = (values != null && values.containsKey(FormsColumns.FORM_ID)) ? values.getAsString(FormsColumns.FORM_ID) : null; HashMap<FormSpec, HashMap<String, Object>> matchedValues = new HashMap<FormSpec, HashMap<String, Object>>(); DbHandle dbHandleName = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface() .generateInternalUseDbHandle(); OdkConnectionInterface db = null; try { // +1 referenceCount if db is returned (non-null) db = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().getConnection(pf.appName, dbHandleName); db.beginTransactionNonExclusive(); Cursor c = null; try { c = db.query(DatabaseConstants.FORMS_TABLE_NAME, null, pf.whereId, pf.whereIdArgs, null, null, null, null); if (c == null) { throw new SQLException( "FAILED Update of " + uri + " -- query for existing row did not return a cursor"); } if (c.moveToFirst()) { int idxId = c.getColumnIndex(FormsColumns._ID); int idxTableId = c.getColumnIndex(FormsColumns.TABLE_ID); int idxFormId = c.getColumnIndex(FormsColumns.FORM_ID); Integer idValue = null; String tableIdValue = null; String formIdValue = null; do { idValue = CursorUtils.getIndexAsType(c, Integer.class, idxId); tableIdValue = CursorUtils.getIndexAsString(c, idxTableId); formIdValue = CursorUtils.getIndexAsString(c, idxFormId); if (contentTableId != null && !contentTableId.equals(tableIdValue)) { throw new SQLException("Modification of tableId for an existing form is prohibited"); } if (contentFormId != null && !contentFormId.equals(formIdValue)) { throw new SQLException("Modification of formId for an existing form is prohibited"); } HashMap<String, Object> cv = new HashMap<String, Object>(); if (values != null) { for (String key : values.keySet()) { cv.put(key, values.get(key)); } } cv.put(FormsColumns.TABLE_ID, tableIdValue); cv.put(FormsColumns.FORM_ID, formIdValue); for (int idx = 0; idx < c.getColumnCount(); ++idx) { String colName = c.getColumnName(idx); if (colName.equals(FormsColumns._ID)) { // don't insert the PK continue; } if (c.isNull(idx)) { cv.put(colName, null); } else { // everything else, we control... Class<?> dataType = CursorUtils.getIndexDataType(c, idx); if (dataType == String.class) { cv.put(colName, CursorUtils.getIndexAsString(c, idx)); } else if (dataType == Long.class) { cv.put(colName, CursorUtils.getIndexAsType(c, Long.class, idx)); } else if (dataType == Double.class) { cv.put(colName, CursorUtils.getIndexAsType(c, Double.class, idx)); } } } FormSpec formSpec = patchUpValues(pf.appName, cv); formSpec._id = idValue.toString(); formSpec.success = false; matchedValues.put(formSpec, cv); } while (c.moveToNext()); } else { // no match on where clause... return 0; } } finally { if (c != null && !c.isClosed()) { c.close(); } } // go through the entries and update the database with these patched-up values... for (Entry<FormSpec, HashMap<String, Object>> e : matchedValues.entrySet()) { FormSpec fs = e.getKey(); HashMap<String, Object> cv = e.getValue(); if (db.update(DatabaseConstants.FORMS_TABLE_NAME, cv, FormsColumns._ID + "=?", new String[] { fs._id }) > 0) { fs.success = true; } } db.setTransactionSuccessful(); } catch (Exception e) { logger.w(t, "FAILED Update of " + uri + " -- query for existing row failed: " + e.toString()); if (e instanceof SQLException) { throw (SQLException) e; } else { throw new SQLException( "FAILED Update of " + uri + " -- query for existing row failed: " + e.toString()); } } finally { if (db != null) { try { if (db.inTransaction()) { db.endTransaction(); } } finally { try { db.releaseReference(); } finally { // this closes the connection OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface() .removeConnection(pf.appName, dbHandleName); } } } } int failureCount = 0; for (FormSpec fs : matchedValues.keySet()) { if (fs.success) { Uri formUri = Uri .withAppendedPath( Uri.withAppendedPath(Uri.withAppendedPath( Uri.parse("content://" + getFormsAuthority()), pf.appName), fs.tableId), fs.formId); getContext().getContentResolver().notifyChange(formUri, null); Uri idUri = Uri.withAppendedPath( Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), pf.appName), fs._id); getContext().getContentResolver().notifyChange(idUri, null); } else { ++failureCount; } } getContext().getContentResolver().notifyChange(uri, null); int count = matchedValues.size(); if (failureCount != 0) { throw new SQLiteException( "Unable to update all forms (" + (count - failureCount) + " of " + count + " updated)"); } return count; }
From source file:net.fred.feedex.adapter.EntriesCursorAdapter.java
@Override public void bindView(View view, final Context context, Cursor cursor) { if (view.getTag(R.id.holder) == null) { ViewHolder holder = new ViewHolder(); holder.titleTextView = (TextView) view.findViewById(android.R.id.text1); holder.dateTextView = (TextView) view.findViewById(android.R.id.text2); holder.mainImgView = (ImageView) view.findViewById(R.id.main_icon); holder.starImgView = (ImageView) view.findViewById(R.id.favorite_icon); view.setTag(R.id.holder, holder); }/*from www . j a v a 2s .c o m*/ final ViewHolder holder = (ViewHolder) view.getTag(R.id.holder); String titleText = cursor.getString(mTitlePos); holder.titleTextView.setText(titleText); final long feedId = cursor.getLong(mFeedIdPos); String feedName = cursor.getString(mFeedNamePos); String mainImgUrl = cursor.getString(mMainImgPos); mainImgUrl = TextUtils.isEmpty(mainImgUrl) ? null : NetworkUtils.getDownloadedOrDistantImageUrl(cursor.getLong(mIdPos), mainImgUrl); ColorGenerator generator = ColorGenerator.DEFAULT; int color = generator.getColor(feedId); // The color is specific to the feedId (which shouldn't change) String lettersForName = feedName != null ? (feedName.length() < 2 ? feedName.toUpperCase() : feedName.substring(0, 2).toUpperCase()) : ""; TextDrawable letterDrawable = TextDrawable.builder().buildRound(lettersForName, color); if (mainImgUrl != null) { Glide.with(context).load(mainImgUrl).asBitmap().centerCrop().placeholder(letterDrawable) .error(letterDrawable).into(new BitmapImageViewTarget(holder.mainImgView) { @Override protected void setResource(Bitmap resource) { RoundedBitmapDrawable circularBitmapDrawable = RoundedBitmapDrawableFactory .create(context.getResources(), resource); circularBitmapDrawable.setCircular(true); getView().setImageDrawable(circularBitmapDrawable); } }); } else { Glide.clear(holder.mainImgView); holder.mainImgView.setImageDrawable(letterDrawable); } holder.isFavorite = cursor.getInt(mFavoritePos) == 1; holder.starImgView.setVisibility(holder.isFavorite ? View.VISIBLE : View.INVISIBLE); if (mShowFeedInfo && mFeedNamePos > -1) { if (feedName != null) { holder.dateTextView.setText(Html.fromHtml("<font color='#247ab0'>" + feedName + "</font>" + Constants.COMMA_SPACE + StringUtils.getDateTimeString(cursor.getLong(mDatePos)))); } else { holder.dateTextView.setText(StringUtils.getDateTimeString(cursor.getLong(mDatePos))); } } else { holder.dateTextView.setText(StringUtils.getDateTimeString(cursor.getLong(mDatePos))); } if (cursor.isNull(mIsReadPos)) { holder.titleTextView.setEnabled(true); holder.dateTextView.setEnabled(true); holder.isRead = false; } else { holder.titleTextView.setEnabled(false); holder.dateTextView.setEnabled(false); holder.isRead = true; } }
From source file:net.etuldan.sparss.fragment.EntryFragment.java
@Override public boolean onOptionsItemSelected(MenuItem item) { if (mEntriesIds != null) { final Activity activity = getActivity(); switch (item.getItemId()) { case R.id.menu_star: { mFavorite = !mFavorite;//from ww w .j a v a2 s. c o m if (mFavorite) { item.setTitle(R.string.menu_unstar).setIcon(R.drawable.ic_star); } else { item.setTitle(R.string.menu_star).setIcon(R.drawable.ic_star_border); } final Uri uri = ContentUris.withAppendedId(mBaseUri, mEntriesIds[mCurrentPagerPos]); new Thread() { @Override public void run() { ContentValues values = new ContentValues(); values.put(EntryColumns.IS_FAVORITE, mFavorite ? 1 : 0); ContentResolver cr = MainApplication.getContext().getContentResolver(); cr.update(uri, values, null, null); // Update the cursor Cursor updatedCursor = cr.query(uri, null, null, null, null); updatedCursor.moveToFirst(); mEntryPagerAdapter.setUpdatedCursor(mCurrentPagerPos, updatedCursor); } }.start(); break; } case R.id.menu_share: { Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos); if (cursor != null) { String link = cursor.getString(mLinkPos); if (link != null) { String title = cursor.getString(mTitlePos); startActivity(Intent.createChooser( new Intent(Intent.ACTION_SEND).putExtra(Intent.EXTRA_SUBJECT, title) .putExtra(Intent.EXTRA_TEXT, link).setType(Constants.MIMETYPE_TEXT_PLAIN), getString(R.string.menu_share))); } } break; } case R.id.menu_full_screen: { setImmersiveFullScreen(true); break; } case R.id.menu_copy_clipboard: { Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos); String link = cursor.getString(mLinkPos); ClipboardManager clipboard = (ClipboardManager) activity .getSystemService(Context.CLIPBOARD_SERVICE); ClipData clip = ClipData.newPlainText("Copied Text", link); clipboard.setPrimaryClip(clip); Toast.makeText(activity, R.string.copied_clipboard, Toast.LENGTH_SHORT).show(); break; } case R.id.menu_mark_as_unread: { final Uri uri = ContentUris.withAppendedId(mBaseUri, mEntriesIds[mCurrentPagerPos]); new Thread() { @Override public void run() { ContentResolver cr = MainApplication.getContext().getContentResolver(); cr.update(uri, FeedData.getUnreadContentValues(), null, null); } }.start(); activity.finish(); break; } case R.id.menu_open_in_browser: { Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos); if (cursor != null) { String link = cursor.getString(mLinkPos); if (link != null) { Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(link)); startActivity(browserIntent); } } break; } case R.id.menu_switch_full_original: { isChecked = !item.isChecked(); item.setChecked(isChecked); if (mPreferFullText) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { mPreferFullText = false; mEntryPagerAdapter.displayEntry(mCurrentPagerPos, null, true); } }); } else { Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos); final boolean alreadyMobilized = !cursor.isNull(mMobilizedHtmlPos); if (alreadyMobilized) { activity.runOnUiThread(new Runnable() { @Override public void run() { mPreferFullText = true; mEntryPagerAdapter.displayEntry(mCurrentPagerPos, null, true); } }); } else if (!isRefreshing()) { ConnectivityManager connectivityManager = (ConnectivityManager) activity .getSystemService(Context.CONNECTIVITY_SERVICE); final NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); // since we have acquired the networkInfo, we use it for basic checks if (networkInfo != null && networkInfo.getState() == NetworkInfo.State.CONNECTED) { FetcherService.addEntriesToMobilize(new long[] { mEntriesIds[mCurrentPagerPos] }); activity.startService(new Intent(activity, FetcherService.class) .setAction(FetcherService.ACTION_MOBILIZE_FEEDS)); activity.runOnUiThread(new Runnable() { @Override public void run() { showSwipeProgress(); } }); } else { activity.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(activity, R.string.network_error, Toast.LENGTH_SHORT).show(); } }); } } } break; } default: break; } } return super.onOptionsItemSelected(item); }
From source file:edu.mit.mobile.android.locast.data.Sync.java
/** * Given a live cursor pointing to a data item and/or a set of contentValues loaded from the network, * attempt to sync.//from www. j ava 2s . co m * Either c or cvNet can be null, but not both. * @param c A cursor pointing to the data item. Null is OK here. * @param jsonObject JSON object for the item as loaded from the network. null is OK here. * @param sync An empty JsonSyncableItem object. * @param publicPath TODO * * @return True if the item has been modified on either end. * @throws IOException */ private boolean syncItem(Uri toSync, Cursor c, JSONObject jsonObject, JsonSyncableItem sync, SyncProgressNotifier syncProgress, String publicPath) throws SyncException, IOException { boolean modified = false; boolean needToCloseCursor = false; boolean toSyncIsIndex = false; final SyncMap syncMap = sync.getSyncMap(); Uri locUri = null; final Uri origToSync = toSync; ContentValues cvNet = null; final Context context = getApplicationContext(); final ContentResolver cr = context.getContentResolver(); if (jsonObject != null) { if ("http".equals(toSync.getScheme()) || "https".equals(toSync.getScheme())) { // we successfully loaded it from the 'net, but toSync is really for local URIs. Erase it. toSync = sync.getContentUri(); if (toSync == null) { if (DEBUG) { Log.w(TAG, "cannot get local URI for " + origToSync + ". Skipping..."); } return false; } } try { cvNet = JsonSyncableItem.fromJSON(context, null, jsonObject, syncMap); } catch (final Exception e) { final SyncException se = new SyncException("Problem loading JSON object."); se.initCause(e); throw se; } } final String contentType = cr.getType(toSync); if (c != null) { if (contentType.startsWith(CONTENT_TYPE_PREFIX_DIR)) { locUri = ContentUris.withAppendedId(toSync, c.getLong(c.getColumnIndex(JsonSyncableItem._ID))) .buildUpon().query(null).build(); toSyncIsIndex = true; } else { locUri = toSync; } // skip any items already sync'd if (mLastUpdated.isUpdatedRecently(locUri)) { return false; } final int draftCol = c.getColumnIndex(TaggableItem._DRAFT); if (draftCol != -1 && c.getInt(draftCol) != 0) { if (DEBUG) { Log.d(TAG, locUri + " is marked a draft. Not syncing."); } return false; } syncMap.onPreSyncItem(cr, locUri, c); } else if (contentType.startsWith(CONTENT_TYPE_PREFIX_DIR)) { // strip any query strings toSync = toSync.buildUpon().query(null).build(); } // if (c != null){ // MediaProvider.dumpCursorToLog(c, sync.getFullProjection()); // } // when the PUBLIC_URI is null, that means it's only local final int pubUriColumn = (c != null) ? c.getColumnIndex(JsonSyncableItem._PUBLIC_URI) : -1; if (c != null && (c.isNull(pubUriColumn) || c.getString(pubUriColumn) == "")) { // new content on the local side only. Gotta publish. try { jsonObject = JsonSyncableItem.toJSON(context, locUri, c, syncMap); if (publicPath == null) { publicPath = MediaProvider.getPostPath(this, locUri); } if (DEBUG) { Log.d(TAG, "Posting " + locUri + " to " + publicPath); } // The response from a post to create a new item should be the newly created item, // which contains the public ID that we need. jsonObject = nc.postJson(publicPath, jsonObject); final ContentValues cvUpdate = JsonSyncableItem.fromJSON(context, locUri, jsonObject, syncMap); if (cr.update(locUri, cvUpdate, null, null) == 1) { // at this point, server and client should be in sync. mLastUpdated.markUpdated(locUri); if (DEBUG) { Log.i(TAG, "Hooray! " + locUri + " has been posted succesfully."); } } else { Log.e(TAG, "update of " + locUri + " failed"); } modified = true; } catch (final Exception e) { final SyncException se = new SyncException(getString(R.string.error_sync_no_post)); se.initCause(e); throw se; } // only on the remote side, so pull it in. } else if (c == null && cvNet != null) { if (DEBUG) { Log.i(TAG, "Only on the remote side, using network-provided values."); } final String[] params = { cvNet.getAsString(JsonSyncableItem._PUBLIC_URI) }; c = cr.query(toSync, sync.getFullProjection(), JsonSyncableItem._PUBLIC_URI + "=?", params, null); needToCloseCursor = true; if (!c.moveToFirst()) { locUri = cr.insert(toSync, cvNet); modified = true; } else { locUri = ContentUris.withAppendedId(toSync, c.getLong(c.getColumnIndex(JsonSyncableItem._ID))) .buildUpon().query(null).build(); syncMap.onPreSyncItem(cr, locUri, c); } } // we've now found data on both sides, so sync them. if (!modified && c != null) { publicPath = c.getString(c.getColumnIndex(JsonSyncableItem._PUBLIC_URI)); try { if (cvNet == null) { try { if (publicPath == null && toSyncIsIndex && !MediaProvider.canSync(locUri)) { // At this point, we've already checked the index and it doesn't contain the item (otherwise it would be in the syncdItems). // If we can't sync individual items, it's possible that the index is paged or the item has been deleted. if (DEBUG) { Log.w(TAG, "Asked to sync " + locUri + " but item wasn't in server index and cannot sync individual entries. Skipping and hoping it is up to date."); } return false; } else { if (mLastUpdated.isUpdatedRecently(nc.getFullUri(publicPath))) { if (DEBUG) { Log.d(TAG, "already sync'd! " + publicPath); } return false; } if (jsonObject == null) { jsonObject = nc.getObject(publicPath); } cvNet = JsonSyncableItem.fromJSON(context, locUri, jsonObject, syncMap); } } catch (final HttpResponseException hre) { if (hre.getStatusCode() == HttpStatus.SC_NOT_FOUND) { final SyncItemDeletedException side = new SyncItemDeletedException(locUri); side.initCause(hre); throw side; } } } if (cvNet == null) { Log.e(TAG, "got null values from fromJSON() on item " + locUri + ": " + (jsonObject != null ? jsonObject.toString() : "<< no json object >>")); return false; } final Date netLastModified = new Date(cvNet.getAsLong(JsonSyncableItem._MODIFIED_DATE)); final Date locLastModified = new Date(c.getLong(c.getColumnIndex(JsonSyncableItem._MODIFIED_DATE))); if (netLastModified.equals(locLastModified)) { // same! yay! We don't need to do anything. if (DEBUG) { Log.d("LocastSync", locUri + " doesn't need to sync."); } } else if (netLastModified.after(locLastModified)) { // remote is more up to date, update! cr.update(locUri, cvNet, null, null); if (DEBUG) { Log.d("LocastSync", cvNet + " is newer than " + locUri); } modified = true; } else if (netLastModified.before(locLastModified)) { // local is more up to date, propagate! jsonObject = nc.putJson(publicPath, JsonSyncableItem.toJSON(context, locUri, c, syncMap)); if (DEBUG) { Log.d("LocastSync", cvNet + " is older than " + locUri); } modified = true; } mLastUpdated.markUpdated(nc.getFullUri(publicPath)); } catch (final JSONException e) { final SyncException se = new SyncException( "Item sync error for path " + publicPath + ": invalid JSON."); se.initCause(e); throw se; } catch (final NetworkProtocolException e) { final SyncException se = new SyncException( "Item sync error for path " + publicPath + ": " + e.getHttpResponseMessage()); se.initCause(e); throw se; } finally { if (needToCloseCursor) { c.close(); needToCloseCursor = false; } } } if (needToCloseCursor) { c.close(); } if (locUri == null) { throw new RuntimeException("Never got a local URI for a sync'd item."); } // two calls are made in two different contexts. Which context you use depends on the application. syncMap.onPostSyncItem(context, locUri, jsonObject, modified); sync.onPostSyncItem(context, locUri, jsonObject, modified); mLastUpdated.markUpdated(locUri); // needed for things that may have requested a sync with a different URI than what was eventually produced. if (origToSync != locUri) { mLastUpdated.markUpdated(origToSync); cr.notifyChange(origToSync, null); } return modified; }
From source file:net.news.inrss.fragment.EntryFragment.java
@Override public boolean onOptionsItemSelected(MenuItem item) { if (mEntriesIds != null) { final Activity activity = getActivity(); switch (item.getItemId()) { case R.id.menu_star: { mFavorite = !mFavorite;/*from www . j av a 2 s .c o m*/ if (mFavorite) { item.setTitle(R.string.menu_unstar).setIcon(R.drawable.ic_star); } else { item.setTitle(R.string.menu_star).setIcon(R.drawable.ic_star_border); } final Uri uri = ContentUris.withAppendedId(mBaseUri, mEntriesIds[mCurrentPagerPos]); new Thread() { @Override public void run() { ContentValues values = new ContentValues(); values.put(EntryColumns.IS_FAVORITE, mFavorite ? 1 : 0); ContentResolver cr = MainApplication.getContext().getContentResolver(); cr.update(uri, values, null, null); // Update the cursor Cursor updatedCursor = cr.query(uri, null, null, null, null); updatedCursor.moveToFirst(); mEntryPagerAdapter.setUpdatedCursor(mCurrentPagerPos, updatedCursor); } }.start(); break; } case R.id.menu_share: { Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos); if (cursor != null) { String link = cursor.getString(mLinkPos); if (link != null) { String title = cursor.getString(mTitlePos); startActivity(Intent.createChooser( new Intent(Intent.ACTION_SEND).putExtra(Intent.EXTRA_SUBJECT, title) .putExtra(Intent.EXTRA_TEXT, link).setType(Constants.MIMETYPE_TEXT_PLAIN), getString(R.string.menu_share))); } } break; } case R.id.menu_full_screen: { setImmersiveFullScreen(true); break; } case R.id.menu_copy_clipboard: { Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos); String link = cursor.getString(mLinkPos); ClipboardManager clipboard = (ClipboardManager) activity .getSystemService(Context.CLIPBOARD_SERVICE); ClipData clip = ClipData.newPlainText("Copied Text", link); clipboard.setPrimaryClip(clip); Toast.makeText(activity, R.string.copied_clipboard, Toast.LENGTH_SHORT).show(); break; } case R.id.menu_mark_as_unread: { final Uri uri = ContentUris.withAppendedId(mBaseUri, mEntriesIds[mCurrentPagerPos]); new Thread() { @Override public void run() { ContentResolver cr = MainApplication.getContext().getContentResolver(); cr.update(uri, FeedData.getUnreadContentValues(), null, null); } }.start(); activity.finish(); break; } case R.id.menu_open_in_browser: { Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos); if (cursor != null) { String link = cursor.getString(mLinkPos); if (link != null) { Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(link)); startActivity(browserIntent); } } break; } case R.id.menu_switch_full_original: { if (mPreferFullText) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { mPreferFullText = false; Log.d(TAG, "run: manual call of displayEntry(), fullText=false"); mEntryPagerAdapter.displayEntry(mCurrentPagerPos, null, true); } }); } else { Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos); final boolean alreadyMobilized = !cursor.isNull(mMobilizedHtmlPos); if (alreadyMobilized) { Log.d(TAG, "onOptionsItemSelected: alreadyMobilized"); mPreferFullText = true; activity.runOnUiThread(new Runnable() { @Override public void run() { Log.d(TAG, "run: manual call of displayEntry(), fullText=true"); mEntryPagerAdapter.displayEntry(mCurrentPagerPos, null, true); } }); } else if (!isRefreshing()) { Log.d(TAG, "onOptionsItemSelected: about to load article..."); mPreferFullText = false; ConnectivityManager connectivityManager = (ConnectivityManager) activity .getSystemService(Context.CONNECTIVITY_SERVICE); final NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); // since we have acquired the networkInfo, we use it for basic checks if (networkInfo != null && networkInfo.getState() == NetworkInfo.State.CONNECTED) { FetcherService.addEntriesToMobilize(new long[] { mEntriesIds[mCurrentPagerPos] }); activity.startService(new Intent(activity, FetcherService.class) .setAction(FetcherService.ACTION_MOBILIZE_FEEDS)); } else { activity.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(activity, R.string.network_error, Toast.LENGTH_SHORT).show(); } }); Log.d(TAG, "onOptionsItemSelected: cannot load article. no internet connection."); } } else { Log.d(TAG, "onOptionsItemSelected: refreshing already in progress"); } } mShowFullContentItem.setChecked(mPreferFullText); break; } default: break; } } return super.onOptionsItemSelected(item); }
From source file:org.odk.collect.android.activities.FormEntryActivity.java
/** * Called when the activity is first created. *///from w w w. ja va 2 s . c o m @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // must be at the beginning of any activity that can be called from an // external intent try { Collect.createODKDirs(); } catch (RuntimeException e) { createErrorDialog(e.getMessage(), EXIT); return; } setContentView(R.layout.form_entry); formsDao = new FormsDao(); errorMessage = null; beenSwiped = false; alertDialog = null; currentView = null; inAnimation = null; outAnimation = null; gestureDetector = new GestureDetector(this, this); questionHolder = (LinearLayout) findViewById(R.id.questionholder); hasHardwareMenu = ViewConfigurationCompat .hasPermanentMenuKey(ViewConfiguration.get(getApplicationContext())); // get admin preference settings adminPreferences = getSharedPreferences(AdminPreferencesActivity.ADMIN_PREFERENCES, 0); initToolbar(); nextButton = (ImageButton) findViewById(R.id.form_forward_button); nextButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { beenSwiped = true; showNextView(); } }); backButton = (ImageButton) findViewById(R.id.form_back_button); backButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { beenSwiped = true; showPreviousView(); } }); String startingXPath = null; String waitingXPath = null; String instancePath = null; Boolean newForm = true; autoSaved = false; if (savedInstanceState != null) { if (savedInstanceState.containsKey(KEY_FORMPATH)) { formPath = savedInstanceState.getString(KEY_FORMPATH); } if (savedInstanceState.containsKey(KEY_INSTANCEPATH)) { instancePath = savedInstanceState.getString(KEY_INSTANCEPATH); } if (savedInstanceState.containsKey(KEY_XPATH)) { startingXPath = savedInstanceState.getString(KEY_XPATH); Timber.i("startingXPath is: %s", startingXPath); } if (savedInstanceState.containsKey(KEY_XPATH_WAITING_FOR_DATA)) { waitingXPath = savedInstanceState.getString(KEY_XPATH_WAITING_FOR_DATA); Timber.i("waitingXPath is: %s", waitingXPath); } if (savedInstanceState.containsKey(NEWFORM)) { newForm = savedInstanceState.getBoolean(NEWFORM, true); } if (savedInstanceState.containsKey(KEY_ERROR)) { errorMessage = savedInstanceState.getString(KEY_ERROR); } if (savedInstanceState.containsKey(KEY_AUTO_SAVED)) { autoSaved = savedInstanceState.getBoolean(KEY_AUTO_SAVED); } } // If a parse error message is showing then nothing else is loaded // Dialogs mid form just disappear on rotation. if (errorMessage != null) { createErrorDialog(errorMessage, EXIT); return; } // Check to see if this is a screen flip or a new form load. Object data = getLastCustomNonConfigurationInstance(); if (data instanceof FormLoaderTask) { formLoaderTask = (FormLoaderTask) data; } else if (data instanceof SaveToDiskTask) { saveToDiskTask = (SaveToDiskTask) data; } else if (data == null) { if (!newForm) { if (Collect.getInstance().getFormController() != null) { refreshCurrentView(); } else { Timber.w("Reloading form and restoring state."); // we need to launch the form loader to load the form // controller... formLoaderTask = new FormLoaderTask(instancePath, startingXPath, waitingXPath); Collect.getInstance().getActivityLogger().logAction(this, "formReloaded", formPath); // TODO: this doesn' work (dialog does not get removed): // showDialog(PROGRESS_DIALOG); // show dialog before we execute... formLoaderTask.execute(formPath); } return; } // Not a restart from a screen orientation change (or other). Collect.getInstance().setFormController(null); supportInvalidateOptionsMenu(); Intent intent = getIntent(); if (intent != null) { Uri uri = intent.getData(); if (uri != null && getContentResolver().getType(uri).equals(InstanceColumns.CONTENT_ITEM_TYPE)) { // get the formId and version for this instance... String jrFormId = null; String jrVersion = null; { Cursor instanceCursor = null; try { instanceCursor = getContentResolver().query(uri, null, null, null, null); if (instanceCursor.getCount() != 1) { this.createErrorDialog(getString(R.string.bad_uri, uri), EXIT); return; } else { instanceCursor.moveToFirst(); instancePath = instanceCursor.getString( instanceCursor.getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH)); Collect.getInstance().getActivityLogger().logAction(this, "instanceLoaded", instancePath); jrFormId = instanceCursor .getString(instanceCursor.getColumnIndex(InstanceColumns.JR_FORM_ID)); int idxJrVersion = instanceCursor.getColumnIndex(InstanceColumns.JR_VERSION); jrVersion = instanceCursor.isNull(idxJrVersion) ? null : instanceCursor.getString(idxJrVersion); } } finally { if (instanceCursor != null) { instanceCursor.close(); } } } String[] selectionArgs; String selection; if (jrVersion == null) { selectionArgs = new String[] { jrFormId }; selection = FormsColumns.JR_FORM_ID + "=? AND " + FormsColumns.JR_VERSION + " IS NULL"; } else { selectionArgs = new String[] { jrFormId, jrVersion }; selection = FormsColumns.JR_FORM_ID + "=? AND " + FormsColumns.JR_VERSION + "=?"; } { Cursor formCursor = null; try { formCursor = formsDao.getFormsCursor(selection, selectionArgs); if (formCursor.getCount() == 1) { formCursor.moveToFirst(); formPath = formCursor .getString(formCursor.getColumnIndex(FormsColumns.FORM_FILE_PATH)); } else if (formCursor.getCount() < 1) { this.createErrorDialog( getString(R.string.parent_form_not_present, jrFormId) + ((jrVersion == null) ? "" : "\n" + getString(R.string.version) + " " + jrVersion), EXIT); return; } else if (formCursor.getCount() > 1) { // still take the first entry, but warn that // there are multiple rows. // user will need to hand-edit the SQLite // database to fix it. formCursor.moveToFirst(); formPath = formCursor .getString(formCursor.getColumnIndex(FormsColumns.FORM_FILE_PATH)); this.createErrorDialog(getString(R.string.survey_multiple_forms_error), EXIT); return; } } finally { if (formCursor != null) { formCursor.close(); } } } } else if (uri != null && getContentResolver().getType(uri).equals(FormsColumns.CONTENT_ITEM_TYPE)) { Cursor c = null; try { c = getContentResolver().query(uri, null, null, null, null); if (c.getCount() != 1) { this.createErrorDialog(getString(R.string.bad_uri, uri), EXIT); return; } else { c.moveToFirst(); formPath = c.getString(c.getColumnIndex(FormsColumns.FORM_FILE_PATH)); // This is the fill-blank-form code path. // See if there is a savepoint for this form that // has never been // explicitly saved // by the user. If there is, open this savepoint // (resume this filled-in // form). // Savepoints for forms that were explicitly saved // will be recovered // when that // explicitly saved instance is edited via // edit-saved-form. final String filePrefix = formPath.substring(formPath.lastIndexOf('/') + 1, formPath.lastIndexOf('.')) + "_"; final String fileSuffix = ".xml.save"; File cacheDir = new File(Collect.CACHE_PATH); File[] files = cacheDir.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { String name = pathname.getName(); return name.startsWith(filePrefix) && name.endsWith(fileSuffix); } }); // see if any of these savepoints are for a // filled-in form that has never been // explicitly saved by the user... for (int i = 0; i < files.length; ++i) { File candidate = files[i]; String instanceDirName = candidate.getName().substring(0, candidate.getName().length() - fileSuffix.length()); File instanceDir = new File( Collect.INSTANCES_PATH + File.separator + instanceDirName); File instanceFile = new File(instanceDir, instanceDirName + ".xml"); if (instanceDir.exists() && instanceDir.isDirectory() && !instanceFile.exists()) { // yes! -- use this savepoint file instancePath = instanceFile.getAbsolutePath(); break; } } } } finally { if (c != null) { c.close(); } } } else { Timber.e("Unrecognized URI: %s", uri); this.createErrorDialog(getString(R.string.unrecognized_uri, uri), EXIT); return; } formLoaderTask = new FormLoaderTask(instancePath, null, null); Collect.getInstance().getActivityLogger().logAction(this, "formLoaded", formPath); showDialog(PROGRESS_DIALOG); // show dialog before we execute... formLoaderTask.execute(formPath); } } }
From source file:cn.studyjams.s2.sj0132.bowenyan.mygirlfriend.nononsenseapps.notepad.ui.widget.ListWidgetConfig.java
@TargetApi(Build.VERSION_CODES.JELLY_BEAN) void setupPreview() { final WidgetPrefs widgetPrefs = new WidgetPrefs(this, appWidgetId); mNotesAdapter = new SimpleWidgetPreviewAdapter(this, R.layout.widgetlist_item, R.layout.widgetlist_header, null,// w w w. j a v a 2 s .c o m new String[] { Task.Columns.TITLE, Task.Columns.DUE, Task.Columns.COMPLETED, Task.Columns.COMPLETED, Task.Columns.COMPLETED }, new int[] { android.R.id.text1, R.id.dueDate, R.id.completedCheckBoxDark, R.id.itemSpacer, R.id.completedCheckBoxLight }, 0); mNotesAdapter.setViewBinder(new ViewBinder() { final WidgetPrefs widgetPrefs = new WidgetPrefs(ListWidgetConfig.this, appWidgetId); boolean isHeader = false; String sTemp = ""; final SimpleDateFormat weekdayFormatter = TimeFormatter.getLocalFormatterWeekday(ListWidgetConfig.this); final SimpleDateFormat dateFormatter = TimeFormatter.getLocalFormatterMicro(ListWidgetConfig.this); @Override public boolean setViewValue(View view, Cursor c, int colIndex) { // Check for headers, they have invalid ids isHeader = c.getLong(0) == -1; switch (colIndex) { case 1: if (isHeader) { sTemp = c.getString(1); if (Task.HEADER_KEY_OVERDUE.equals(sTemp)) { sTemp = getString(R.string.date_header_overdue); } else if (Task.HEADER_KEY_TODAY.equals(sTemp)) { sTemp = getString(R.string.date_header_today); } else if (Task.HEADER_KEY_PLUS1.equals(sTemp)) { sTemp = getString(R.string.date_header_tomorrow); } else if (Task.HEADER_KEY_PLUS2.equals(sTemp) || Task.HEADER_KEY_PLUS3.equals(sTemp) || Task.HEADER_KEY_PLUS4.equals(sTemp)) { sTemp = weekdayFormatter.format(new Date(c.getLong(4))); } else if (Task.HEADER_KEY_LATER.equals(sTemp)) { sTemp = getString(R.string.date_header_future); } else if (Task.HEADER_KEY_NODATE.equals(sTemp)) { sTemp = getString(R.string.date_header_none); } else if (Task.HEADER_KEY_COMPLETE.equals(sTemp)) { sTemp = getString(R.string.date_header_completed); } ((TextView) view).setText(sTemp); // ((TextView) view).setText(TitleNoteTextView // .getStyledText(sTemp, 1.3f, 1, 1)); } else { ((TextView) view).setText( TitleNoteTextView.getStyledText(c.getString(1), c.getString(2), 1.0f, 1, 1)); final int rows = widgetPrefs.getInt(KEY_TITLEROWS, DEFAULT_ROWS); ((TextView) view).setMaxLines(rows < 1 ? 1 : rows); } // Set color ((TextView) view).setTextColor(widgetPrefs.getInt(KEY_TEXTPRIMARY, DEFAULT_TEXTPRIMARY)); return true; case 2: // already done. return true; case 3: // Complete checkbox boolean visible; if (view.getId() == R.id.completedCheckBoxLight) { visible = THEME_LIGHT == widgetPrefs.getInt(KEY_THEME, DEFAULT_THEME); } else if (view.getId() == R.id.completedCheckBoxDark) { visible = THEME_DARK == widgetPrefs.getInt(KEY_THEME, DEFAULT_THEME); } else { // Spacer visible = true; } visible &= !widgetPrefs.getBoolean(KEY_HIDDENCHECKBOX, false); view.setVisibility(visible ? View.VISIBLE : View.GONE); return true; case 4: // Date view.setVisibility(widgetPrefs.getBoolean(KEY_HIDDENDATE, false) ? View.GONE : View.VISIBLE); if (c.isNull(colIndex)) { ((TextView) view).setText(""); } else { ((TextView) view).setText(dateFormatter.format(new Date(c.getLong(colIndex)))); } ((TextView) view).setTextColor(widgetPrefs.getInt(KEY_TEXTPRIMARY, DEFAULT_TEXTPRIMARY)); return true; default: return false; } } }); binding.widgetPreviewWrapper.notesList.setAdapter(mNotesAdapter); mCallback = new LoaderCallbacks<Cursor>() { @Override public Loader<Cursor> onCreateLoader(int id, Bundle arg1) { if (id == 1) { return new CursorLoader(ListWidgetConfig.this, TaskList.URI, TaskList.Columns.FIELDS, null, null, getString(R.string.const_as_alphabetic, TaskList.Columns.TITLE)); } else { final Uri targetUri; final long listId = widgetPrefs.getLong(KEY_LIST, ALL_LISTS_ID); final String sortSpec; final String sortType = widgetPrefs.getString(KEY_SORT_TYPE, getString(R.string.default_sorttype)); if (sortType.equals(getString(R.string.const_possubsort)) && listId > 0) { targetUri = Task.URI; sortSpec = Task.Columns.LEFT; } else if (sortType.equals(getString(R.string.const_modified))) { targetUri = Task.URI; sortSpec = Task.Columns.UPDATED + " DESC"; } // due date sorting else if (sortType.equals(getString(R.string.const_duedate))) { targetUri = Task.URI_SECTIONED_BY_DATE; sortSpec = null; } // Alphabetic else { targetUri = Task.URI; sortSpec = getString(R.string.const_as_alphabetic, Task.Columns.TITLE); } String listWhere = null; String[] listArg = null; if (listId > 0) { listWhere = Task.Columns.DBLIST + " IS ? AND " + Task.Columns.COMPLETED + " IS NULL"; listArg = new String[] { Long.toString(listId) }; } else { listWhere = Task.Columns.COMPLETED + " IS NULL"; listArg = null; } return new CursorLoader(ListWidgetConfig.this, targetUri, Task.Columns.FIELDS, listWhere, listArg, sortSpec); } } @Override public void onLoadFinished(Loader<Cursor> l, Cursor c) { if (l.getId() == 1) { mListAdapter.swapCursor(c); final int pos = getListPositionOf(mListAdapter, widgetPrefs.getLong(KEY_LIST, ALL_LISTS_ID)); //if (c.getCount() > 0) { // Set current item binding.widgetConfWrapper.listSpinner.setSelection(pos); //} } else { mNotesAdapter.swapCursor(c); } } @Override public void onLoaderReset(Loader<Cursor> l) { if (l.getId() == 1) { mListAdapter.swapCursor(null); } else { mNotesAdapter.swapCursor(null); } } }; getSupportLoaderManager().restartLoader(1, null, mCallback); }
From source file:com.kll.collect.android.activities.FormEntryActivity.java
/** Called when the activity is first created. */ @Override// w w w. j a v a2 s.c o m public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // must be at the beginning of any activity that can be called from an // external intent try { Collect.createODKDirs(); } catch (RuntimeException e) { createErrorDialog(e.getMessage(), EXIT); return; } Log.i("Activity", "Created"); mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); mSharedPreferences .registerOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { compressImage = mSharedPreferences .getBoolean(PreferencesActivity.KEY_ENABLE_IMAGE_COMPRESSION, false); } }); setContentView(R.layout.form_entry); /* setTitle(getString(R.string.app_name) + " > " + getString(R.string.loading_form));*/ setTitle(getString(R.string.app_name)); Log.i("Entry", "Form"); mErrorMessage = null; //progressBar = (ProgressBar) findViewById(R.id.progress); //progressBar.setVisibility(ProgressBar.VISIBLE); //progressBar.setProgress(0); mBeenSwiped = false; mAlertDialog = null; mCurrentView = null; mInAnimation = null; mOutAnimation = null; mGestureDetector = new GestureDetector(this, this); mQuestionHolder = (LinearLayout) findViewById(R.id.questionholder); // get admin preference settings mAdminPreferences = getSharedPreferences(AdminPreferencesActivity.ADMIN_PREFERENCES, 0); mNextButton = (ImageButton) findViewById(R.id.form_forward_button); mNextButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mBeenSwiped = true; showNextView(); } }); mBackButton = (ImageButton) findViewById(R.id.form_back_button); mBackButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mBeenSwiped = true; showPreviousView(); } }); needLocation = mSharedPreferences.getBoolean(PreferencesActivity.KEY_GPS_FIX, false); if (needLocation) { mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 5, this); } // Load JavaRosa modules. needed to restore forms. new XFormsModule().registerModule(); // needed to override rms property manager org.javarosa.core.services.PropertyManager.setPropertyManager(new PropertyManager(getApplicationContext())); String startingXPath = null; String waitingXPath = null; String instancePath = null; Boolean newForm = true; if (savedInstanceState != null) { if (savedInstanceState.containsKey(KEY_FORMPATH)) { mFormPath = savedInstanceState.getString(KEY_FORMPATH); } if (savedInstanceState.containsKey(KEY_INSTANCEPATH)) { instancePath = savedInstanceState.getString(KEY_INSTANCEPATH); } if (savedInstanceState.containsKey(KEY_XPATH)) { startingXPath = savedInstanceState.getString(KEY_XPATH); Log.i(t, "startingXPath is: " + startingXPath); } if (savedInstanceState.containsKey(KEY_XPATH_WAITING_FOR_DATA)) { waitingXPath = savedInstanceState.getString(KEY_XPATH_WAITING_FOR_DATA); Log.i(t, "waitingXPath is: " + waitingXPath); } if (savedInstanceState.containsKey(NEWFORM)) { newForm = savedInstanceState.getBoolean(NEWFORM, true); } if (savedInstanceState.containsKey(KEY_ERROR)) { mErrorMessage = savedInstanceState.getString(KEY_ERROR); } } // If a parse error message is showing then nothing else is loaded // Dialogs mid form just disappear on rotation. if (mErrorMessage != null) { createErrorDialog(mErrorMessage, EXIT); return; } // Check to see if this is a screen flip or a new form load. Object data = getLastNonConfigurationInstance(); if (data instanceof FormLoaderTask) { mFormLoaderTask = (FormLoaderTask) data; } else if (data instanceof SaveToDiskTask) { mSaveToDiskTask = (SaveToDiskTask) data; } else if (data == null) { if (!newForm) { if (Collect.getInstance().getFormController() != null) { refreshCurrentView(); } else { Log.w(t, "Reloading form and restoring state."); // we need to launch the form loader to load the form // controller... mFormLoaderTask = new FormLoaderTask(instancePath, startingXPath, waitingXPath); Collect.getInstance().getActivityLogger().logAction(this, "formReloaded", mFormPath); // TODO: this doesn' work (dialog does not get removed): // showDialog(PROGRESS_DIALOG); // show dialog before we execute... Log.i("Loader", "Executing"); mFormLoaderTask.execute(mFormPath); } return; } // Not a restart from a screen orientation change (or other). Collect.getInstance().setFormController(null); CompatibilityUtils.invalidateOptionsMenu(this); Intent intent = getIntent(); if (intent != null) { Uri uri = intent.getData(); if (getContentResolver().getType(uri).equals(InstanceColumns.CONTENT_ITEM_TYPE)) { // get the formId and version for this instance... String jrFormId = null; String jrVersion = null; { Cursor instanceCursor = null; try { instanceCursor = getContentResolver().query(uri, null, null, null, null); if (instanceCursor.getCount() != 1) { this.createErrorDialog("Bad URI: " + uri, EXIT); return; } else { instanceCursor.moveToFirst(); instancePath = instanceCursor.getString( instanceCursor.getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH)); Collect.getInstance().getActivityLogger().logAction(this, "instanceLoaded", instancePath); jrFormId = instanceCursor .getString(instanceCursor.getColumnIndex(InstanceColumns.JR_FORM_ID)); int idxJrVersion = instanceCursor.getColumnIndex(InstanceColumns.JR_VERSION); jrVersion = instanceCursor.isNull(idxJrVersion) ? null : instanceCursor.getString(idxJrVersion); } } finally { if (instanceCursor != null) { instanceCursor.close(); } } } String[] selectionArgs; String selection; if (jrVersion == null) { selectionArgs = new String[] { jrFormId }; selection = FormsColumns.JR_FORM_ID + "=? AND " + FormsColumns.JR_VERSION + " IS NULL"; } else { selectionArgs = new String[] { jrFormId, jrVersion }; selection = FormsColumns.JR_FORM_ID + "=? AND " + FormsColumns.JR_VERSION + "=?"; } { Cursor formCursor = null; try { formCursor = getContentResolver().query(FormsColumns.CONTENT_URI, null, selection, selectionArgs, null); if (formCursor.getCount() == 1) { formCursor.moveToFirst(); mFormPath = formCursor .getString(formCursor.getColumnIndex(FormsColumns.FORM_FILE_PATH)); } else if (formCursor.getCount() < 1) { this.createErrorDialog( getString(R.string.parent_form_not_present, jrFormId) + ((jrVersion == null) ? "" : "\n" + getString(R.string.version) + " " + jrVersion), EXIT); return; } else if (formCursor.getCount() > 1) { // still take the first entry, but warn that // there are multiple rows. // user will need to hand-edit the SQLite // database to fix it. formCursor.moveToFirst(); mFormPath = formCursor .getString(formCursor.getColumnIndex(FormsColumns.FORM_FILE_PATH)); this.createErrorDialog(getString(R.string.survey_multiple_forms_error), EXIT); return; } } finally { if (formCursor != null) { formCursor.close(); } } } } else if (getContentResolver().getType(uri).equals(FormsColumns.CONTENT_ITEM_TYPE)) { Cursor c = null; try { c = getContentResolver().query(uri, null, null, null, null); if (c.getCount() != 1) { this.createErrorDialog("Bad URI: " + uri, EXIT); return; } else { c.moveToFirst(); mFormPath = c.getString(c.getColumnIndex(FormsColumns.FORM_FILE_PATH)); // This is the fill-blank-form code path. // See if there is a savepoint for this form that // has never been // explicitly saved // by the user. If there is, open this savepoint // (resume this filled-in // form). // Savepoints for forms that were explicitly saved // will be recovered // when that // explicitly saved instance is edited via // edit-saved-form. final String filePrefix = mFormPath.substring(mFormPath.lastIndexOf('/') + 1, mFormPath.lastIndexOf('.')) + "_"; final String fileSuffix = ".xml.save"; File cacheDir = new File(Collect.CACHE_PATH); File[] files = cacheDir.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { String name = pathname.getName(); return name.startsWith(filePrefix) && name.endsWith(fileSuffix); } }); // see if any of these savepoints are for a // filled-in form that has never been // explicitly saved by the user... for (int i = 0; i < files.length; ++i) { File candidate = files[i]; String instanceDirName = candidate.getName().substring(0, candidate.getName().length() - fileSuffix.length()); File instanceDir = new File( Collect.INSTANCES_PATH + File.separator + instanceDirName); File instanceFile = new File(instanceDir, instanceDirName + ".xml"); if (instanceDir.exists() && instanceDir.isDirectory() && !instanceFile.exists()) { // yes! -- use this savepoint file instancePath = instanceFile.getAbsolutePath(); break; } } } } finally { if (c != null) { c.close(); } } } else { Log.e(t, "unrecognized URI"); this.createErrorDialog("Unrecognized URI: " + uri, EXIT); return; } mFormLoaderTask = new FormLoaderTask(instancePath, null, null); Collect.getInstance().getActivityLogger().logAction(this, "formLoaded", mFormPath); showDialog(PROGRESS_DIALOG); // show dialog before we execute... Log.i("Loader", "Executing"); mFormLoaderTask.execute(mFormPath); } } }