List of usage examples for android.content ContentResolver insert
public final @Nullable Uri insert(@RequiresPermission.Write @NonNull Uri url, @Nullable ContentValues values)
From source file:com.antew.redditinpictures.library.reddit.LoginResponse.java
@Override public void processHttpResponse(Context context) { ContentResolver resolver = context.getContentResolver(); // Delete old logins resolver.delete(RedditContract.Login.CONTENT_URI, null, null); RedditLoginResponse response = JsonDeserializer.deserialize(result.getJson(), RedditLoginResponse.class); if (response == null) { Ln.e("Error parsing Reddit login response"); return;/*from w ww .j a v a 2s . c o m*/ } // The username isn't sent back with the login response, so we have it passed // through from the login request String username = BundleUtil.getString(result.getExtraData(), RedditContract.Login.USERNAME, null); if (response.getLoginResponse() != null && response.getLoginResponse().getData() != null) { response.getLoginResponse().getData().setUsername(username); } ContentValues loginValues = response.getContentValues(); Intent loginNotify = new Intent(Constants.Broadcast.BROADCAST_LOGIN_COMPLETE); loginNotify.putExtra(Constants.Extra.EXTRA_USERNAME, username); Integer loginSuccess = loginValues.getAsInteger(RedditContract.Login.SUCCESS); if (loginSuccess != null && loginSuccess == 1) { loginNotify.putExtra(Constants.Extra.EXTRA_SUCCESS, true); resolver.insert(RedditContract.Login.CONTENT_URI, loginValues); } else { loginNotify.putExtra(Constants.Extra.EXTRA_SUCCESS, false); loginNotify.putExtra(Constants.Extra.EXTRA_ERROR_MESSAGE, loginValues.getAsString(RedditContract.Login.ERROR_MESSAGE)); loginNotify.putExtra(Constants.Extra.EXTRA_USERNAME, username); } LocalBroadcastManager.getInstance(context).sendBroadcast(loginNotify); }
From source file:com.nekomeshi312.whiteboardcorrection.WhiteBoardCorrectionActivity.java
@Override public void onPictureTaken(byte[] data, Camera camera) { // TODO Auto-generated method stub Log.i(LOG_TAG, "onPictureTaken"); String path = null;/*from w ww . ja v a 2s. c om*/ String name = null; if (null != data) { if (MyDebug.DEBUG) Log.d(LOG_TAG, "Captured:size = " + data.length); int sdErrorID = SDCardAccess.checkSDCard(this); if (0 != sdErrorID) {//SD?????????? Toast.makeText(this, sdErrorID, Toast.LENGTH_LONG).show(); } else { String fn = null; final String folderBase = getString(R.string.picture_folder_base_name); final String filenameBase = getString(R.string.picture_base_name); final String warpBase = getString(R.string.picture_warped_name); name = PictureFolder.createPictureName(this, folderBase, filenameBase, warpBase); path = PictureFolder.createPicturePath(this, folderBase); String[] n = new String[2]; if (createPictureName(n)) { path = n[0]; name = n[1]; fn = path + name; if (MyDebug.DEBUG) Log.d(LOG_TAG, "Picture file name = " + fn); FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(fn); fileOutputStream.write(data); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); name = null; } finally { if (null != fileOutputStream) { try { fileOutputStream.flush(); fileOutputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); name = null; } } } } } } mFocusStatus = FOCUS_STATUS_IDLE; mShutterStatus = SHUTTER_STATUS_IDLE; if (null == name) { mFragCameraView.startPreview();//?pictureTaken????activity???????????????startPreview???? return; } mFragCameraView.stopPreview();//???????????????????? //fragment?fragment?? final int width = camera.getParameters().getPictureSize().width; final int height = camera.getParameters().getPictureSize().height; final int prevWidth = camera.getParameters().getPreviewSize().width; final int prevHeight = camera.getParameters().getPreviewSize().height; //???jpge?? //MediaScannerConnection.scanFile??????????DISPLAY_NAME??WIDTH??? //????????????????????? ContentResolver cr = getContentResolver(); ContentValues values = new ContentValues(); values.put(Images.Media.TITLE, name); values.put(Images.Media.DISPLAY_NAME, name); //<- ????????????? values.put(Images.Media.MIME_TYPE, "image/jpeg"); values.put(Images.Media.DATA, path + name); values.put(Images.Media.WIDTH, width); values.put(Images.Media.HEIGHT, height); cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); mWhiteBoardCheckInfo.mFilePath = path; mWhiteBoardCheckInfo.mFileName = name; mWhiteBoardCheckInfo.mPicWidth = width; mWhiteBoardCheckInfo.mPicHeight = height; mWhiteBoardCheckInfo.mPrevWidth = prevWidth; mWhiteBoardCheckInfo.mPrevHeight = prevHeight; mWhiteBoardCheckInfo.mIsCaptured = true; transitToBoardCheckFragment(); }
From source file:com.github.mkjensen.dml.live.SetupFragment.java
private void processChannels() { ContentResolver resolver = getContext().getContentResolver(); deleteExistingChannels(resolver, inputId); ContentValues values = new ContentValues(); values.put(Channels.COLUMN_INPUT_ID, inputId); values.put(Channels.COLUMN_SERVICE_TYPE, Channels.SERVICE_TYPE_AUDIO_VIDEO); values.put(Channels.COLUMN_TYPE, Channels.TYPE_OTHER); values.put(Channels.COLUMN_VIDEO_FORMAT, Channels.VIDEO_FORMAT_720P); int id = 0;// w w w . j ava 2s . c om for (Channel channel : channels) { String title = channel.getTitle(); String url = getUrl(channel); if (url == null) { Log.d(TAG, String.format("Discarded channel [%s] because no suitable stream was found", title)); continue; } id++; values.put(Channels.COLUMN_DISPLAY_NAME, title); values.put(Channels.COLUMN_DISPLAY_NUMBER, id); values.put(Channels.COLUMN_INTERNAL_PROVIDER_DATA, url); values.put(Channels.COLUMN_ORIGINAL_NETWORK_ID, id); values.put(Channels.COLUMN_SERVICE_ID, id); values.put(Channels.COLUMN_TRANSPORT_STREAM_ID, id); resolver.insert(Channels.CONTENT_URI, values); } Log.d(TAG, "Added channels: " + id); }
From source file:org.mariotaku.twidere.fragment.support.UserProfileFragment.java
private boolean handleMenuItemClick(final MenuItem item) { final AsyncTwitterWrapper twitter = getTwitterWrapper(); final ParcelableUser user = mUser; final Relationship relationship = mFriendship; if (user == null || twitter == null) return false; switch (item.getItemId()) { case MENU_BLOCK: { if (mFriendship != null) { if (mFriendship.isSourceBlockingTarget()) { twitter.destroyBlockAsync(user.account_id, user.id); } else { CreateUserBlockDialogFragment.show(getFragmentManager(), user); }//w ww. j av a 2s . co m } break; } case MENU_REPORT_SPAM: { ReportSpamDialogFragment.show(getFragmentManager(), user); break; } case MENU_MUTE_USER: { final ContentResolver resolver = getContentResolver(); resolver.delete(Filters.Users.CONTENT_URI, Where.equals(Filters.Users.USER_ID, user.id).getSQL(), null); resolver.insert(Filters.Users.CONTENT_URI, makeFilterdUserContentValues(user)); showInfoMessage(getActivity(), R.string.user_muted, false); break; } case MENU_MENTION: { final Intent intent = new Intent(INTENT_ACTION_MENTION); final Bundle bundle = new Bundle(); bundle.putParcelable(EXTRA_USER, user); intent.putExtras(bundle); startActivity(intent); break; } case MENU_SEND_DIRECT_MESSAGE: { final Uri.Builder builder = new Uri.Builder(); builder.scheme(SCHEME_TWIDERE); builder.authority(AUTHORITY_DIRECT_MESSAGES_CONVERSATION); builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_ID, String.valueOf(user.account_id)); builder.appendQueryParameter(QUERY_PARAM_RECIPIENT_ID, String.valueOf(user.id)); startActivity(new Intent(Intent.ACTION_VIEW, builder.build())); break; } case MENU_SET_COLOR: { final Intent intent = new Intent(getActivity(), ColorPickerDialogActivity.class); intent.putExtra(EXTRA_COLOR, getUserColor(getActivity(), user.id, true)); intent.putExtra(EXTRA_ALPHA_SLIDER, false); intent.putExtra(EXTRA_CLEAR_BUTTON, true); startActivityForResult(intent, REQUEST_SET_COLOR); break; } case MENU_CLEAR_NICKNAME: { clearUserNickname(getActivity(), user.id); break; } case MENU_SET_NICKNAME: { final String nick = getUserNickname(getActivity(), user.id, true); SetUserNicknameDialogFragment.show(getFragmentManager(), user.id, nick); break; } case MENU_ADD_TO_LIST: { final Intent intent = new Intent(INTENT_ACTION_SELECT_USER_LIST); intent.setClass(getActivity(), UserListSelectorActivity.class); intent.putExtra(EXTRA_ACCOUNT_ID, user.account_id); intent.putExtra(EXTRA_SCREEN_NAME, getAccountScreenName(getActivity(), user.account_id)); startActivityForResult(intent, REQUEST_ADD_TO_LIST); break; } case MENU_OPEN_WITH_ACCOUNT: { final Intent intent = new Intent(INTENT_ACTION_SELECT_ACCOUNT); intent.setClass(getActivity(), AccountSelectorActivity.class); intent.putExtra(EXTRA_SINGLE_SELECTION, true); startActivityForResult(intent, REQUEST_SELECT_ACCOUNT); break; } case MENU_EDIT: { final Bundle extras = new Bundle(); extras.putLong(EXTRA_ACCOUNT_ID, user.account_id); final Intent intent = new Intent(INTENT_ACTION_EDIT_USER_PROFILE); intent.setClass(getActivity(), UserProfileEditorActivity.class); intent.putExtras(extras); startActivity(intent); return true; } case MENU_FOLLOW: { if (relationship == null) return false; final boolean isFollowing = relationship.isSourceFollowingTarget(); final boolean isCreatingFriendship = twitter.isCreatingFriendship(user.account_id, user.id); final boolean isDestroyingFriendship = twitter.isDestroyingFriendship(user.account_id, user.id); if (!isCreatingFriendship && !isDestroyingFriendship) { if (isFollowing) { DestroyFriendshipDialogFragment.show(getFragmentManager(), user); } else { twitter.createFriendshipAsync(user.account_id, user.id); } } return true; } default: { if (item.getIntent() != null) { try { startActivity(item.getIntent()); } catch (final ActivityNotFoundException e) { Log.w(LOGTAG, e); return false; } } break; } } return true; }
From source file:com.example.android.miniweather.app.FetchWeatherTask.java
/** * Helper method to handle insertion of a new location in the weather database. * * @param locationSetting The location string used to request updates from the server. * @param cityName A human-readable city name, e.g "Mountain View" * @param lat the latitude of the city//from www . java2 s .c om * @param lon the longitude of the city * @return the row ID of the added location. */ long addLocation(String locationSetting, String cityName, double lat, double lon) { // Students: First, check if the location with this city name exists in the db // If it exists, return the current ID // Otherwise, insert it using the content resolver and the base URI ContentResolver contentResolver = mContext.getContentResolver(); Cursor cursor; long locationID; cursor = contentResolver.query(WeatherContract.LocationEntry.CONTENT_URI, new String[] { WeatherContract.LocationEntry._ID }, WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ?", new String[] { locationSetting }, null); if (cursor.moveToFirst()) { int locationIDIndex = cursor.getColumnIndex(WeatherContract.LocationEntry._ID); locationID = cursor.getLong(locationIDIndex); } else { ContentValues newLocation = new ContentValues(); Uri insertedUri; newLocation.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting); newLocation.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName); newLocation.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, lat); newLocation.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon); insertedUri = contentResolver.insert(WeatherContract.LocationEntry.CONTENT_URI, newLocation); locationID = ContentUris.parseId(insertedUri); } cursor.close(); return locationID; }
From source file:de.vanita5.twittnuker.fragment.support.UserProfileFragment.java
private boolean handleMenuItemClick(final MenuItem item) { final AsyncTwitterWrapper twitter = getTwitterWrapper(); final ParcelableUser user = mUser; final Relationship relationship = mRelationship; if (user == null || twitter == null) return false; switch (item.getItemId()) { case MENU_BLOCK: { if (mRelationship != null) { if (mRelationship.isSourceBlockingTarget()) { twitter.destroyBlockAsync(user.account_id, user.id); } else { CreateUserBlockDialogFragment.show(getFragmentManager(), user); }/*from w ww . j a va 2s .co m*/ } break; } case MENU_REPORT_SPAM: { ReportSpamDialogFragment.show(getFragmentManager(), user); break; } case MENU_ADD_TO_FILTER: { final ContentResolver resolver = getContentResolver(); resolver.delete(Filters.Users.CONTENT_URI, Where.equals(Filters.Users.USER_ID, user.id).getSQL(), null); resolver.insert(Filters.Users.CONTENT_URI, makeFilterdUserContentValues(user)); showInfoMessage(getActivity(), R.string.message_user_muted, false); break; } case MENU_MENTION: { final Intent intent = new Intent(INTENT_ACTION_MENTION); final Bundle bundle = new Bundle(); bundle.putParcelable(EXTRA_USER, user); intent.putExtras(bundle); startActivity(intent); break; } case MENU_SEND_DIRECT_MESSAGE: { final Uri.Builder builder = new Uri.Builder(); builder.scheme(SCHEME_TWITTNUKER); builder.authority(AUTHORITY_DIRECT_MESSAGES_CONVERSATION); builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_ID, String.valueOf(user.account_id)); builder.appendQueryParameter(QUERY_PARAM_RECIPIENT_ID, String.valueOf(user.id)); startActivity(new Intent(Intent.ACTION_VIEW, builder.build())); break; } case MENU_SET_COLOR: { final Intent intent = new Intent(getActivity(), ColorPickerDialogActivity.class); intent.putExtra(EXTRA_COLOR, getUserColor(getActivity(), user.id, true)); intent.putExtra(EXTRA_ALPHA_SLIDER, false); intent.putExtra(EXTRA_CLEAR_BUTTON, true); startActivityForResult(intent, REQUEST_SET_COLOR); break; } case MENU_CLEAR_NICKNAME: { clearUserNickname(getActivity(), user.id); break; } case MENU_SET_NICKNAME: { final String nick = getUserNickname(getActivity(), user.id, true); SetUserNicknameDialogFragment.show(getFragmentManager(), user.id, nick); break; } case MENU_ADD_TO_LIST: { final Intent intent = new Intent(INTENT_ACTION_SELECT_USER_LIST); intent.setClass(getActivity(), UserListSelectorActivity.class); intent.putExtra(EXTRA_ACCOUNT_ID, user.account_id); intent.putExtra(EXTRA_SCREEN_NAME, getAccountScreenName(getActivity(), user.account_id)); startActivityForResult(intent, REQUEST_ADD_TO_LIST); break; } case MENU_OPEN_WITH_ACCOUNT: { final Intent intent = new Intent(INTENT_ACTION_SELECT_ACCOUNT); intent.setClass(getActivity(), AccountSelectorActivity.class); intent.putExtra(EXTRA_SINGLE_SELECTION, true); startActivityForResult(intent, REQUEST_SELECT_ACCOUNT); break; } case MENU_EDIT: { final Bundle extras = new Bundle(); extras.putLong(EXTRA_ACCOUNT_ID, user.account_id); final Intent intent = new Intent(INTENT_ACTION_EDIT_USER_PROFILE); intent.setClass(getActivity(), UserProfileEditorActivity.class); intent.putExtras(extras); startActivity(intent); return true; } case MENU_FOLLOW: { if (relationship == null) return false; final boolean isFollowing = relationship.isSourceFollowingTarget(); final boolean isCreatingFriendship = twitter.isCreatingFriendship(user.account_id, user.id); final boolean isDestroyingFriendship = twitter.isDestroyingFriendship(user.account_id, user.id); if (!isCreatingFriendship && !isDestroyingFriendship) { if (isFollowing) { DestroyFriendshipDialogFragment.show(getFragmentManager(), user); } else { twitter.createFriendshipAsync(user.account_id, user.id); } } return true; } default: { if (item.getIntent() != null) { try { startActivity(item.getIntent()); } catch (final ActivityNotFoundException e) { if (Utils.isDebugBuild()) Log.w(LOGTAG, e); return false; } } break; } } return true; }
From source file:edu.princeton.jrpalmer.asmlibrary.Settings.java
@Override protected void onResume() { if (Util.trafficCop(this)) finish();/*from w ww . j a v a2 s .c om*/ IntentFilter uploadFilter; uploadFilter = new IntentFilter( getResources().getString(R.string.internal_message_id) + Util.MESSAGE_FIX_UPLOADED); uploadReceiver = new UploadReceiver(); registerReceiver(uploadReceiver, uploadFilter); IntentFilter fixFilter; fixFilter = new IntentFilter( getResources().getString(R.string.internal_message_id) + Util.MESSAGE_FIX_RECORDED); fixReceiver = new FixReceiver(); registerReceiver(fixReceiver, fixFilter); shareMyData = PropertyHolder.getShareData(); toggleParticipationViews(shareMyData); int nUploads = PropertyHolder.getNUploads(); final long participationTime = PropertyHolder.ptCheck(); participationTimeText.setBase(SystemClock.elapsedRealtime() - participationTime); // service button boolean isServiceOn = PropertyHolder.isServiceOn(); mServiceButton.setChecked(isServiceOn); mServiceButton.setOnClickListener(new ToggleButton.OnClickListener() { public void onClick(View view) { if (view.getId() != R.id.service_button) return; Context context = view.getContext(); boolean on = ((ToggleButton) view).isChecked(); String schedule = on ? Util.MESSAGE_SCHEDULE : Util.MESSAGE_UNSCHEDULE; // Log.e(TAG, schedule + on); // now schedule or unschedule Intent intent = new Intent(getString(R.string.internal_message_id) + schedule); context.sendBroadcast(intent); showSpinner(on, storeMyData); if (on && shareMyData) { final long ptNow = PropertyHolder.ptStart(); participationTimeText.setBase(SystemClock.elapsedRealtime() - ptNow); participationTimeText.start(); ContentResolver ucr = getContentResolver(); ucr.insert(Util.getUploadQueueUri(context), UploadContentValues.createUpload("ONF", "on," + Util.iso8601(System.currentTimeMillis()) + "," + ptNow)); } else { final long ptNow = PropertyHolder.ptStop(); participationTimeText.setBase(SystemClock.elapsedRealtime() - ptNow); participationTimeText.stop(); // stop uploader Intent stopUploaderIntent = new Intent(Settings.this, FileUploader.class); // Stop service if it is currently running stopService(stopUploaderIntent); if (shareMyData) { ContentResolver ucr = getContentResolver(); ucr.insert(Util.getUploadQueueUri(context), UploadContentValues.createUpload("ONF", "off," + Util.iso8601(System.currentTimeMillis()) + "," + ptNow)); } } // If user turns CountdownDisplay on but GPS is not on, remind // user to turn // GPS on if (on) { final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { if (!manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { buildAlertMessageNoGpsNoNet(); } else buildAlertMessageNoGps(); } } return; } }); // interval spinner int intspinner_item = android.R.layout.simple_spinner_item; int dropdown_item = android.R.layout.simple_spinner_dropdown_item; ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.interval_array, intspinner_item); adapter.setDropDownViewResource(dropdown_item); mIntervalSpinner.setAdapter(adapter); mIntervalSpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent, View v, int pos, long id) { int parentId = parent.getId(); if (parentId != R.id.spinner_interval) return; if (pos > mInterval.length) return; if (!PropertyHolder.isServiceOn()) { PropertyHolder.setAlarmInterval(mInterval[pos]); return; } PropertyHolder.setAlarmInterval(mInterval[pos]); mServiceButton.setChecked(true); Intent intent = new Intent(getString(R.string.internal_message_id) + Util.MESSAGE_SCHEDULE); Context context = getApplicationContext(); context.sendBroadcast(intent); showSpinner(true, storeMyData); if (shareMyData) { ContentResolver ucr = getContentResolver(); ucr.insert(Util.getUploadQueueUri(context), UploadContentValues.createUpload("INT", Util.iso8601(System.currentTimeMillis()) + "," + mInterval[pos])); } } public void onNothingSelected(AdapterView<?> parent) { // do nothing } }); int pos = ai2pos(PropertyHolder.getAlarmInterval()); mIntervalSpinner.setSelection(pos); showSpinner(isServiceOn, storeMyData); // mydata buttons // storage spinner storageDays = PropertyHolder.getStorageDays(); mStorageSpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent, View v, int pos, long id) { int parentId = parent.getId(); if (parentId != R.id.spinner_mydata) return; if (pos > MAX_STORAGE - MIN_STORAGE) return; PropertyHolder.setStorageDays(pos + MIN_STORAGE); PropertyHolder.setStoreMyData((pos + MIN_STORAGE) > 0); } public void onNothingSelected(AdapterView<?> parent) { // do nothing } }); int storagepos = storageDays - MIN_STORAGE; mStorageSpinner.setSelection(storagepos); // NEW STUFF mToggleSatRadioGroup = (RadioGroup) findViewById(R.id.toggleSatRadioGroup); mToggleIconsRadioGroup = (RadioGroup) findViewById(R.id.toggleIconsRadioGroup); mToggleAccRadioGroup = (RadioGroup) findViewById(R.id.toggleAccRadioGroup); mLimitStartDateRadioGroup = (RadioGroup) findViewById(R.id.limitStartDateRadioGroup); mLimitEndDateRadioGroup = (RadioGroup) findViewById(R.id.limitEndDateRadioGroup); Intent i = getIntent(); if (i.getBooleanExtra(MapMyData.DATES_BUTTON_MESSAGE, false)) { RelativeLayout dateSettingsArea = (RelativeLayout) findViewById(R.id.dateSettingsArea); dateSettingsArea.setFocusable(true); dateSettingsArea.setFocusableInTouchMode(true); dateSettingsArea.requestFocus(); } if (shareMyData && isServiceOn) { participationTimeText.setBase(SystemClock.elapsedRealtime() - PropertyHolder.ptStart()); participationTimeText.start(); } nUploadsText.setText(String.valueOf(nUploads)); if (nUploads >= Util.UPLOADS_TO_PRO && !PropertyHolder.getProVersion() && participationTime >= Util.TIME_TO_PRO) { Util.createProNotification(context); PropertyHolder.setProVersion(true); PropertyHolder.setNeedsDebriefingSurvey(true); } boolean proV = PropertyHolder.getProVersion(); // 19 December 2013: end of research changes mShareDataRadioGroup.check(R.id.sharedataNo); mShareDataRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { if (checkedId == R.id.sharedataYes) { buildSharingOverAnnouncement(); } mShareDataRadioGroup.check(R.id.sharedataNo); } }); /* * if (proV) { * * if (shareMyData) { mShareDataRadioGroup.check(R.id.sharedataYes); if * (PropertyHolder.isRegistered() == false || * PropertyHolder.hasConsented() == false) { send2Intro(context); } } * else { mShareDataRadioGroup.check(R.id.sharedataNo); } * * mShareDataRadioGroup .setOnCheckedChangeListener(new * OnCheckedChangeListener() { * * @Override public void onCheckedChanged(RadioGroup group, int * checkedId) { shareMyData = (checkedId == R.id.sharedataYes); * PropertyHolder.setShareData(shareMyData); * toggleParticipationViews(shareMyData); final boolean on = * PropertyHolder.isServiceOn(); if (shareMyData) { if * (PropertyHolder.isRegistered() == false || * PropertyHolder.hasConsented() == false) { send2Intro(context); * * } if (on) { * * final long ptNow = PropertyHolder.ptStart(); * participationTimeText.setBase(SystemClock .elapsedRealtime() - * ptNow); * * participationTimeText.start(); * * ContentResolver ucr = getContentResolver(); * * ucr.insert( Util.getUploadQueueUri(context), * UploadContentValues.createUpload( "ONF", "on," + Util.iso8601(System * .currentTimeMillis()) + "," + ptNow)); * * } } else { * * final long ptNow = PropertyHolder.ptStop(); * participationTimeText.setBase(SystemClock .elapsedRealtime() - * ptNow); participationTimeText.stop(); // stop uploader Intent i = new * Intent(Settings.this, FileUploader.class); // Stop service if it is * currently running stopService(i); * * if (on) { ContentResolver ucr = getContentResolver(); * * ucr.insert( Util.getUploadQueueUri(context), * UploadContentValues.createUpload( "ONF", "off," + Util.iso8601(System * .currentTimeMillis()) + "," + ptNow)); * * } * * } * * } }); } else { mShareDataRadioGroup.check(R.id.sharedataYes); * mShareDataRadioGroup .setOnCheckedChangeListener(new * OnCheckedChangeListener() { * * @Override public void onCheckedChanged(RadioGroup group, int * checkedId) { if (checkedId == R.id.sharedataNo) { * mShareDataRadioGroup.check(R.id.sharedataYes); * showCurrentlySharingDialog(); } } }); * * } */ new CheckPendingUploadsSizeTask().execute(context); new CheckUserDbSizeTask().execute(context); deletePendingUploadsButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { ContentResolver cr = getContentResolver(); final int nDeleted = cr.delete(Util.getUploadQueueUri(context), "1", null); // Log.i("Settings", "number of rows deleted=" + nDeleted); Util.toast(context, String.valueOf(nDeleted) + " " + getResources().getString(R.string.locations_deleted) + "."); updateStorageSizes(); } }); deleteUserDbButton = (ImageButton) findViewById(R.id.deleteMyDbButton); deleteUserDbButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { ContentResolver cr = getContentResolver(); final int nDeleted = cr.delete(Util.getFixesUri(context), "1", null); Util.toast(context, String.valueOf(nDeleted) + " " + getResources().getString(R.string.locations_deleted) + "."); updateStorageSizes(); } }); uploadButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (Util.isOnline(context)) { Intent i = new Intent(Settings.this, FileUploader.class); startService(i); new UploadMessageTask().execute(context); } else { Util.toast(context, getResources().getString(R.string.offline_warning)); } } }); mToggleSatRadioGroup.check(PropertyHolder.getMapSat() ? R.id.toggleSatYes : R.id.toggleSatNo); mToggleSatRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { PropertyHolder.setMapSat(checkedId == R.id.toggleSatYes); } }); mToggleIconsRadioGroup.check(PropertyHolder.getMapIcons() ? R.id.toggleIconsYes : R.id.toggleIconsNo); mToggleIconsRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { PropertyHolder.setMapIcons(checkedId == R.id.toggleIconsYes); } }); mToggleAccRadioGroup.check(PropertyHolder.getMapAcc() ? R.id.toggleAccYes : R.id.toggleAccNo); mToggleAccRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { PropertyHolder.setMapAcc(checkedId == R.id.toggleAccYes); } }); mStartDateButton = (Button) findViewById(R.id.startDateButton); mEndDateButton = (Button) findViewById(R.id.endDateButton); boolean limitStartDate = PropertyHolder.getLimitStartDate(); boolean limitEndDate = PropertyHolder.getLimitEndDate(); if (!limitStartDate) mStartDateButton.setVisibility(View.GONE); else { mStartDateButton.setVisibility(View.VISIBLE); } if (!limitEndDate) mEndDateButton.setVisibility(View.GONE); else { mEndDateButton.setVisibility(View.VISIBLE); } mLimitStartDateRadioGroup.check(limitStartDate ? R.id.limitStartDateYes : R.id.limitStartDateNo); mLimitStartDateRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { PropertyHolder.setLimitStartDate(checkedId == R.id.limitStartDateYes); if (checkedId != R.id.limitStartDateYes) mStartDateButton.setVisibility(View.GONE); else { mStartDateButton.setVisibility(View.VISIBLE); } } }); mLimitEndDateRadioGroup.check(limitEndDate ? R.id.limitEndDateYes : R.id.limitEndDateNo); mLimitEndDateRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { PropertyHolder.setLimitEndDate(checkedId == R.id.limitEndDateYes); if (checkedId != R.id.limitEndDateYes) mEndDateButton.setVisibility(View.GONE); else { mEndDateButton.setVisibility(View.VISIBLE); } } }); mStartDateButton.setText(Util.userDateNoTime(PropertyHolder.getMapStartDate())); mStartDateButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { DialogFragment newFragment = new StartDatePickerFragment(); newFragment.show(getSupportFragmentManager(), "datePicker"); } }); mEndDateButton.setText(Util.userDateNoTime(PropertyHolder.getMapEndDate())); mEndDateButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { DialogFragment newFragment = new EndDatePickerFragment(); newFragment.show(getSupportFragmentManager(), "datePicker"); } }); if (PropertyHolder.getNeedsDebriefingSurvey()) { buildProAnnouncement(); PropertyHolder.setNeedsDebriefingSurvey(false); } super.onResume(); }
From source file:com.dabay6.android.apps.carlog.ui.vehicle.fragments.VehicleEditFragment.java
/** * */// w w w.j a v a2s . c o m @Override protected ContentValues buildContentValues() { final ContentResolver resolver = getActivity().getContentResolver(); final StringBuilder vehicleName = new StringBuilder(); vehicleName.append(ViewUtils.getText(name)); if (vehicle == null) { vehicle = new VehicleDTO(); } if (TextUtils.isEmpty(vehicleName)) { if (!ViewUtils.isEmpty(year)) { vehicleName.insert(0, " "); vehicleName.insert(0, ViewUtils.getText(year)); } vehicleName.append(ViewUtils.getText(make)).append(" ").append(ViewUtils.getText(model)); } vehicle.setIsActive(true); vehicle.setLicensePlate(ViewUtils.getText(licensePlate)); vehicle.setName(vehicleName.toString()); vehicle.setVin(ViewUtils.getText(vin)); if (modelAdapter.getMakeId() == null) { final MakeDTO makeDTO = new MakeDTO(); makeDTO.setMakeName(ViewUtils.getText(make)); modelAdapter.setMakeId( ContentUris.parseId(resolver.insert(Make.CONTENT_URI, MakeDTO.buildContentValues(makeDTO)))); } vehicle.setMakeId(modelAdapter.getMakeId()); if (modelId == null) { final ModelDTO modelDTO = new ModelDTO(); modelDTO.setMakeId(modelAdapter.getMakeId()); modelDTO.setModelName(ViewUtils.getText(model)); modelId = ContentUris .parseId(resolver.insert(Model.CONTENT_URI, ModelDTO.buildContentValues(modelDTO))); } vehicle.setModelId(modelId); if (!ViewUtils.isEmpty(year)) { vehicle.setYear(Integer.valueOf(ViewUtils.getText(year))); } return VehicleDTO.buildContentValues(vehicle); }
From source file:com.example.gaurav.sunshine.app.FetchWeatherTask.java
/** * Helper method to handle insertion of a new location in the weather database. * * @param locationSetting The location string used to request updates from the server. * @param cityName A human-readable city name, e.g "Mountain View" * @param lat the latitude of the city//from w ww. ja v a 2 s . c o m * @param lon the longitude of the city * @return the row ID of the added location. */ long addLocation(String locationSetting, String cityName, double lat, double lon) { // Students: First, check if the location with this city name exists in the db // If it exists, return the current ID // Otherwise, insert it using the content resolver and the base URI long rowId; final ContentResolver resolver = mContext.getContentResolver(); Uri uri = Uri.parse(WeatherContract.BASE_CONTENT_URI + "/" + WeatherContract.PATH_LOCATION); String selectionArgs[] = { WeatherContract.LocationEntry.COLUMN_CITY_NAME }; String selection = WeatherContract.LocationEntry.COLUMN_CITY_NAME + " =? "; //First, query database to check if this location already exists. Cursor cursor = resolver.query(uri, null, selection, new String[] { cityName }, null); if (cursor.moveToNext()) return Long.parseLong(cursor.getString(cursor.getColumnIndex(WeatherContract.LocationEntry._ID))); else { ContentValues values = new ContentValues(); values.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName); values.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting); values.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, lat); values.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon); //resolver.insert(uri, values); return Long.parseLong(resolver.insert(uri, values).getLastPathSegment()); } // return -1; }
From source file:org.jsharkey.sky.WebserviceHelper.java
/** * Perform a webservice query to retrieve and store the forecast for the * given widget. This call blocks until request is finished and * {@link Forecasts#CONTENT_URI} has been updated. *//*from w w w . j av a 2s. c o m*/ public static void updateForecasts(Context context, Uri appWidgetUri, int days) throws ForecastParseException { Uri appWidgetForecasts = Uri.withAppendedPath(appWidgetUri, AppWidgets.TWIG_FORECASTS); ContentResolver resolver = context.getContentResolver(); Cursor cursor = null; double lat = Double.NaN; double lon = Double.NaN; // Pull exact forecast location from database try { cursor = resolver.query(appWidgetUri, PROJECTION_APPWIDGET, null, null, null); if (cursor != null && cursor.moveToFirst()) { lat = cursor.getDouble(COL_LAT); lon = cursor.getDouble(COL_LON); } } finally { if (cursor != null) { cursor.close(); } } // Query webservice for this location List<Forecast> forecasts = queryLocation(lat, lon, days); if (forecasts == null || forecasts.size() == 0) { throw new ForecastParseException("No forecasts found from webservice query"); } // Purge existing forecasts covered by incoming data, and anything // before today long lastMidnight = ForecastUtils.getLastMidnight(); long earliest = Long.MAX_VALUE; for (Forecast forecast : forecasts) { earliest = Math.min(earliest, forecast.validStart); } resolver.delete(appWidgetForecasts, ForecastsColumns.VALID_START + " >= " + earliest + " OR " + ForecastsColumns.VALID_START + " <= " + lastMidnight, null); // Insert any new forecasts found ContentValues values = new ContentValues(); for (Forecast forecast : forecasts) { Log.d(TAG, "inserting forecast with validStart=" + forecast.validStart); values.clear(); values.put(ForecastsColumns.VALID_START, forecast.validStart); values.put(ForecastsColumns.TEMP_HIGH, forecast.tempHigh); values.put(ForecastsColumns.TEMP_LOW, forecast.tempLow); values.put(ForecastsColumns.CONDITIONS, forecast.conditions); values.put(ForecastsColumns.URL, forecast.url); if (forecast.alert) { values.put(ForecastsColumns.ALERT, ForecastsColumns.ALERT_TRUE); } resolver.insert(appWidgetForecasts, values); } // Mark widget cache as being updated values.clear(); values.put(AppWidgetsColumns.LAST_UPDATED, System.currentTimeMillis()); resolver.update(appWidgetUri, values, null, null); }