Example usage for android.os Environment DIRECTORY_PICTURES

List of usage examples for android.os Environment DIRECTORY_PICTURES

Introduction

In this page you can find the example usage for android.os Environment DIRECTORY_PICTURES.

Prototype

String DIRECTORY_PICTURES

To view the source code for android.os Environment DIRECTORY_PICTURES.

Click Source Link

Document

Standard directory in which to place pictures that are available to the user.

Usage

From source file:tjs.tuneramblr.CheckinFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.checkin, container, false);

    // get a handle on the UI elements
    addSongButton = (Button) view.findViewById(R.id.addButton);
    takePhotoButton = (Button) view.findViewById(R.id.takePhotoBtn);
    trackNameText = (TextView) view.findViewById(R.id.trackNameText);
    artistNameText = (TextView) view.findViewById(R.id.artistNameText);
    albumNameText = (TextView) view.findViewById(R.id.albumNameText);
    doingWhatText = (EditText) view.findViewById(R.id.doing_what);

    // update the track display
    populateTrackDisplay(getActivity().getApplicationContext());

    // listeners//from ww w.  j  ava 2  s.  c om
    addSongButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            ILastLocationFinder locationFinder = PlatformSpecificImplementationFactory
                    .getLastLocationFinder(v.getContext());

            TrackInfoDS tids = new TrackInfoDS(v.getContext());

            // build an Intent to send over to the checkin service
            Intent trackCheckinIntent = new Intent(v.getContext(), TrackCheckinService.class);
            trackCheckinIntent.putExtra(TuneramblrConstants.EXTRA_IMG_URI_KEY, imageUri);
            trackCheckinIntent.putExtra(TuneramblrConstants.EXTRA_LOCATION_KEY, locationFinder
                    .getLastBestLocation(TuneramblrConstants.MAX_DISTANCE, TuneramblrConstants.MAX_TIME));
            trackCheckinIntent.putExtra(TuneramblrConstants.EXTRA_TRACK_CHECKIN_TYPE_KEY,
                    CheckinType.USER_LIKE);
            trackCheckinIntent.putExtra(TuneramblrConstants.EXTRA_DOING_WHAT_KEY,
                    doingWhatText.getText().toString());

            tids.open();
            trackCheckinIntent.putExtra(TuneramblrConstants.EXTRA_TRACK_INFO_KEY, tids.getLastRecordedTrack());
            tids.close();

            v.getContext().startService(trackCheckinIntent);

            // notify the user that the track has been sent
            Toast songResultText = Toast.makeText(v.getContext(), R.string.songSubmitted, Toast.LENGTH_LONG);
            songResultText.show();

            // clear the image URI
            imageUri = null;

            // clear the text area
            doingWhatText.setText("");
        }
    });

    takePhotoButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            // use the stock camera and save the image to some location on
            // the phone/SDCARD
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            imageUri = getImageUri();
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            startActivityForResult(intent, TuneramblrMobileActivity.TAKE_PHOTO_CODE);
        }

        /** Create a File for saving an image */
        public File buildOutputMediaFile() {

            File mediaStorageDir = new File(
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                    "tuneramblr");

            // Create the storage directory if it does not exist
            if (!mediaStorageDir.exists()) {
                if (!mediaStorageDir.mkdirs()) {
                    Log.d("tuneramblr", "failed to create directory");
                    return null;
                }
            }

            // Create a media file name
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            File mediaFile;
            mediaFile = new File(mediaStorageDir.getPath(), "IMG_TR_" + timeStamp + ".jpg");

            return mediaFile;
        }

        /**
         * Get the uri of the captured file
         * 
         * @return A Uri which path is the path of an image file, stored on
         *         the dcim folder
         */
        public Uri getImageUri() {
            // Store image in dcim
            File file = buildOutputMediaFile();
            Uri imu = Uri.fromFile(file);

            return imu;
        }
    });

    // this is just to update the UI as new track information is received.
    // this uses the meta media intent filter.
    getActivity().registerReceiver(new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {

            // pull the track info from the intent
            String track = intent.getStringExtra("track");
            String artist = intent.getStringExtra("artist");
            String album = intent.getStringExtra("album");

            // update the UI elements
            trackNameText.setText(track);
            artistNameText.setText(artist);
            albumNameText.setText(album);

        }
    }, MetaMediaRequester.buildMediaIntentFilter());

    return view;
}

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

@Override
protected void onCreate(Bundle savedInstanceState) {
    photouri = Uri//from   w  w  w.  jav  a 2s.c o m
            .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;

    // 
    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.albedinsky.android.support.intent.ImageIntent.java

/**
 * Same as {@link #createContentFile(String,  String)} with <b>.jpg</b> suffix for the specified
 * <var>fileName</var> (if it does not contain any) and {@link Environment#DIRECTORY_PICTURES}
 * as <var>externalDirectoryType</var>.
 *
 * @param fileName The desired name for the image file.
 * @see #createImageFile()//ww w  .j ava 2s.com
 */
@Nullable
public static File createImageFile(@NonNull String fileName) {
    return createContentFile(appendDefaultFileSuffixIfNotPresented(fileName, ".jpg"),
            Environment.DIRECTORY_PICTURES);
}

From source file:com.mahhaus.scanloto.ScannerActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_document_scan);
    //Set the flag to keep the screen on (otherwise the screen may go dark during scanning)
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    imageViewResult = (ImageView) findViewById(R.id.image_result);
    errorMessageLayout = (FrameLayout) findViewById(R.id.error_message_layout);
    errorMessage = (TextView) findViewById(R.id.textViewResult);

    documentScanView = (DocumentScanView) findViewById(R.id.document_scan_view);
    // add a camera open listener that will be called when the camera is opened or an error occurred
    //  this is optional (if not set a RuntimeException will be thrown if an error occurs)
    documentScanView.setCameraOpenListener(ScannerActivity.this);
    // the view can be configured via a json file in the assets, and this config is set here
    // (alternatively it can be configured via xml, see the Energy Example for that)
    documentScanView.setConfigFromAsset("document_view_config.json");

    // Optional: Set a ratio you want the documents to be restricted to. default is set to DIN_AX
    //documentScanView.setDocumentRatios(DocumentScanView.DocumentRatio.DIN_AX_PORTRAIT.getRatio());

    // Optional: Set a maximum deviation for the ratio. 0.15 is the default
    //documentScanView.setMaxDocumentRatioDeviation(0.15);

    // initialize Anyline with the license key and a Listener that is called if a result is found
    documentScanView.initAnyline(getString(R.string.anyline_license_key), new DocumentResultListener() {
        //            @Override
        //            public void onResult(AnylineImage transformedImage, AnylineImage fullFrame, List<PointF> documentOutline) {
        ////from ww w  .  j a v a 2  s.co m
        //
        //            }

        @Override
        public void onResult(AnylineImage transformedImage, AnylineImage fullFrame) {
            errorMessage.setText(fullFrame.toString());
            // handle the result document images here
            if (progressDialog != null && progressDialog.isShowing()) {
                progressDialog.dismiss();
            }

            imageViewResult
                    .setImageBitmap(Bitmap.createScaledBitmap(transformedImage.getBitmap(), 100, 160, false));

            /**
             * IMPORTANT: cache provided frames here, and release them at the end of this onResult. Because
             * keeping them in memory (e.g. setting the full frame to an ImageView)
             * will result in a OutOfMemoryError soon. This error is reported in {@link #onTakePictureError
             * (Throwable)}
             *
             * Use a DiskCache http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html#disk-cache
             * for example
             *
             */
            File outDir = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "ok");
            outDir.mkdir();
            // change the file ending to png if you want a png
            File outFile = new File(outDir, "" + System.currentTimeMillis() + ".jpg");
            try {
                // convert the transformed image into a gray scaled image internally
                // transformedImage.getGrayCvMat(false);
                // get the transformed image as bitmap
                // Bitmap bmp = transformedImage.getBitmap();
                // save the image with quality 100 (only used for jpeg, ignored for png)
                transformedImage.save(outFile, 100);
                showToast(getString(R.string.document_image_saved_to) + " " + outFile.getAbsolutePath());
            } catch (IOException e) {
                e.printStackTrace();
            }

            // release the images
            transformedImage.release();
            fullFrame.release();

        }

        @Override
        public void onPreviewProcessingSuccess(AnylineImage anylineImage) {
            // this is called after the preview of the document is completed, and a full picture will be
            // processed automatically
        }

        @Override
        public void onPreviewProcessingFailure(DocumentScanView.DocumentError documentError) {
            // this is called on any error while processing the document image
            // Note: this is called every time an error occurs in a run, so that might be quite often
            // An error message should only be presented to the user after some time

            showErrorMessageFor(documentError);
        }

        @Override
        public void onPictureProcessingFailure(DocumentScanView.DocumentError documentError) {

            showErrorMessageFor(documentError, true);
            if (progressDialog != null && progressDialog.isShowing()) {
                progressDialog.dismiss();
            }

            // if there is a problem, here is how images could be saved in the error case
            // this will be a full, not cropped, not transformed image
            AnylineImage image = documentScanView.getCurrentFullImage();

            if (image != null) {
                File outDir = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "error");
                outDir.mkdir();
                File outFile = new File(outDir,
                        "" + System.currentTimeMillis() + documentError.name() + ".jpg");
                try {
                    image.save(outFile, 100);
                    Log.d(TAG, "error image saved to " + outFile.getAbsolutePath());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                image.release();
            }
        }

        @Override
        public boolean onDocumentOutlineDetected(List<PointF> list, boolean documentShapeAndBrightnessValid) {
            // is called when the outline of the document is detected. return true if the outline is consumed by
            // the implementation here, false if the outline should be drawn by the DocumentScanView
            lastOutline = list; // saving the outline for the animations
            return false;
        }

        @Override
        public void onTakePictureSuccess() {
            // this is called after the image has been captured from the camera and is about to be processed
            progressDialog = ProgressDialog.show(ScannerActivity.this, "", "", true);

            if (errorMessageAnimator != null && errorMessageAnimator.isRunning()) {
                errorMessageAnimator.cancel();
                errorMessageLayout.setVisibility(View.GONE);
            }
        }

        @Override
        public void onTakePictureError(Throwable throwable) {
            // This is called if the image could not be captured from the camera (most probably because of an
            // OutOfMemoryError)
            throw new RuntimeException(throwable);
        }

    });

    // optionally stop the scan once a valid result was returned
    // documentScanView.cancelOnResult(true);

}

From source file:com.rnd.snapsplit.view.OcrCaptureFragment.java

/**
 * Initializes the UI and creates the detector pipeline.
 *//*from  w  w  w  .j a  v a2  s.c om*/
//    @Override
//    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//
//        if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
//            Toast.makeText(getContext(), "pic saved", Toast.LENGTH_LONG).show();
//            Log.d("CameraDemo", "Pic saved");
//        }
//    }

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    final View view = inflater.inflate(R.layout.view_ocr_capture, container, false);
    final Activity activity = getActivity();
    final Context context = getContext();

    ((Toolbar) activity.findViewById(R.id.tool_bar_hamburger))
            .setBackgroundColor(ContextCompat.getColor(context, android.R.color.transparent));
    final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
            + "/picFolder/";
    File newdir = new File(dir);
    newdir.mkdirs();

    mPreview = (CameraSourcePreview) view.findViewById(R.id.preview);
    mGraphicOverlay = (GraphicOverlay<OcrGraphic>) view.findViewById(R.id.graphicOverlay);

    StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
    StrictMode.setVmPolicy(builder.build());

    // Set good defaults for capturing text.
    boolean autoFocus = true;
    boolean useFlash = false;

    //        createNewThread();
    //        t.start();

    final ImageView upArrow = (ImageView) view.findViewById(R.id.arrow_up);
    upArrow.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (rotationAngle == 0) { // arrow up
                //mCameraSource.takePicture(null, mPicture);
                //mGraphicOverlay.clear();
                //                    mGraphicOverlay.clear();
                //                    mGraphicOverlay.amountItem = null;
                onPause();
                //shouldContinue = false;
                //mCamera.takePicture(null, null, mPicture);

                File pictureFile = getOutputMediaFile();
                if (pictureFile == null) {
                    return;
                }
                try {
                    FileOutputStream fos = new FileOutputStream(pictureFile);
                    Bitmap receiptBitmap = byteStreamToBitmap(mCameraSource.mostRecentBitmap);
                    receiptBitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos);
                    picPath = pictureFile.getAbsolutePath();
                    //fos.write(mCameraSource.mostRecentBitmap);
                    fos.close();
                } catch (FileNotFoundException e) {

                } catch (IOException e) {
                }

                upArrow.animate().rotation(180).setDuration(500).start();

                TextView amount = (TextView) view.findViewById(R.id.text_amount_value);
                if (mGraphicOverlay.amountItem == null) {
                    amount.setText("0.00");
                } else {
                    amount.setText(String.format("%.2f", mGraphicOverlay.amountItemAfterFormat));
                }
                TextView desc = (TextView) view.findViewById(R.id.text_name_value);
                desc.setText(mGraphicOverlay.description);

                RelativeLayout box = (RelativeLayout) view.findViewById(R.id.recognition_box);
                box.setVisibility(View.VISIBLE);
                Animation slide_up = AnimationUtils.loadAnimation(activity.getApplicationContext(),
                        R.anim.slide_up);

                box.startAnimation(slide_up);
                rotationAngle = 180;

            } else {
                //                    t.interrupt();
                //                    t = null;
                RelativeLayout box = (RelativeLayout) view.findViewById(R.id.recognition_box);
                Animation slide_down = AnimationUtils.loadAnimation(activity.getApplicationContext(),
                        R.anim.slide_down);

                upArrow.animate().rotation(0).setDuration(500).start();

                box.startAnimation(slide_down);
                box.setVisibility(View.INVISIBLE);
                //shouldContinue = true;
                mGraphicOverlay.amountItem = null;
                mGraphicOverlay.amountItemAfterFormat = 0f;
                mGraphicOverlay.description = "";
                onResume();
                //                    createNewThread();
                //                    t.start();
                rotationAngle = 0;
            }
        }
    });

    ImageView addButton = (ImageView) view.findViewById(R.id.add_icon);
    addButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // takePicture();
            EditText description = (EditText) view.findViewById(R.id.text_name_value);
            EditText amount = (EditText) view.findViewById(R.id.text_amount_value);
            float floatAmount = Float.parseFloat(amount.getText().toString());
            Summary t = new Summary(description.getText().toString(), floatAmount);

            Bundle bundle = new Bundle();
            bundle.putSerializable("splitTransaction", t);

            //                 ByteArrayOutputStream stream = new ByteArrayOutputStream();
            //                 mCameraSource.mostRecentBitmap.compress(Bitmap.CompressFormat.PNG, 80, stream);
            //                 byte[] byteArray = stream.toByteArray();
            //Bitmap receiptBitmap = byteStreamToBitmap(mCameraSource.mostRecentBitmap);
            //bundle.putParcelable("receiptPicture",receiptBitmap);
            bundle.putString("receiptPicture", picPath);

            FriendsSelectionFragment fragment = new FriendsSelectionFragment();
            fragment.setArguments(bundle);

            ((Toolbar) activity.findViewById(R.id.tool_bar_hamburger)).setVisibility(View.INVISIBLE);
            getActivity().getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragment_holder, fragment, "FriendsSelectionFragment").addToBackStack(null)
                    .commit();
        }
    });

    // Check for the camera permission before accessing the camera.  If the
    // permission is not granted yet, request permission.
    int rc = ActivityCompat.checkSelfPermission(context, Manifest.permission.CAMERA);
    if (rc == PackageManager.PERMISSION_GRANTED) {
        createCameraSource(autoFocus, useFlash);
    } else {
        requestCameraPermission();
    }

    gestureDetector = new GestureDetector(context, new CaptureGestureListener());
    scaleGestureDetector = new ScaleGestureDetector(context, new ScaleListener());

    //        Snackbar.make(mGraphicOverlay, "Tap to Speak. Pinch/Stretch to zoom",
    //                Snackbar.LENGTH_LONG)
    //                .show();

    // Set up the Text To Speech engine.
    TextToSpeech.OnInitListener listener = new TextToSpeech.OnInitListener() {
        @Override
        public void onInit(final int status) {
            if (status == TextToSpeech.SUCCESS) {
                Log.d("OnInitListener", "Text to speech engine started successfully.");
                tts.setLanguage(Locale.US);
            } else {
                Log.d("OnInitListener", "Error starting the text to speech engine.");
            }
        }
    };
    tts = new TextToSpeech(activity.getApplicationContext(), listener);

    return view;
}

From source file:MainActivity.java

private File getPictureFile() {
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(System.currentTimeMillis());
    String fileName = "PHOTO_" + timeStamp + ".jpg";
    return new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), fileName);
}

From source file:com.wit.android.support.content.intent.ImageIntent.java

/**
 * Same as {@link #createContentFile(String, String, String)} with <b>.jpg</b> as <var>fileType</var>
 * and {@link Environment#DIRECTORY_PICTURES} as <var>environmentDirectoryType</var>.
 *
 * @param fileName Desired name for the image file.
 * @see #createImageFile()//from www  . j  a v  a2s.  com
 */
@Nullable
public static File createImageFile(@NonNull String fileName) {
    return createContentFile(fileName, ".jpg", Environment.DIRECTORY_PICTURES);
}

From source file:com.github.piasy.rxqrcode.RxQrCode.java

public static Observable<File> generateQrCodeFile(Context context, String content, int width, int height) {
    return Observable.fromEmitter(emitter -> {
        MultiFormatWriter writer = new MultiFormatWriter();
        Bitmap origin = null;//from w ww . ja  v a  2s  .  c o m
        Bitmap scaled = null;
        try {
            BitMatrix bm = writer.encode(content, BarcodeFormat.QR_CODE, QR_CODE_LENGTH, QR_CODE_LENGTH,
                    Collections.singletonMap(EncodeHintType.MARGIN, 0));
            origin = Bitmap.createBitmap(QR_CODE_LENGTH, QR_CODE_LENGTH, Bitmap.Config.ARGB_8888);

            for (int i = 0; i < QR_CODE_LENGTH; i++) {
                for (int j = 0; j < QR_CODE_LENGTH; j++) {
                    origin.setPixel(i, j, bm.get(i, j) ? Color.BLACK : Color.WHITE);
                }
            }
            scaled = Bitmap.createScaledBitmap(origin, width, height, true);
            File dir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
            if (dir == null) {
                emitter.onError(new IllegalStateException("external file system unavailable!"));
                return;
            }
            String fileName = "rx_qr_" + System.currentTimeMillis() + ".png";
            File localFile = new File(dir, fileName);

            FileOutputStream outputStream = new FileOutputStream(localFile);
            scaled.compress(Bitmap.CompressFormat.PNG, 85, outputStream);
            outputStream.flush();
            outputStream.close();

            emitter.onNext(localFile);
            emitter.onCompleted();
        } catch (WriterException | IOException e) {
            emitter.onError(e);
        } finally {
            if (origin != null) {
                origin.recycle();
            }
            if (scaled != null) {
                scaled.recycle();
            }
        }
    }, Emitter.BackpressureMode.BUFFER);
}

From source file:com.xengar.android.booksearch.ui.BookDetailActivity.java

public Uri getLocalBitmapUri(ImageView imageView) {
    // Extract Bitmap from ImageView drawable
    Drawable drawable = imageView.getDrawable();
    Bitmap bmp = null;//  w w  w .j  av  a 2  s.  c om
    if (drawable instanceof BitmapDrawable) {
        bmp = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
    } else {
        return null;
    }
    // Store image to default external storage directory
    Uri bmpUri = null;
    try {
        File file = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES),
                "share_image_" + System.currentTimeMillis() + ".png");
        file.getParentFile().mkdirs();
        FileOutputStream out = new FileOutputStream(file);
        bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
        out.close();
        bmpUri = Uri.fromFile(file);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return bmpUri;
}

From source file:me.piebridge.prevent.ui.UserGuideActivity.java

private File getQrCode() {
    File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    if (dir == null) {
        return null;
    }//from w w  w.j a v  a 2s .  c  o  m
    if (!checkPermission()) {
        return null;
    }
    File screenshots = new File(dir, "Screenshots");
    if (!screenshots.exists()) {
        screenshots.mkdirs();
    }
    return new File(screenshots, "pr_donate.png");
}