Example usage for android.net Uri fromFile

List of usage examples for android.net Uri fromFile

Introduction

In this page you can find the example usage for android.net Uri fromFile.

Prototype

public static Uri fromFile(File file) 

Source Link

Document

Creates a Uri from a file.

Usage

From source file:com.example.research.whatis.MainActivity.java

protected void startCameraActivity() {

    Uri outputFileUri = Uri.fromFile(sdImageMainDirectory);

    Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
    intent.putExtra("outPutURI", outputFileUri);

    startActivityForResult(intent, 0);//from www.j  ava 2 s .c om
}

From source file:org.mobisocial.corral.CorralDownloadClient.java

/**
 * Synchronized method that retrieves content by any possible transport, and
 * returns a uri representing it locally. This method blocks until the file
 * is available locally, or it has been determined that the file cannot
 * currently be fetched./*www.  j  a  va2  s  .com*/
 */
Uri fetchContent(DbObj obj, CorralDownloadFuture future, DownloadProgressCallback callback) throws IOException {
    if (obj.getJson() == null || !obj.getJson().has(OBJ_LOCAL_URI)) {
        if (DBG) {
            Log.d(TAG, "no local uri for obj.");
        }
        return null;
    }
    if (mObjectManager.isObjectFromLocalDevice(obj.getLocalId())) {
        try {
            // TODO: Objects shared out from the content corral should
            // be accessible through the content corral. We don't have
            // to copy all files but we should have the option to create
            // a locate cache.
            return Uri.parse(obj.getJson().getString(OBJ_LOCAL_URI));
        } catch (JSONException e) {
            Log.e(TAG, "json exception getting local uri", e);
            return null;
        }
    }

    DbIdentity user = obj.getSender();
    if (user == null) {
        throw new IOException("Null user in corral");
    }
    File localFile = localFileForContent(obj, false);
    if (localFile.exists()) {
        return Uri.fromFile(localFile);
    }

    try {
        if (userAvailableOnLan(user)) {
            return doMediaScan(getFileOverLan(user, obj, future, callback));
        }
    } catch (IOException e) {
        if (DBG)
            Log.d(TAG, "Failed to pull LAN file", e);
    }

    try {
        return doMediaScan(CorralHelper.downloadContent(mContext, localFile, obj, future, callback));
    } catch (IOException e) {
        if (DBG)
            Log.d(TAG, "Failed to pull Corral file", e);
    }

    try {
        return doMediaScan(getFileOverBluetooth(user, obj, future, callback));
    } catch (IOException e) {
    }

    if (!localFile.exists()) {
        callback.onProgress(DownloadState.TRANSFER_COMPLETE, DownloadChannel.NONE,
                DownloadProgressCallback.FAILURE);
        throw new IOException("Failed to fetch file");
    }

    callback.onProgress(DownloadState.TRANSFER_COMPLETE, DownloadChannel.NONE,
            DownloadProgressCallback.SUCCESS);
    return doMediaScan(Uri.fromFile(localFile));
}

From source file:com.samuelcastro.cordova.InstagramSharePlugin.java

private void shareVideo(String videoString, String captionString) {

    // Create the URI from the media
    File media = new File(this.getRealVideoPathFromURI(Uri.parse(videoString)));
    Uri uri = Uri.fromFile(media);

    Intent shareIntent = new Intent(Intent.ACTION_SEND);
    shareIntent.setType("video/*");
    shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
    shareIntent.putExtra(Intent.EXTRA_TEXT, captionString);
    shareIntent.setPackage("com.instagram.android");

    this.cordova.startActivityForResult((CordovaPlugin) this, shareIntent, 12345);

}

From source file:com.snipme.record.Record.java

/**
 * Creates a JSONObject that represents a File from the Uri
 *
 * @param data the Uri of the audio/image/video
 * @return a JSONObject that represents a File
 * @throws IOException//w w w.  j a v a2s  .co m
 */
private JSONObject createMediaFile(Uri data) {
    File fp = webView.getResourceApi().mapUriToFile(data);
    JSONObject obj = new JSONObject();

    Class webViewClass = webView.getClass();
    PluginManager pm = null;
    try {
        Method gpm = webViewClass.getMethod("getPluginManager");
        pm = (PluginManager) gpm.invoke(webView);
    } catch (NoSuchMethodException e) {
    } catch (IllegalAccessException e) {
    } catch (InvocationTargetException e) {
    }
    if (pm == null) {
        try {
            Field pmf = webViewClass.getField("pluginManager");
            pm = (PluginManager) pmf.get(webView);
        } catch (NoSuchFieldException e) {
        } catch (IllegalAccessException e) {
        }
    }
    FileUtils filePlugin = (FileUtils) pm.getPlugin("File");
    LocalFilesystemURL url = filePlugin.filesystemURLforLocalPath(fp.getAbsolutePath());

    try {
        // File properties
        obj.put("name", fp.getName());
        obj.put("fullPath", fp.toURI().toString());
        if (url != null) {
            obj.put("localURL", url.toString());
        }
        // Because of an issue with MimeTypeMap.getMimeTypeFromExtension() all .3gpp files
        // are reported as video/3gpp. I'm doing this hacky check of the URI to see if it
        // is stored in the audio or video content store.
        if (fp.getAbsoluteFile().toString().endsWith(".3gp")
                || fp.getAbsoluteFile().toString().endsWith(".3gpp")) {
            if (data.toString().contains("/audio/")) {
                obj.put("type", AUDIO_3GPP);
            } else {
                obj.put("type", VIDEO_3GPP);
            }
        } else {
            obj.put("type", FileHelper.getMimeType(Uri.fromFile(fp), cordova));
        }

        obj.put("lastModifiedDate", fp.lastModified());
        obj.put("size", fp.length());
    } catch (JSONException e) {
        // this will never happen
        e.printStackTrace();
    }
    return obj;
}

From source file:com.github.notizklotz.derbunddownloader.issuesgrid.DownloadedIssuesActivity.java

private void openPDF(String uri) {
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.fromFile(new File(uri)), MEDIA_TYPE_PDF);
    intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

    PackageManager packageManager = getPackageManager();
    assert packageManager != null;

    if (intent.resolveActivity(packageManager) != null) {
        startActivity(intent);/*  ww w. j a v  a 2 s .  c o m*/
    } else {
        Toast.makeText(this, R.string.no_pdf_reader, Toast.LENGTH_LONG).show();
    }
}

From source file:com.cyberocw.habittodosecretary.file.StorageHelper.java

/**
 * Creates a fiile to be used as attachment.
 *///from ww w.j  a  va 2 s.c  o  m
public static FileVO createAttachmentFromUri(Context mContext, Uri uri, boolean moveSource) {
    String name = FileHelper.getNameFromUri(mContext, uri);
    String extension = FileHelper.getFileExtension(name).toLowerCase(Locale.getDefault());
    File f;
    if (moveSource) {
        f = createNewAttachmentFile(mContext, extension);
        try {
            FileUtils.moveFile(new File(uri.getPath()), f);
        } catch (IOException e) {
            //Log.e(Constants.TAG, "Can't move file " + uri.getPath());
        }
    } else {
        //getExternalFilesDir   ? ? 
        f = StorageHelper.createExternalStoragePrivateFile(mContext, uri, extension);
    }
    FileVO mAttachment = null;
    if (f != null) {
        mAttachment = new FileVO(Uri.fromFile(f), StorageHelper.getMimeTypeInternal(mContext, uri));
        mAttachment.setName(name);
        mAttachment.setSize(f.length());
    }
    return mAttachment;
}

From source file:com.mercandalli.android.apps.files.file.FileAddDialog.java

@SuppressWarnings("PMD.AvoidUsingHardCodedIP")
public FileAddDialog(@NonNull final Activity activity, final int id_file_parent,
        @Nullable final IListener listener, @Nullable final IListener dismissListener) {
    super(activity, R.style.DialogFullscreen);
    mActivity = activity;//from w w w  .  ja v a2  s . c  om
    mDismissListener = dismissListener;
    mFileParentId = id_file_parent;
    mListener = listener;

    setContentView(R.layout.dialog_add_file);
    setCancelable(true);

    final View rootView = findViewById(R.id.dialog_add_file_root);
    rootView.startAnimation(AnimationUtils.loadAnimation(mActivity, R.anim.dialog_add_file_open));
    rootView.setOnClickListener(this);

    findViewById(R.id.dialog_add_file_upload_file).setOnClickListener(this);
    findViewById(R.id.dialog_add_file_add_directory).setOnClickListener(this);

    findViewById(R.id.dialog_add_file_text_doc).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            DialogUtils.prompt(mActivity, mActivity.getString(R.string.dialog_file_create_txt),
                    mActivity.getString(R.string.dialog_file_name_interrogation),
                    mActivity.getString(R.string.dialog_file_create),
                    new DialogUtils.OnDialogUtilsStringListener() {
                        @Override
                        public void onDialogUtilsStringCalledBack(String text) {
                            //TODO create a online txt with content
                            Toast.makeText(getContext(), getContext().getString(R.string.not_implemented),
                                    Toast.LENGTH_SHORT).show();
                        }
                    }, mActivity.getString(android.R.string.cancel), null);
            FileAddDialog.this.dismiss();
        }
    });

    findViewById(R.id.dialog_add_file_scan).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            // Ensure that there's a camera activity to handle the intent
            if (takePictureIntent.resolveActivity(mActivity.getPackageManager()) != null) {
                // Create the File where the photo should go
                ApplicationActivity.sPhotoFile = createImageFile();
                // Continue only if the File was successfully created
                if (ApplicationActivity.sPhotoFile != null) {
                    if (listener != null) {
                        ApplicationActivity.sPhotoFileListener = listener;
                    }
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                            Uri.fromFile(ApplicationActivity.sPhotoFile.getFile()));
                    mActivity.startActivityForResult(takePictureIntent, ApplicationActivity.REQUEST_TAKE_PHOTO);
                }
            }
            FileAddDialog.this.dismiss();
        }
    });

    findViewById(R.id.dialog_add_file_add_timer).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            final Calendar currentTime = Calendar.getInstance();

            DialogDatePicker dialogDate = new DialogDatePicker(mActivity,
                    new DatePickerDialog.OnDateSetListener() {
                        @Override
                        public void onDateSet(DatePicker view, final int year, final int monthOfYear,
                                final int dayOfMonth) {

                            Calendar currentTime = Calendar.getInstance();

                            DialogTimePicker dialogTime = new DialogTimePicker(mActivity,
                                    new TimePickerDialog.OnTimeSetListener() {
                                        @Override
                                        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                                            Log.d("TIme Picker", hourOfDay + ":" + minute);

                                            final SimpleDateFormat dateFormatGmt = new SimpleDateFormat(
                                                    "yyyy-MM-dd HH:mm:ss", Locale.US);
                                            dateFormatGmt.setTimeZone(TimeZone.getTimeZone("UTC"));
                                            final SimpleDateFormat dateFormatLocal = new SimpleDateFormat(
                                                    "yyyy-MM-dd HH:mm:ss", Locale.US);

                                            String nowAsISO = dateFormatGmt.format(new Date());

                                            final JSONObject json = new JSONObject();
                                            try {
                                                json.put("type", "timer");
                                                json.put("date_creation", nowAsISO);
                                                json.put("timer_date",
                                                        "" + dateFormatGmt.format(dateFormatLocal.parse(year
                                                                + "-" + (monthOfYear + 1) + "-" + dayOfMonth
                                                                + " " + hourOfDay + ":" + minute + ":00")));

                                                final SimpleDateFormat dateFormatGmtTZ = new SimpleDateFormat(
                                                        "yyyy-MM-dd'T'HH-mm'Z'", Locale.US);
                                                dateFormatGmtTZ.setTimeZone(TimeZone.getTimeZone("UTC"));
                                                nowAsISO = dateFormatGmtTZ.format(new Date());

                                                final List<StringPair> parameters = new ArrayList<>();
                                                parameters.add(new StringPair("content", json.toString()));
                                                parameters.add(new StringPair("name", "TIMER_" + nowAsISO));
                                                parameters.add(
                                                        new StringPair("id_file_parent", "" + id_file_parent));
                                                new TaskPost(mActivity,
                                                        Constants.URL_DOMAIN + Config.ROUTE_FILE,
                                                        new IPostExecuteListener() {
                                                            @Override
                                                            public void onPostExecute(JSONObject json,
                                                                    String body) {
                                                                if (listener != null) {
                                                                    listener.execute();
                                                                }
                                                            }
                                                        }, parameters).execute();
                                            } catch (JSONException | ParseException e) {
                                                Log.e(getClass().getName(), "Failed to convert Json", e);
                                            }

                                        }
                                    }, currentTime.get(Calendar.HOUR_OF_DAY), currentTime.get(Calendar.MINUTE),
                                    true);
                            dialogTime.show();

                        }
                    }, currentTime.get(Calendar.YEAR), currentTime.get(Calendar.MONTH),
                    currentTime.get(Calendar.DAY_OF_MONTH));
            dialogDate.show();

            FileAddDialog.this.dismiss();
        }
    });

    findViewById(R.id.dialog_add_file_article).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            DialogCreateArticle dialogCreateArticle = new DialogCreateArticle(mActivity, listener);
            dialogCreateArticle.show();
            FileAddDialog.this.dismiss();
        }
    });

    FileAddDialog.this.show();
}

From source file:br.com.anteros.vendas.gui.AnexoCadastroActivity.java

/**
 * Carrega os dados do objeto Anexo na view.
 *//* ww  w.  j  av a 2 s.  c o m*/
private void carregaDadosParaView() {
    edDescricao.setText(anexo.getNome());

    File imgFile = null;

    if (anexo.hasConteudo()) {
        fileName = anexo.getNome();
        imgFile = new File(anexo.getConteudoPath());
    } else {
        imgFile = new File(filePath, fileName);
    }

    if (imgFile.exists()) {
        atribuiImageParaFotoGaleria(imgFile);
        imgFoto.setImageBitmap(fotoGaleria);
        imgVisualizar.setEnabled(true);
    } else {
        imgFoto.setImageDrawable(getResources().getDrawable(R.drawable.ic_arquivo_nao_encontrado));
        imgVisualizar.setEnabled(false);
    }

    /**
     * Obtm a URI referente ao arquivo anexo
     */
    mUri = Uri.fromFile(imgFile);
}

From source file:com.example.carsharing.ShortWayActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    photouri = Uri
            .fromFile(new File(this.getExternalFilesDir(Environment.DIRECTORY_PICTURES), IMAGE_FILE_NAME2));
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_short_way);

    activity_drawer = new Drawer(this, R.id.short_way_layout);
    mDrawerToggle = activity_drawer.newdrawer();
    mDrawerLayout = activity_drawer.setDrawerLayout();

    bdriver = true;/*from   www.j  a  va 2s.  c  o  m*/

    // 
    SharedPreferences sharedPref = this.getSharedPreferences(getString(R.string.PreferenceDefaultName),
            Context.MODE_PRIVATE);
    UserPhoneNumber = sharedPref.getString(getString(R.string.PreferenceUserPhoneNumber), "0");

    // 
    standard_date = new SimpleDateFormat("yyyy-MM-dd", Locale.SIMPLIFIED_CHINESE);
    primary_date = new SimpleDateFormat("yyyyMMdd", Locale.SIMPLIFIED_CHINESE);
    standard_time = new SimpleDateFormat("HH:mm:ss", Locale.SIMPLIFIED_CHINESE);
    primary_time = new SimpleDateFormat("HHmmss", Locale.SIMPLIFIED_CHINESE);

    queue = Volley.newRequestQueue(this);

    exchange = (ImageView) findViewById(R.id.shortway_exchange);
    exchange.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            String temp = startplace.getText().toString();
            if (!temp.equals("") && !endplace.getText().toString().equals("")) {
                startplace.setText(endplace.getText().toString());
                endplace.setText(temp);
                float a, b;
                a = startplace_longitude;
                b = startplace_latitude;
                startplace_longitude = destination_longitude;
                startplace_latitude = destination_latitude;
                destination_longitude = a;
                destination_latitude = b;

            }
        }
    });

    datebutton = (Button) findViewById(R.id.shortway_dates);
    earlystarttime = (Button) findViewById(R.id.shortway_earliest_start_time);
    latestarttime = (Button) findViewById(R.id.shortway_latest_start_time);
    increase = (Button) findViewById(R.id.shortway_increase);
    decrease = (Button) findViewById(R.id.shortway_decrease);
    s2 = (TextView) findViewById(R.id.shortway_count);
    startplace = (Button) findViewById(R.id.shortway_startplace);
    endplace = (Button) findViewById(R.id.shortway_endplace);
    sure = (Button) findViewById(R.id.shortway_sure);

    commute = findViewById(R.id.drawer_commute);
    shortway = findViewById(R.id.drawer_shortway);
    longway = findViewById(R.id.drawer_longway);
    setting = findViewById(R.id.drawer_setting);
    personalcenter = findViewById(R.id.drawer_personalcenter);
    about = findViewById(R.id.drawer_respond);
    taxi = findViewById(R.id.drawer_taxi);

    drawericon = (ImageView) findViewById(R.id.drawer_icon);
    drawername = (TextView) findViewById(R.id.drawer_name);
    drawernum = (TextView) findViewById(R.id.drawer_phone);
    carbrand = (EditText) findViewById(R.id.shortway_CarBrand);
    model = (EditText) findViewById(R.id.shortway_CarModel);
    color = (EditText) findViewById(R.id.shortway_color);
    licensenum = (EditText) findViewById(R.id.shortway_Num);

    licensenum.addTextChangedListener(numTextWatcher);
    carbrand.addTextChangedListener(detTextWatcher);
    color.addTextChangedListener(coTextWatcher);
    model.addTextChangedListener(moTextWatcher);

    next = (Button) findViewById(R.id.shortway_sure);
    next.setEnabled(false);
    db = new DatabaseHelper(ShortWayActivity.this, "test", null, 1);
    db1 = db.getWritableDatabase();

    final TextView content = (TextView) findViewById(R.id.shortway_content);
    mRadio1 = (RadioButton) findViewById(R.id.shortway_radioButton1);
    mRadio2 = (RadioButton) findViewById(R.id.shortway_radioButton2);
    shortway_group = (RadioGroup) findViewById(R.id.shortway_radiobutton01);
    star1 = (ImageView) findViewById(R.id.shortway_star);
    star2 = (ImageView) findViewById(R.id.shortway_star01);

    // judge the value of "pre_page"
    Bundle bundle = this.getIntent().getExtras();
    String PRE_PAGE = bundle.getString("pre_page");
    if (PRE_PAGE.compareTo("ReOrder") == 0) { // 
        startplace.setText(bundle.getString("stpusername") + "," + bundle.getString("stpmapname"));
        bstart = true;
        endplace.setText(bundle.getString("epusername") + "," + bundle.getString("epmapname"));
        bend = true;
        startplace_longitude = bundle.getFloat("stpx");
        Log.e("startplace_longitude", String.valueOf(startplace_longitude));
        startplace_latitude = bundle.getFloat("stpy");
        Log.e("startplace_latitude", String.valueOf(startplace_latitude));
        destination_longitude = bundle.getFloat("epx");
        Log.e("destination_longitude", String.valueOf(destination_longitude));
        destination_latitude = bundle.getFloat("epy");
        Log.e("destination_latitude", String.valueOf(destination_latitude));
        datebutton.setText(bundle.getString("re_short_startdate"));
        bdate = true;
        earlystarttime.setText(bundle.getString("re_short_starttime"));
        best = true;
        latestarttime.setText(bundle.getString("re_short_endtime"));
        blst = true;
    }
    // judge the value of "pre_page"

    about.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            mDrawerLayout.closeDrawer(findViewById(R.id.left_drawer));
            Intent about = new Intent(ShortWayActivity.this, AboutActivity.class);
            startActivity(about);
        }
    });
    setting.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            mDrawerLayout.closeDrawer(findViewById(R.id.left_drawer));
            Intent setting = new Intent(ShortWayActivity.this, SettingActivity.class);
            startActivity(setting);
        }
    });

    // database
    db = new DatabaseHelper(getApplicationContext(), UserPhoneNumber, null, 1);
    db1 = db.getWritableDatabase();

    // database end

    star1.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {

            if (bstart) {
                if (Pointisliked(StartPointMapName)) {
                    // Define 'where' part of query.
                    String selection = getString(R.string.dbstring_PlaceMapName) + " LIKE ?";
                    // Specify arguments in placeholder order.
                    String[] selelectionArgs = { StartPointMapName };
                    // Issue SQL statement.
                    db1.delete(getString(R.string.dbtable_placeliked), selection, selelectionArgs);
                    star1.setImageResource(R.drawable.ic_action_not_important);

                } else {
                    ContentValues content = new ContentValues();
                    content.put(getString(R.string.dbstring_PlaceUserName), StartPointUserName);
                    content.put(getString(R.string.dbstring_PlaceMapName), StartPointMapName);
                    content.put(getString(R.string.dbstring_longitude), startplace_longitude);
                    content.put(getString(R.string.dbstring_latitude), startplace_latitude);
                    db1.insert(getString(R.string.dbtable_placeliked), null, content);

                    // Define 'where' part of query.
                    String selection = getString(R.string.dbstring_PlaceMapName) + " LIKE ?";
                    // Specify arguments in placeholder order.
                    String[] selelectionArgs = { StartPointMapName };
                    // Issue SQL statement.
                    db1.delete(getString(R.string.dbtable_placehistory), selection, selelectionArgs);
                    star1.setImageResource(R.drawable.ic_action_important);
                }

            }

        }
    });
    star2.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {

            if (bend) {
                if (Pointisliked(EndPointMapName)) {
                    // Define 'where' part of query.
                    String selection = getString(R.string.dbstring_PlaceMapName) + " LIKE ?";
                    // Specify arguments in placeholder order.
                    String[] selelectionArgs = { EndPointMapName };
                    // Issue SQL statement.
                    db1.delete(getString(R.string.dbtable_placeliked), selection, selelectionArgs);
                    star2.setImageResource(R.drawable.ic_action_not_important);

                } else {
                    ContentValues content = new ContentValues();
                    content.put(getString(R.string.dbstring_PlaceUserName), EndPointUserName);
                    content.put(getString(R.string.dbstring_PlaceMapName), EndPointMapName);
                    content.put(getString(R.string.dbstring_longitude), destination_longitude);
                    content.put(getString(R.string.dbstring_latitude), destination_latitude);
                    db1.insert(getString(R.string.dbtable_placeliked), null, content);

                    // Define 'where' part of query.
                    String selection = getString(R.string.dbstring_PlaceMapName) + " LIKE ?";
                    // Specify arguments in placeholder order.
                    String[] selelectionArgs = { EndPointMapName };
                    // Issue SQL statement.
                    db1.delete(getString(R.string.dbtable_placehistory), selection, selelectionArgs);
                    star2.setImageResource(R.drawable.ic_action_important);
                }

            }

        }
    });

    taxi.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            mDrawerLayout.closeDrawer(findViewById(R.id.left_drawer));
        }
    });

    personalcenter.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            mDrawerLayout.closeDrawer(findViewById(R.id.left_drawer));
            Intent personalcenter = new Intent(ShortWayActivity.this, PersonalCenterActivity.class);

            startActivity(personalcenter);
        }
    });

    shortway.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            mDrawerLayout.closeDrawer(findViewById(R.id.left_drawer));
        }
    });

    longway.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            mDrawerLayout.closeDrawer(findViewById(R.id.left_drawer));
            Intent longway = new Intent(ShortWayActivity.this, MainActivity.class);
            startActivity(longway);
        }
    });

    commute.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            mDrawerLayout.closeDrawer(findViewById(R.id.left_drawer));
            Intent commute = new Intent(ShortWayActivity.this, CommuteActivity.class);
            commute.putExtra("pre_page", "Drawer");
            startActivity(commute);
        }
    });

    // RadioGroup
    shortway_group.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup arg0, int checkedId) {
            // TODO Auto-generated method stub18
            // ID

            // """"textView
            if (checkedId == mRadio2.getId()) {
                bpassenager = true;
                bdriver = false;

                licensenum.setEnabled(false);
                carbrand.setEnabled(false);
                color.setEnabled(false);
                model.setEnabled(false);

                licensenum.setFilters(new InputFilter[] { new InputFilter() {
                    @Override
                    public CharSequence filter(CharSequence source, int start, int end, Spanned dest,
                            int dstart, int dend) {
                        return source.length() < 1 ? dest.subSequence(dstart, dend) : "";
                    }
                } });
                carbrand.setFilters(new InputFilter[] { new InputFilter() {
                    @Override
                    public CharSequence filter(CharSequence source, int start, int end, Spanned dest,
                            int dstart, int dend) {
                        return source.length() < 1 ? dest.subSequence(dstart, dend) : "";
                    }
                } });
                color.setFilters(new InputFilter[] { new InputFilter() {
                    @Override
                    public CharSequence filter(CharSequence source, int start, int end, Spanned dest,
                            int dstart, int dend) {
                        return source.length() < 1 ? dest.subSequence(dstart, dend) : "";
                    }
                } });
                model.setFilters(new InputFilter[] { new InputFilter() {
                    @Override
                    public CharSequence filter(CharSequence source, int start, int end, Spanned dest,
                            int dstart, int dend) {
                        return source.length() < 1 ? dest.subSequence(dstart, dend) : "";
                    }
                } });
                content.setText(getString(R.string.warningInfo_seatNeed));
                licensenum.setHintTextColor(Color.parseColor("#cccccc"));
                carbrand.setHintTextColor(Color.parseColor("#cccccc"));
                color.setHintTextColor(Color.parseColor("#cccccc"));
                model.setHintTextColor(Color.parseColor("#cccccc"));
                licensenum.setInputType(InputType.TYPE_NULL);
                carbrand.setInputType(InputType.TYPE_NULL);
                color.setInputType(InputType.TYPE_NULL);
                model.setInputType(InputType.TYPE_NULL);
            } else {
                bpassenager = false;
                bdriver = true;

                licensenum.setEnabled(true);
                carbrand.setEnabled(true);
                color.setEnabled(true);
                model.setEnabled(true);

                licensenum.setFilters(new InputFilter[] { new InputFilter() {
                    @Override
                    public CharSequence filter(CharSequence source, int start, int end, Spanned dest,
                            int dstart, int dend) {

                        return null;
                    }
                } });
                carbrand.setFilters(new InputFilter[] { new InputFilter() {
                    @Override
                    public CharSequence filter(CharSequence source, int start, int end, Spanned dest,
                            int dstart, int dend) {
                        return null;
                    }
                } });
                color.setFilters(new InputFilter[] { new InputFilter() {
                    @Override
                    public CharSequence filter(CharSequence source, int start, int end, Spanned dest,
                            int dstart, int dend) {

                        return null;
                    }
                } });
                model.setFilters(new InputFilter[] { new InputFilter() {
                    @Override
                    public CharSequence filter(CharSequence source, int start, int end, Spanned dest,
                            int dstart, int dend) {

                        return null;
                    }
                } });
                content.setText(getString(R.string.warningInfo_seatOffer));
                licensenum.setHintTextColor(Color.parseColor("#9F35FF"));
                carbrand.setHintTextColor(Color.parseColor("#9F35FF"));
                color.setHintTextColor(Color.parseColor("#9F35FF"));
                model.setHintTextColor(Color.parseColor("#9F35FF"));
                // licensenum.setText("");
                // carbrand.setText("");
                // color.setText("");
                // model.setText("");
                licensenum.setInputType(InputType.TYPE_CLASS_TEXT);
                carbrand.setInputType(InputType.TYPE_CLASS_TEXT);
                color.setInputType(InputType.TYPE_CLASS_TEXT);
                model.setInputType(InputType.TYPE_CLASS_TEXT);

                // start!
                selectcarinfo(UserPhoneNumber);
                // end!
            }
            confirm();
        }

    });

    sure.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            if (shortway_group.getCheckedRadioButtonId() == mRadio1.getId())
                userrole = "d";
            else
                userrole = "p";

            // start!
            shortway_request(UserPhoneNumber, datebutton.getText().toString(),
                    earlystarttime.getText().toString(), latestarttime.getText().toString());
            // end!

        }

        private void shortway_request(final String shortway_phonenum, final String shortway_date,
                final String shortway_starttime, final String shortway_endtime) {
            // TODO Auto-generated method stub

            // start
            try {
                test_date = primary_date.parse(shortway_date);
                standard_shortway_startdate = standard_date.format(test_date);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            try {
                test_date = primary_time.parse(shortway_starttime);
                standard_shortway_starttime = standard_time.format(test_date);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            try {
                test_date = primary_time.parse(shortway_endtime);
                standard_shortway_endtime = standard_time.format(test_date);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            // end!

            String shortway_baseurl = getString(R.string.uri_base) + getString(R.string.uri_ShortwayRequest)
                    + getString(R.string.uri_addrequest_action);
            // "http://192.168.1.111:8080/CarsharingServer/ShortwayRequest!addrequest.action?";

            Log.w("URL", shortway_baseurl);
            StringRequest stringRequest = new StringRequest(Request.Method.POST, shortway_baseurl,
                    new Response.Listener<String>() {

                        @Override
                        public void onResponse(String response) {
                            Log.d("shortway_result", response);
                            JSONObject json1 = null;
                            try {
                                json1 = new JSONObject(response);
                                requestok = json1.getBoolean("result");
                            } catch (JSONException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                            if (requestok == true) {

                                if (carinfochoosing_type == 1) {
                                    // add
                                    // start!
                                    carinfo(shortway_phonenum, licensenum.getText().toString(),
                                            carbrand.getText().toString(), model.getText().toString(),
                                            color.getText().toString(), String.valueOf(sum), 1);
                                    // end!
                                } else {
                                    // update
                                    // start!
                                    carinfo(shortway_phonenum, licensenum.getText().toString(),
                                            carbrand.getText().toString(), model.getText().toString(),
                                            color.getText().toString(), String.valueOf(sum), 2);
                                    // end!
                                }

                                Intent sure = new Intent(ShortWayActivity.this, OrderResponseActivity.class);
                                sure.putExtra(getString(R.string.request_response), "true");
                                sure.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                startActivity(sure);
                            } else {
                                // Toast errorinfo =
                                // Toast.makeText(getApplicationContext(),
                                // "", Toast.LENGTH_LONG);
                                // errorinfo.show();
                                Intent sure = new Intent(ShortWayActivity.this, OrderResponseActivity.class);
                                sure.putExtra(getString(R.string.request_response), "false");
                            }
                        }

                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Log.e("shortway_result", error.getMessage(), error);
                            // Toast errorinfo = Toast.makeText(null,
                            // "", Toast.LENGTH_LONG);
                            // errorinfo.show();
                            Intent sure = new Intent(ShortWayActivity.this, OrderResponseActivity.class);
                            sure.putExtra(getString(R.string.request_response), "false");
                            sure.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            startActivity(sure);
                        }
                    }) {
                protected Map<String, String> getParams() {
                    // POSTgetParams

                    // start
                    try {
                        test_date = primary_date.parse(shortway_date);
                        standard_shortway_startdate = standard_date.format(test_date);
                    } catch (ParseException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    try {
                        test_date = primary_time.parse(shortway_starttime);
                        standard_shortway_starttime = standard_time.format(test_date);
                    } catch (ParseException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    try {
                        test_date = primary_time.parse(shortway_endtime);
                        standard_shortway_endtime = standard_time.format(test_date);
                    } catch (ParseException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    // end!

                    Map<String, String> params = new HashMap<String, String>();
                    params.put("phonenum", shortway_phonenum);
                    params.put("userrole", userrole);
                    params.put("startplacex", String.valueOf(startplace_longitude));
                    params.put("startplacey", String.valueOf(startplace_latitude));
                    params.put(getString(R.string.uri_startplace), startplace.getText().toString());
                    params.put("destinationx", String.valueOf(destination_longitude));
                    params.put("destinationy", String.valueOf(destination_latitude));
                    params.put(getString(R.string.uri_destination), endplace.getText().toString());
                    params.put("startdate", standard_shortway_startdate);
                    params.put("starttime", standard_shortway_starttime);
                    params.put("endtime", standard_shortway_endtime);

                    return params;
                }
            };

            queue.add(stringRequest);
        }
    });

    startplace.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            startActivityForResult(new Intent(ShortWayActivity.this, ChooseAddressActivity.class), 1);
        }
    });

    endplace.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            startActivityForResult(new Intent(ShortWayActivity.this, ChooseArrivalActivity.class), 2);
        }
    });

    increase.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            sum++;
            s2.setText("" + sum);
            confirm();
        }
    });

    decrease.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            sum--;
            if (sum < 0) {
                sum = 0;
            }
            s2.setText("" + sum);
            confirm();
        }
    });

    datebutton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            showDialog(DATE_DIALOG);
        }
    });

    earlystarttime.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            showDialog(TIME_DIALOG);
        }
    });
    latestarttime.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            showDialog(TIME_DIALOG1);

        }
    });

}

From source file:com.dnielfe.manager.AppManager.java

@Override
public boolean onContextItemSelected(MenuItem item) {
    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
    int index = info.position;
    String packagename = mAppList.get(index).packageName;

    switch (item.getItemId()) {
    case ID_LAUNCH:
        Intent i = pm.getLaunchIntentForPackage(packagename);
        startActivity(i);/*from w w w. j  a v  a2  s  .c o m*/
        break;

    case ID_MANAGE:
        startActivity(new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
                Uri.parse("package:" + packagename)));
        break;

    case ID_UNINSTALL:
        Intent i1 = new Intent(Intent.ACTION_DELETE);
        i1.setData(Uri.parse("package:" + packagename));
        startActivity(i1);
        get_downloaded_apps();
        break;

    case ID_MARKET:
        Intent intent1 = new Intent(Intent.ACTION_VIEW);
        intent1.setData(Uri.parse("market://details?id=" + packagename));
        startActivity(intent1);
        break;

    case ID_SEND:
        try {
            ApplicationInfo info1 = pm.getApplicationInfo(packagename, 0);
            String source_dir = info1.sourceDir;
            File file = new File(source_dir);
            Uri uri11 = Uri.fromFile(file.getAbsoluteFile());

            Intent infointent = new Intent(Intent.ACTION_SEND);
            infointent.setType("application/zip");
            infointent.putExtra(Intent.EXTRA_STREAM, uri11);
            startActivity(Intent.createChooser(infointent, getString(R.string.share)));
        } catch (Exception e) {
            Toast.makeText(AppManager.this, "Error", Toast.LENGTH_SHORT).show();
        }
        break;
    }
    return false;
}