Example usage for android.app Activity getContentResolver

List of usage examples for android.app Activity getContentResolver

Introduction

In this page you can find the example usage for android.app Activity getContentResolver.

Prototype

@Override
    public ContentResolver getContentResolver() 

Source Link

Usage

From source file:com.murrayc.galaxyzoo.app.QuestionFragment.java

/**
 * Avoid calling this from the main (UI) thread - StrictMode doesn't like it on at least API 15
 * and API 16.//  w w w .j ava 2s  .c o m
 *
 * @param classificationInProgress
 */
private void saveClassificationSync(final ClassificationInProgress classificationInProgress) {
    final String itemId = getItemId();
    if (TextUtils.equals(itemId, ItemsContentProvider.URI_PART_ITEM_ID_NEXT)) {
        Log.error("QuestionFragment.saveClassification(): Attempting to save with the 'next' ID.");
        return;
    }

    final Activity activity = getActivity();
    if (activity == null)
        return;

    final ContentResolver resolver = activity.getContentResolver();

    // Add the related Classification Answers:
    // Use a ContentProvider operation to perform operations together,
    // either completely or not at all, as a transaction.
    // This should prevent an incomplete classification from being uploaded
    // before we have finished adding it.
    //
    // We use the specific ArrayList<> subtype instead of List<> because
    // ContentResolver.applyBatch() takes an ArrayList for some reason.
    final ArrayList<ContentProviderOperation> ops = new ArrayList<>();

    int sequence = 0;
    final List<ClassificationInProgress.QuestionAnswer> answers = classificationInProgress.getAnswers();
    if (answers != null) {
        for (final ClassificationInProgress.QuestionAnswer answer : answers) {
            ContentProviderOperation.Builder builder = ContentProviderOperation
                    .newInsert(ClassificationAnswer.CLASSIFICATION_ANSWERS_URI);
            final ContentValues valuesAnswers = new ContentValues();
            valuesAnswers.put(ClassificationAnswer.Columns.ITEM_ID, itemId);
            valuesAnswers.put(ClassificationAnswer.Columns.SEQUENCE, sequence);
            valuesAnswers.put(ClassificationAnswer.Columns.QUESTION_ID, answer.getQuestionId());
            valuesAnswers.put(ClassificationAnswer.Columns.ANSWER_ID, answer.getAnswerId());
            builder.withValues(valuesAnswers);
            ops.add(builder.build());

            //For instance, if the question has multiple-choice checkboxes to select before clicking
            //the "Done" answer:
            final List<String> checkboxIds = answer.getCheckboxIds();
            if (checkboxIds != null) {
                for (final String checkboxId : checkboxIds) {
                    builder = ContentProviderOperation
                            .newInsert(ClassificationCheckbox.CLASSIFICATION_CHECKBOXES_URI);
                    final ContentValues valuesCheckbox = new ContentValues();
                    valuesCheckbox.put(ClassificationCheckbox.Columns.ITEM_ID, itemId);
                    valuesCheckbox.put(ClassificationCheckbox.Columns.SEQUENCE, sequence);
                    valuesCheckbox.put(ClassificationCheckbox.Columns.QUESTION_ID, answer.getQuestionId());
                    valuesCheckbox.put(ClassificationCheckbox.Columns.CHECKBOX_ID, checkboxId);
                    builder.withValues(valuesCheckbox);
                    ops.add(builder.build());
                }
            }

            sequence++;
        }
    }

    //Mark the Item (Subject) as done:
    final Uri.Builder uriBuilder = Item.ITEMS_URI.buildUpon();
    uriBuilder.appendPath(getItemId());
    final ContentProviderOperation.Builder builder = ContentProviderOperation.newUpdate(uriBuilder.build());
    final ContentValues values = new ContentValues();
    values.put(Item.Columns.DONE, true);
    values.put(Item.Columns.DATETIME_DONE, getCurrentDateTimeAsIso8601());
    values.put(Item.Columns.FAVORITE, classificationInProgress.isFavorite());
    builder.withValues(values);
    ops.add(builder.build());

    try {
        resolver.applyBatch(ClassificationAnswer.AUTHORITY, ops);
    } catch (final RemoteException | OperationApplicationException e) {
        //This should never happen, and would mean a loss of the current classification,
        //so let it crash the app and generate a report with a stacktrace,
        //because that's (slightly) better than just ignoring it.
        //
        //I guess that OperationApplicationException is not an unchecked exception,
        //because it could be caused by not just pure programmer error,
        //for instance if our data did not fulfill a Sqlite database constraint.
        Log.error("QuestionFragment. saveClassification(): Exception from applyBatch()", e);
        throw new RuntimeException("ContentResolver.applyBatch() failed.", e);
    }

    //The ItemsContentProvider will upload the classification later.
}

From source file:ca.rmen.android.scrumchatter.meeting.detail.MeetingFragment.java

/**
 * Read the given meeting in the background. Init or restart the loader for the meeting members. Update the views for the meeting.
 *//*from  w w  w  .  j a v a 2s. c o m*/
private void loadMeeting() {
    Log.v(TAG, "loadMeeting: current meeting = " + mMeeting);
    Activity activity = getActivity();
    if (activity == null) {
        Log.w(TAG,
                "loadMeeting called when we are no longer attached to the activity. A monkey might be involved");
        return;
    }
    State meetingState = mMeeting == null ? (State) getArguments().getSerializable(Meetings.EXTRA_MEETING_STATE)
            : mMeeting.getState();
    Bundle bundle = new Bundle(1);
    bundle.putSerializable(Meetings.EXTRA_MEETING_STATE, meetingState);
    if (mAdapter == null) {
        mAdapter = new MeetingCursorAdapter(activity, mMemberStartStopListener);
        mBinding.recyclerViewContent.recyclerView.setAdapter(mAdapter);
        getLoaderManager().initLoader((int) mMeetingId, bundle, mLoaderCallbacks);
    } else {
        getLoaderManager().restartLoader((int) mMeetingId, bundle, mLoaderCallbacks);
    }

    mMeetings.readMeeting(mMeetingId).doOnSuccess(meeting -> mMeeting = meeting).subscribe(this::displayMeeting,
            throwable -> activity.getContentResolver().unregisterContentObserver(mMeetingObserver));
}

From source file:com.google.android.exoplayer2.demo.MediaPlayerFragment.java

private void initBrightnessTouch() {

    //        if (!(getContext() instanceof Activity)) {
    //            return;
    //        }/*w ww .  ja  va2 s. c  om*/
    Activity activity = fragActivity;//(Activity) getContext();

    WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
    float brightnesstemp = lp.screenBrightness != -1f ? lp.screenBrightness : 0.6f;
    // Initialize the layoutParams screen brightness
    try {
        if (Settings.System.getInt(activity.getContentResolver(),
                Settings.System.SCREEN_BRIGHTNESS_MODE) == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) {
            if (!Permissions.canWriteSettings(activity)) {
                return;
            }
            Settings.System.putInt(activity.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE,
                    Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
            //                restoreAutoBrightness = android.provider.Settings.System.getInt(activity.getContentResolver(),
            //                        android.provider.Settings.System.SCREEN_BRIGHTNESS) / 255.0f;
        } else if (brightnesstemp == 0.6f) {
            brightnesstemp = android.provider.Settings.System.getInt(activity.getContentResolver(),
                    android.provider.Settings.System.SCREEN_BRIGHTNESS) / 255.0f;
        }
    } catch (Settings.SettingNotFoundException e) {
        e.printStackTrace();
    }
    lp.screenBrightness = brightnesstemp;
    activity.getWindow().setAttributes(lp);
    mIsFirstBrightnessGesture = false;
}

From source file:cc.mintcoin.wallet.ui.SendCoinsFragment.java

@Override
public void onAttach(final Activity activity) {
    super.onAttach(activity);

    this.activity = (AbstractBindServiceActivity) activity;
    this.application = (WalletApplication) activity.getApplication();
    this.config = application.getConfiguration();
    this.wallet = application.getWallet();
    this.contentResolver = activity.getContentResolver();
    this.loaderManager = getLoaderManager();
}

From source file:com.bushstar.htmlcoin_android_wallet.ui.SendCoinsFragment.java

@Override
public void onAttach(final Activity activity) {
    super.onAttach(activity);

    this.activity = (AbstractBindServiceActivity) activity;
    this.application = (WalletApplication) activity.getApplication();
    this.config = application.getConfiguration();
    this.wallet = application.getWallet();
    this.contentResolver = activity.getContentResolver();
    this.loaderManager = getLoaderManager();
    this.fragmentManager = getFragmentManager();
}

From source file:org.totschnig.myexpenses.activity.CommonCommands.java

static boolean dispatchCommand(Activity ctx, int command, Object tag) {
    Intent i;//w  w  w  .  j  ava  2  s  . co m
    switch (command) {
    case R.id.RATE_COMMAND:
        i = new Intent(Intent.ACTION_VIEW);
        i.setData(Uri.parse(MyApplication.getMarketSelfUri()));
        if (Utils.isIntentAvailable(ctx, i)) {
            ctx.startActivity(i);
        } else {
            Toast.makeText(ctx, R.string.error_accessing_market, Toast.LENGTH_LONG).show();
        }
        return true;
    case R.id.SETTINGS_COMMAND:
        i = new Intent(ctx, MyPreferenceActivity.class);
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        if (tag != null) {
            i.putExtra(MyPreferenceActivity.KEY_OPEN_PREF_KEY, (String) tag);
        }
        ctx.startActivityForResult(i, ProtectedFragmentActivity.PREFERENCES_REQUEST);
        return true;
    case R.id.FEEDBACK_COMMAND:
        i = new Intent(android.content.Intent.ACTION_SEND);
        i.setType("plain/text");
        i.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] { MyApplication.FEEDBACK_EMAIL });
        i.putExtra(android.content.Intent.EXTRA_SUBJECT, "[" + ctx.getString(R.string.app_name) + "] Feedback");
        i.putExtra(android.content.Intent.EXTRA_TEXT,
                getVersionInfo(ctx) + "\n" + ctx.getString(R.string.feedback_email_message));
        if (!Utils.isIntentAvailable(ctx, i)) {
            Toast.makeText(ctx, R.string.no_app_handling_email_available, Toast.LENGTH_LONG).show();
        } else {
            ctx.startActivity(i);
        }
        break;
    case R.id.CONTRIB_INFO_COMMAND:
        CommonCommands.showContribInfoDialog((FragmentActivity) ctx, -1);
        return true;
    case R.id.WEB_COMMAND:
        i = new Intent(Intent.ACTION_VIEW);
        i.setData(Uri.parse(ctx.getString(R.string.website)));
        ctx.startActivity(i);
        return true;
    case R.id.HELP_COMMAND:
        i = new Intent(ctx, Help.class);
        i.putExtra(HelpDialogFragment.KEY_VARIANT,
                tag != null ? (Enum<?>) tag : ((ProtectedFragmentActivity) ctx).helpVariant);
        //for result is needed since it allows us to inspect the calling activity
        ctx.startActivityForResult(i, 0);
        return true;
    case R.id.REQUEST_LICENCE_COMMAND:
        String androidId = Settings.Secure.getString(ctx.getContentResolver(), Settings.Secure.ANDROID_ID);
        i = new Intent(android.content.Intent.ACTION_SEND);
        i.setType("plain/text");
        i.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] { MyApplication.FEEDBACK_EMAIL });
        i.putExtra(android.content.Intent.EXTRA_SUBJECT,
                "[" + ctx.getString(R.string.app_name) + "] " + ctx.getString(R.string.contrib_key));
        String extraText = ctx.getString(R.string.request_licence_mail_head, androidId);
        if (tag != null) {
            extraText += " \n\n[" + ctx.getString(R.string.paypal_transaction_id) + ": " + tag + "]";
        }
        i.putExtra(android.content.Intent.EXTRA_TEXT, extraText);
        if (!Utils.isIntentAvailable(ctx, i)) {
            Toast.makeText(ctx, R.string.no_app_handling_email_available, Toast.LENGTH_LONG).show();
        } else {
            ctx.startActivity(i);
        }
        return true;
    case R.id.VERIFY_LICENCE_COMMAND:
        HashLicenceHandler licenceHandler = (HashLicenceHandler) MyApplication.getInstance()
                .getLicenceHandler();
        LicenceHandler.LicenceStatus licenceStatus = licenceHandler.verifyLicenceKey();
        if (licenceStatus != null) {
            Toast.makeText(ctx,
                    Utils.concatResStrings(ctx, " ", R.string.licence_validation_success,
                            (licenceStatus == LicenceHandler.LicenceStatus.EXTENDED
                                    ? R.string.licence_validation_extended
                                    : R.string.licence_validation_premium)),
                    Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(ctx, R.string.licence_validation_failure, Toast.LENGTH_LONG).show();
        }
        licenceHandler.invalidate();
        return true;
    case android.R.id.home:
        ctx.setResult(FragmentActivity.RESULT_CANCELED);
        ctx.finish();
        return true;
    }
    return false;
}

From source file:cliq.com.cliqgram.fragments.CameraFragment.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    Activity activity = getActivity();

    if (requestCode == PICK_IMAGE_REQUEST && resultCode == Activity.RESULT_OK && data != null
            && data.getData() != null) {

        /**//w  ww.jav  a  2s  .  c om
         * @param imageDate byte[]
         * @param currentUser User
         * @param description String
         * @return post Post
         * Note: Any data in post object may not be able to
         * get before post.saveInBackground() in finished.
         * So, check the database (table "Post") on Parse to see if post is
         * created successfully.
         * If post is created successfully, it will be shown on home page.
         */
        Uri uri = data.getData();

        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(activity.getContentResolver(), uri);
            // Log.d(TAG, String.valueOf(bitmap));

            startImageDisplayActivity(bitmap);

        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        activity.finish();
    }
}

From source file:com.vuze.android.remote.SessionInfo.java

private void openTorrent_perms(Activity activity, Uri uri) {
    try {/*from   w  w w .j a  v a 2 s . c  o  m*/
        InputStream stream = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            String realPath = PaulBurkeFileUtils.getPath(activity, uri);
            if (realPath != null) {
                String meh = realPath.startsWith("/") ? "file://" + realPath : realPath;
                stream = activity.getContentResolver().openInputStream(Uri.parse(meh));
            }
        }
        if (stream == null) {
            ContentResolver contentResolver = activity.getContentResolver();
            stream = contentResolver.openInputStream(uri);
        }
        openTorrent(activity, uri.toString(), stream);
    } catch (SecurityException e) {
        if (AndroidUtils.DEBUG) {
            e.printStackTrace();
        }
        VuzeEasyTracker.getInstance(activity).logError(e);
        String s = "Security Exception trying to access <b>" + uri + "</b>";
        Toast.makeText(activity, Html.fromHtml(s), Toast.LENGTH_LONG).show();
    } catch (FileNotFoundException e) {
        if (AndroidUtils.DEBUG) {
            e.printStackTrace();
        }
        VuzeEasyTracker.getInstance(activity).logError(e);
        String s = "<b>" + uri + "</b> not found";
        if (e.getCause() != null) {
            s += ". " + e.getCause().getMessage();
        }
        Toast.makeText(activity, Html.fromHtml(s), Toast.LENGTH_LONG).show();
    }
}

From source file:com.ncode.android.apps.schedo.ui.EventsFragment.java

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    if (!(activity instanceof Callbacks)) {
        throw new ClassCastException("Activity must implement fragment's callbacks.");
    }/*ww  w.  ja v  a 2s .  co m*/

    mAppContext = getActivity().getApplicationContext();
    mCallbacks = (Callbacks) activity;
    mEventsObserver = new ThrottledContentObserver(new ThrottledContentObserver.Callbacks() {
        @Override
        public void onThrottledContentObserverFired() {
            onEventsContentChanged();
        }
    });
    mTagsObserver = new ThrottledContentObserver(new ThrottledContentObserver.Callbacks() {
        @Override
        public void onThrottledContentObserverFired() {
            onTagsContentChanged();
        }
    });
    activity.getContentResolver().registerContentObserver(ScheduleContract.Events.CONTENT_URI, true,
            mEventsObserver);
    activity.getContentResolver().registerContentObserver(ScheduleContract.Tags.CONTENT_URI, true,
            mTagsObserver);

    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(activity);
    sp.registerOnSharedPreferenceChangeListener(mPrefChangeListener);
}

From source file:com.google.samples.apps.iosched.ui.SessionsFragment.java

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    if (!(activity instanceof Callbacks)) {
        throw new ClassCastException("Activity must implement fragment's callbacks.");
    }/*from  w ww .j  ava2  s.  c  o m*/

    mAppContext = getActivity().getApplicationContext();
    mCallbacks = (Callbacks) activity;
    mSessionsObserver = new ThrottledContentObserver(new ThrottledContentObserver.Callbacks() {
        @Override
        public void onThrottledContentObserverFired() {
            onSessionsContentChanged();
        }
    });
    mTagsObserver = new ThrottledContentObserver(new ThrottledContentObserver.Callbacks() {
        @Override
        public void onThrottledContentObserverFired() {
            onTagsContentChanged();
        }
    });
    activity.getContentResolver().registerContentObserver(ScheduleContract.Sessions.CONTENT_URI, true,
            mSessionsObserver);
    activity.getContentResolver().registerContentObserver(ScheduleContract.Tags.CONTENT_URI, true,
            mTagsObserver);

    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(activity);
    sp.registerOnSharedPreferenceChangeListener(mPrefChangeListener);
}