android.net.Uri Java Examples

The following examples show how to use android.net.Uri. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Notification.java    From phonegapbootcampsite with MIT License 6 votes vote down vote up
/**
 * Beep plays the default notification ringtone.
 *
 * @param count     Number of times to play notification
 */
public void beep(long count) {
    Uri ringtone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    Ringtone notification = RingtoneManager.getRingtone(this.cordova.getActivity().getBaseContext(), ringtone);

    // If phone is not set to silent mode
    if (notification != null) {
        for (long i = 0; i < count; ++i) {
            notification.play();
            long timeout = 5000;
            while (notification.isPlaying() && (timeout > 0)) {
                timeout = timeout - 100;
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                }
            }
        }
    }
}
 
Example #2
Source File: AppUtils.java    From BmapLite with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Get the value of the data column for this Uri. This is useful for
 * MediaStore Uris, and other file-based ContentProviders.
 *
 * @param context       The context.
 * @param uri           The Uri to query.
 * @param selection     (Optional) Filter used in the query.
 * @param selectionArgs (Optional) Selection arguments used in the query.
 * @return The value of the _data column, which is typically a file path.
 */
public static String getDataColumn(Context context, Uri uri, String selection,
                                   String[] selectionArgs) {

    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = {column};

    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                null);
        if (cursor != null && cursor.moveToFirst()) {
            final int column_index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(column_index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}
 
Example #3
Source File: DBUtils.java    From sana.mobile with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Converts any Uri query string into a select statement by taking
 * every key value pair in the query into "key = 'value'".
 *
 * @param uri
 * @return
 */
public static String convertUriQueryToSelect(Uri uri) {
    String qString = uri.getQuery();
    // Shortcut out for null query
    if (TextUtils.isEmpty(qString))
        return null;
    StringBuilder select = new StringBuilder();
    String[] rawQuery = uri.getQuery().split(",");
    for (int index = 0; index < rawQuery.length; index++) {
        String[] kv = rawQuery[index].split("=");
        // append space after first key value pair
        if (index > 0) select.append(" ");
        select.append(String.format("%s LIKE '%s'", kv[0], kv[1]));
    }
    return select.toString();
}
 
Example #4
Source File: ContactsController.java    From TelePlus-Android with GNU General Public License v2.0 6 votes vote down vote up
private void deleteContactFromPhoneBook(int uid) {
    if (!hasContactsPermission()) {
        return;
    }
    synchronized (observerLock) {
        ignoreChanges = true;
    }
    try {
        ContentResolver contentResolver = ApplicationLoader.applicationContext.getContentResolver();
        Uri rawContactUri = ContactsContract.RawContacts.CONTENT_URI.buildUpon().appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "true").appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_NAME, systemAccount.name).appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_TYPE, systemAccount.type).build();
        int value = contentResolver.delete(rawContactUri, ContactsContract.RawContacts.SYNC2 + " = " + uid, null);
    } catch (Exception e) {
        FileLog.e(e);
    }
    synchronized (observerLock) {
        ignoreChanges = false;
    }
}
 
Example #5
Source File: ChatSessionAdapter.java    From Zom-Android-XMPP with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void setGroupChatSubject(String subject) throws RemoteException {
    try {
        if (isGroupChatSession()) {
            ChatGroup group = (ChatGroup)mChatSession.getParticipant();
            getGroupManager().setGroupSubject(group, subject);

            //update the database
            ContentValues values1 = new ContentValues(1);
            values1.put(Imps.Contacts.NICKNAME,subject);
            ContentValues values = values1;

            Uri uriContact = ContentUris.withAppendedId(Imps.Contacts.CONTENT_URI, mContactId);
            mContentResolver.update(uriContact, values, null, null);

        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #6
Source File: ChanUrls.java    From Ouroboros with GNU General Public License v3.0 6 votes vote down vote up
public static String getImageUrl(String boardName, String tim, String ext){
    Uri.Builder builder = new Uri.Builder();

    if (isOldTim(tim)) {
        // Some older files use an old path including the board name.
        builder.scheme(SCHEME)
            .authority(DOMAIN_NAME)
            .appendPath(boardName)
            .appendPath(OLD_IMAGE_DIRECTORY)
            .appendPath(tim + ext)
            .build();
    } else {
        builder.scheme(SCHEME)
            .authority(DOMAIN_NAME)
            .appendPath(IMAGE_DIRECTORY)
            .appendPath(tim + ext)
            .build();
    }

    return builder.toString();
}
 
Example #7
Source File: HelperActivity.java    From MultipleImageSelect with Apache License 2.0 6 votes vote down vote up
private void showAppPermissionSettings() {
    Snackbar snackbar = Snackbar.make(
            view,
            getString(R.string.permission_force),
            Snackbar.LENGTH_INDEFINITE)
            .setAction(getString(R.string.permission_settings), new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Uri uri = Uri.fromParts(
                            getString(R.string.permission_package),
                            HelperActivity.this.getPackageName(),
                            null);

                    Intent intent = new Intent();
                    intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                    intent.setData(uri);
                    startActivityForResult(intent, Constants.PERMISSION_REQUEST_CODE);
                }
            });

    /*((TextView) snackbar.getView()
            .findViewById(android.support.design.R.id.snackbar_text)).setMaxLines(maxLines);*/
    snackbar.show();
}
 
Example #8
Source File: Connection.java    From PS4-Payload-Sender-Android with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Get the value of the data column for this Uri. This is useful for
 * MediaStore Uris, and other file-based ContentProviders.
 *
 * @param context The context.
 * @param uri The Uri to query.
 * @param selection (Optional) Filter used in the query.
 * @param selectionArgs (Optional) Selection arguments used in the query.
 * @return The value of the _data column, which is typically a file path.
 */
private static String getDataColumn(Context context, Uri uri, String selection,
                                    String[] selectionArgs) {

    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = {
            column
    };

    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                null);
        if (cursor != null && cursor.moveToFirst()) {
            final int column_index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(column_index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}
 
Example #9
Source File: MediaDocumentsProvider.java    From FireFiles with Apache License 2.0 6 votes vote down vote up
@Override
public ParcelFileDescriptor openDocument(String docId, String mode, CancellationSignal signal)
        throws FileNotFoundException {

    if (!"r".equals(mode)) {
        throw new IllegalArgumentException("Media is read-only");
    }

    final Uri target = getUriForDocumentId(docId);

    // Delegate to real provider
    final long token = Binder.clearCallingIdentity();
    try {
        return getContext().getContentResolver().openFileDescriptor(target, mode);
    } finally {
        Binder.restoreCallingIdentity(token);
    }
}
 
Example #10
Source File: Notification.java    From reader with MIT License 6 votes vote down vote up
/**
 * Beep plays the default notification ringtone.
 *
 * @param count     Number of times to play notification
 */
public void beep(final long count) {
    cordova.getThreadPool().execute(new Runnable() {
        public void run() {
            Uri ringtone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            Ringtone notification = RingtoneManager.getRingtone(cordova.getActivity().getBaseContext(), ringtone);

            // If phone is not set to silent mode
            if (notification != null) {
                for (long i = 0; i < count; ++i) {
                    notification.play();
                    long timeout = 5000;
                    while (notification.isPlaying() && (timeout > 0)) {
                        timeout = timeout - 100;
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                        }
                    }
                }
            }
        }
    });
}
 
Example #11
Source File: VLCUtil.java    From vlc-example-streamplayer with GNU General Public License v3.0 6 votes vote down vote up
/**
 * VLC authorize only "-._~" in Mrl format, android Uri authorize "_-!.~'()*".
 * Therefore, decode the characters authorized by Android Uri when creating an Uri from VLC.
 */
public static Uri UriFromMrl(String mrl) {
    final char array[] = mrl.toCharArray();
    final StringBuilder sb = new StringBuilder(array.length*2);
    for (int i = 0; i < array.length; ++i) {
        final char c = array[i];
        if (c == '%') {
            if (array.length - i >= 3) {
                try {
                    final int hex = Integer.parseInt(new String(array, i + 1, 2), 16);
                    if (URI_AUTHORIZED_CHARS.indexOf(hex) != -1) {
                        sb.append((char) hex);
                        i += 2;
                        continue;
                    }
                } catch (NumberFormatException ignored) {
                }
            }
        }
        sb.append(c);
    }

    return Uri.parse(sb.toString());
}
 
Example #12
Source File: ContextMenuUtil.java    From lrkFM with MIT License 6 votes vote down vote up
private void addOpenWithToMenu(FMFile f, ContextMenu menu) {
    menu.add(0, ID_OPEN_WITH, 0, activity.getString(R.string.open_with)).setOnMenuItemClickListener(item -> {
        Intent i = new Intent(Intent.ACTION_VIEW);
        String mimeType = FMFile.getMimeTypeFromFile(f);
        i.setDataAndType(Uri.fromFile(f.getFile()), mimeType);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        Intent chooser = Intent.createChooser(i, activity.getString(R.string.choose_application));

        if (i.resolveActivity(activity.getPackageManager()) != null) {
            if (activity.getPackageManager().queryIntentActivities(i, 0).size() == 1) {
                Toast.makeText(activity, R.string.only_one_app_to_handle_file, LENGTH_SHORT).show();
            }
            activity.startActivity(chooser);
        } else {
            Toast.makeText(activity, R.string.no_app_to_handle_file, LENGTH_SHORT).show();
        }

        return true;
    }).setVisible(!f.isDirectory());
}
 
Example #13
Source File: Camera.java    From OsmGo with MIT License 6 votes vote down vote up
/**
 * Save the modified image we've created to a temporary location, so we can
 * return a URI to it later
 * @param bitmap
 * @param contentUri
 * @param is
 * @return
 * @throws IOException
 */
private Uri saveTemporaryImage(Bitmap bitmap, Uri contentUri, InputStream is) throws IOException {
  String filename = contentUri.getLastPathSegment();
  if (!filename.contains(".jpg") && !filename.contains(".jpeg")) {
    filename += "." + (new java.util.Date()).getTime() + ".jpeg";
  }
  File cacheDir = getActivity().getCacheDir();
  File outFile = new File(cacheDir, filename);
  FileOutputStream fos = new FileOutputStream(outFile);
  byte[] buffer = new byte[1024];
  int len;
  while ((len = is.read(buffer)) != -1) {
    fos.write(buffer, 0, len);
  }
  fos.close();
  return Uri.fromFile(outFile);
}
 
Example #14
Source File: MainActivity.java    From JavaHTTPUpload with MIT License 6 votes vote down vote up
private void dispatchTakePictureIntent() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        // Create the File where the photo should go
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            // Error occurred while creating the File

        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
            		Uri.fromFile(photoFile));
            startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
        }
    }
}
 
Example #15
Source File: ManageStorePresenter.java    From aptoide-client-v8 with GNU General Public License v3.0 5 votes vote down vote up
private Completable saveData(ManageStoreViewModel storeModel) {
  return Single.fromCallable(() -> {
    if (storeModel.hasNewAvatar()) {
      return uriToPathResolver.getMediaStoragePath(Uri.parse(storeModel.getPictureUri()));
    }
    return "";
  })
      .flatMapCompletable(
          mediaStoragePath -> accountManager.createOrUpdate(storeModel.getStoreName(),
              storeModel.getStoreDescription(), mediaStoragePath, storeModel.hasNewAvatar(),
              storeModel.getStoreTheme()
                  .getThemeName(), storeModel.storeExists()));
}
 
Example #16
Source File: PermissionUtils.java    From Android-utils with Apache License 2.0 5 votes vote down vote up
/**
 * 去设置权限
 *
 * @param context ctx
 */
public static void toSetPermission(Context context) {
    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
    Uri uri = Uri.fromParts("package", UtilsApp.getApp().getPackageName(), null);
    intent.setData(uri);
    context.startActivity(intent);
}
 
Example #17
Source File: NewFriendAtPresenter.java    From LQRWeChat with MIT License 5 votes vote down vote up
private void agreeFriends(String friendId, LQRViewHolderForRecyclerView helper) {
    if (!NetUtils.isNetworkAvailable(mContext)) {
        UIUtils.showToast(UIUtils.getString(R.string.please_check_net));
        return;
    }
    ApiRetrofit.getInstance().agreeFriends(friendId)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .flatMap(new Func1<AgreeFriendsResponse, Observable<GetUserInfoByIdResponse>>() {
                @Override
                public Observable<GetUserInfoByIdResponse> call(AgreeFriendsResponse agreeFriendsResponse) {
                    if (agreeFriendsResponse != null && agreeFriendsResponse.getCode() == 200) {
                        helper.setViewVisibility(R.id.tvAdded, View.VISIBLE)
                                .setViewVisibility(R.id.btnAck, View.GONE);
                        return ApiRetrofit.getInstance().getUserInfoById(friendId);
                    }
                    return Observable.error(new ServerException(UIUtils.getString(R.string.agree_friend_fail)));
                }
            })
            .subscribe(getUserInfoByIdResponse -> {
                if (getUserInfoByIdResponse != null && getUserInfoByIdResponse.getCode() == 200) {
                    GetUserInfoByIdResponse.ResultEntity result = getUserInfoByIdResponse.getResult();
                    UserInfo userInfo = new UserInfo(UserCache.getId(), result.getNickname(), Uri.parse(result.getPortraitUri()));
                    if (TextUtils.isEmpty(userInfo.getPortraitUri().toString())) {
                        userInfo.setPortraitUri(Uri.parse(DBManager.getInstance().getPortraitUri(userInfo)));
                    }
                    Friend friend = new Friend(userInfo.getUserId(), userInfo.getName(), userInfo.getPortraitUri().toString());
                    DBManager.getInstance().saveOrUpdateFriend(friend);
                    UIUtils.postTaskDelay(() -> {
                        BroadcastManager.getInstance(UIUtils.getContext()).sendBroadcast(AppConst.UPDATE_FRIEND);
                        BroadcastManager.getInstance(UIUtils.getContext()).sendBroadcast(AppConst.UPDATE_CONVERSATIONS);
                    }, 1000);
                }
            }, this::loadError);
}
 
Example #18
Source File: HookPkgUninstallReceiver.java    From MiPushFramework with GNU General Public License v3.0 5 votes vote down vote up
@Override
public List<XC_MethodHook.Unhook> fetchHook() throws Exception {
    return Collections.singletonList(DexposedBridge.findAndHookMethod(Class.forName("com.xiaomi.push.service.receivers.PkgUninstallReceiver"),
            "onReceive", Context.class, Intent.class, new XC_MethodReplacement() {
                @Override
                protected Object replaceHookedMethod(MethodHookParam param) throws Throwable {
                    Context context = (Context) param.args[0];
                    Intent intent = (Intent) param.args[1];
                    if (intent != null && intent.getExtras() !=null) {
                        if ("android.intent.action.PACKAGE_REMOVED".equals(intent.getAction())) {
                            boolean isReplaced = intent.getExtras().getBoolean("android.intent.extra.REPLACING");
                            Uri data = intent.getData();
                            if (data != null && !isReplaced) {
                                try {
                                    Intent serviceIntent = new Intent(context, PushServiceMain.class);
                                    serviceIntent.setAction(PushServiceConstants.ACTION_UNINSTALL);
                                    serviceIntent.putExtra(PushServiceConstants.EXTRA_UNINSTALL_PKG_NAME, data.getEncodedSchemeSpecificPart());
                                    ContextCompat.startForegroundService(context, serviceIntent);
                                    GeoFenceUtils.appIsUninstalled(context.getApplicationContext(), data.getEncodedSchemeSpecificPart());
                                } catch (Throwable e) {
                                    logger.e("Hook", e);
                                }
                            }
                        }
                    }
                    return null;
                }
            }));
}
 
Example #19
Source File: PadContentProvider.java    From padland with Apache License 2.0 5 votes vote down vote up
/**
     * Insert into db
     * @param uri
     * @param values
     * @return
     */
    @Override
    public Uri insert(Uri uri, ContentValues values) {
        /**
         * Add a new record
         */
        long rowID;
        Uri _uri = null;
        switch (uriMatcher.match(uri)) {
            case PADLIST:
                rowID = db.insert(PAD_TABLE_NAME, "", values);
                ContentUris.withAppendedId(PADLIST_CONTENT_URI, rowID);
                break;
            case PADGROUP_LIST:
                rowID = db.insert(PADGROUP_TABLE_NAME, "", values);
                ContentUris.withAppendedId(PADGROUPS_CONTENT_URI, rowID);
                break;
            default:
                throw new IllegalArgumentException( "Unknown URI " + uri );
        }
        /**
         * If record is added successfully
         */
        if (rowID > 0)
        {
//            getContext().getContentResolver().notifyChange(_uri, null);
            return _uri;
        }
        throw new SQLException("Failed to add a record into " + uri);

    }
 
Example #20
Source File: TracksBrowser.java    From mobile-manager-tool with MIT License 5 votes vote down vote up
/**
  * @return number of albums from Bundle
  */
 public String getNumSongs() {
 	String[] projection = {
             BaseColumns._ID, ArtistColumns.ARTIST, ArtistColumns.NUMBER_OF_TRACKS
     };
 	Uri uri = Audio.Artists.EXTERNAL_CONTENT_URI;
     Long id = ApolloUtils.getArtistId(getArtist(), ARTIST_ID, this);
     Cursor cursor = null;
     try{
     	cursor = this.getContentResolver().query(uri, projection, BaseColumns._ID+ "=" + DatabaseUtils.sqlEscapeString(String.valueOf(id)), null, null);
     }
     catch(Exception e){
     	e.printStackTrace();
     }
     if(cursor == null)
     	return String.valueOf(0);
     int mArtistNumAlbumsIndex = cursor.getColumnIndexOrThrow(ArtistColumns.NUMBER_OF_TRACKS);
     if(cursor.getCount()>0){
  	cursor.moveToFirst();
      String numAlbums = cursor.getString(mArtistNumAlbumsIndex);
cursor.close();
      if(numAlbums != null){
      	return numAlbums;
      }
     }
     return String.valueOf(0);
 }
 
Example #21
Source File: ContentResolver.java    From AndroidComponentPlugin with Apache License 2.0 5 votes vote down vote up
@Override
public final @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode,
        @Nullable CancellationSignal signal) throws FileNotFoundException {
    try {
        if (mWrapped != null) return mWrapped.openAssetFile(uri, mode, signal);
    } catch (RemoteException e) {
        return null;
    }

    return openAssetFileDescriptor(uri, mode, signal);
}
 
Example #22
Source File: ContentService.java    From AndroidComponentPlugin with Apache License 2.0 5 votes vote down vote up
private int checkUriPermission(Uri uri, int pid, int uid, int modeFlags, int userHandle) {
    try {
        return ActivityManager.getService().checkUriPermission(
                uri, pid, uid, modeFlags, userHandle, null);
    } catch (RemoteException e) {
        return PackageManager.PERMISSION_DENIED;
    }
}
 
Example #23
Source File: OverclockingWidgetView.java    From rpicheck with MIT License 5 votes vote down vote up
private static PendingIntent getSelfPendingIntent(Context context, int appWidgetId, Uri uri, String action) {
    final Intent intent = new Intent(context, OverclockingWidget.class);
    intent.setAction(action);
    intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
    intent.setData(uri);
    return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
 
Example #24
Source File: FrescoUtil.java    From MyImageUtil with Apache License 2.0 5 votes vote down vote up
/**
 * 清除单张图片的磁盘缓存
 * @param url
 */
public static void clearCacheByUrl(String url){
    url = append(url);
    ImagePipeline imagePipeline = Fresco.getImagePipeline();
    Uri uri = Uri.parse(url);
   // imagePipeline.evictFromMemoryCache(uri);
    imagePipeline.evictFromDiskCache(uri);
    //imagePipeline.evictFromCache(uri);//这个包含了从内存移除和从硬盘移除
}
 
Example #25
Source File: MonsterInfoDescriptor.java    From PADListener with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @param monsterId the monsterId
 * @return the Uri to access one monster
 */
public static Uri uriById(long monsterId) {
	final Uri.Builder uriBuilder = CONTENT_URI.buildUpon();
	uriBuilder.appendPath(String.valueOf(monsterId));

	return uriBuilder.build();
}
 
Example #26
Source File: ChatActivity.java    From LoveTalkClient with Apache License 2.0 5 votes vote down vote up
public void selectImageFromCamera() {
	Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
	Uri imageUri = Uri.fromFile(new File(localCameraPath));
	openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
	startActivityForResult(openCameraIntent,
			TAKE_CAMERA_REQUEST);
}
 
Example #27
Source File: FragmentUser.java    From BigApp_WordPress_Android with Apache License 2.0 5 votes vote down vote up
@Override
public void onViewClick(View v) {
    int vId = v.getId();
    switch (vId) {
        case R.id.item_avatar:
            if (mDialogPicChooser == null) {
                mDialogPicChooser = new DialogPicChooser(mContext, new DialogPicChooser.OnModeChangedLisener() {
                    @Override
                    public void onModeChanged(int mode) {
                        if (mode == 1) {
                            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            mImagePath = SdCacheTools.getTempCacheDir(mContext.getApplicationContext()) + "/camera_" + System.currentTimeMillis() + "jpg";
                            File imageFile = new File(mImagePath);
                            intent.putExtra(MediaStore.EXTRA_OUTPUT,
                                    Uri.fromFile(imageFile));
                            startActivityForResult(intent, 1001);
                            return;
                        }
                        Intent intent = new Intent(Intent.ACTION_PICK);
                        intent.setType("image/*");//相片类型
                        startActivityForResult(intent, 1002);
                    }
                });
            }
            mDialogPicChooser.show();
            break;
        case R.id.item_nick_name:
            showEditDialog(R.string.v_user_edit_nick_name, nickName);
            break;
        case R.id.item_user_desc:
            ActivityUser.gotoFragmentModifyDescription(mContext);
            break;
        case R.id.item_pwd:
            ActivityUser.gotoFragmentModifyPwd(mContext);
            break;
    }
}
 
Example #28
Source File: PhoneNumberViewItem.java    From LibreTasks with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public View buildUI(DataType initData) {
  if (initData != null) {
    editText.setText(initData.getValue());
  }
  
  ContentResolver cr = activity.getContentResolver();
  List<String> contacts = new ArrayList<String>();
  // Form an array specifying which columns to return.
  String[] projection = new String[] {People.NAME, People.NUMBER };
  // Get the base URI for the People table in the Contacts content provider.
  Uri contactsUri = People.CONTENT_URI;
  // Make the query.
  Cursor cursor = cr.query(contactsUri, 
      projection, // Which columns to return
      null, // Which rows to return (all rows)
      null, // Selection arguments (none)
      Contacts.People.DEFAULT_SORT_ORDER);
  if (cursor.moveToFirst()) {
    String name;
    String phoneNumber;
    int nameColumn = cursor.getColumnIndex(People.NAME);
    int phoneColumn = cursor.getColumnIndex(People.NUMBER);
    do {
      // Get the field values of contacts
      name = cursor.getString(nameColumn);
      phoneNumber = cursor.getString(phoneColumn);
      contacts.add(name + ": " + phoneNumber);
    } while (cursor.moveToNext());
  }
  cursor.close();
  
  String[] contactsStr = new String[]{};
  ArrayAdapter<String> adapter = new ArrayAdapter<String>(activity,
      android.R.layout.simple_dropdown_item_1line, contacts.toArray(contactsStr));
  
  editText.setAdapter(adapter);
  editText.setThreshold(1);
  return(editText);
}
 
Example #29
Source File: MessagesActivity.java    From SlimSocial-for-Facebook with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void onExternalPageRequest(String url) {
    try {
        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
    } catch (ActivityNotFoundException e) {//this prevents the crash
        Log.e("shouldOverrideUrlLoad", "" + e.getMessage());
        e.printStackTrace();
    }
}
 
Example #30
Source File: AlbumDaoImpl.java    From kripton with Apache License 2.0 5 votes vote down vote up
/**
 * <h1>Content provider URI (INSERT operation):</h1>
 * <pre>content://com.abubusoft.kripton.example/albums</pre>
 *
 * <h2>JQL INSERT for Content Provider</h2>
 * <pre>INSERT INTO Album (artistId, name) VALUES (:artistId, :name)</pre>
 *
 * <h2>SQL INSERT for Content Provider</h2>
 * <pre>INSERT INTO album (artist_id, name) VALUES (:artistId, :name)</pre>
 *
 * <p><strong>Dynamic where statement is ignored, due no param with @BindSqlDynamicWhere was added.</strong></p>
 *
 * <p><strong>In URI, * is replaced with [*] for javadoc rapresentation</strong></p>
 *
 * @param uri "content://com.abubusoft.kripton.example/albums"
 * @param contentValues content values
 * @return new row's id
 */
long insert2ForContentProvider(Uri uri, ContentValues contentValues) {
  Logger.info("Execute INSERT for URI %s", uri.toString());
  KriptonContentValues _contentValues=contentValuesForContentProvider(contentValues);
  for (String columnName:_contentValues.values().keySet()) {
    if (!insert2ForContentProviderColumnSet.contains(columnName)) {
      throw new KriptonRuntimeException(String.format("For URI 'content://com.abubusoft.kripton.example/albums', column '%s' does not exists in table '%s' or can not be defined in this INSERT operation", columnName, "album" ));
    }
  }


  // log for content values -- BEGIN
  Object _contentValue;
  for (String _contentKey:_contentValues.values().keySet()) {
    _contentValue=_contentValues.values().get(_contentKey);
    if (_contentValue==null) {
      Logger.info("==> :%s = <null>", _contentKey);
    } else {
      Logger.info("==> :%s = '%s' (%s)", _contentKey, StringUtils.checkSize(_contentValue), _contentValue.getClass().getCanonicalName());
    }
  }
  // log for content values -- END
  // conflict algorithm NONE
  // insert operation
  long result = getDatabase().insert("album", 0, _contentValues.values());
  // support for livedata
  registryEvent(result>0?1:0);
  return result;
}