Example usage for android.app ProgressDialog setTitle

List of usage examples for android.app ProgressDialog setTitle

Introduction

In this page you can find the example usage for android.app ProgressDialog setTitle.

Prototype

@Override
    public void setTitle(CharSequence title) 

Source Link

Usage

From source file:fm.smart.r1.ItemActivity.java

public void addToList(final String item_id) {
    final ProgressDialog myOtherProgressDialog = new ProgressDialog(this);
    myOtherProgressDialog.setTitle("Please Wait ...");
    myOtherProgressDialog.setMessage("Adding item to study goal ...");
    myOtherProgressDialog.setIndeterminate(true);
    myOtherProgressDialog.setCancelable(true);

    final Thread add = new Thread() {
        public void run() {
            ItemActivity.add_item_result = new AddItemResult(
                    Main.lookup.addItemToGoal(Main.transport, Main.default_study_goal_id, item_id, null));

            myOtherProgressDialog.dismiss();
            ItemActivity.this.runOnUiThread(new Thread() {
                public void run() {
                    final AlertDialog dialog = new AlertDialog.Builder(ItemActivity.this).create();
                    dialog.setTitle(ItemActivity.add_item_result.getTitle());
                    dialog.setMessage(ItemActivity.add_item_result.getMessage());
                    ItemActivity.add_item_result = null;
                    dialog.setButton("OK", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                        }/*from   ww w.ja va 2  s.  c om*/
                    });

                    dialog.show();
                }
            });

        }
    };
    myOtherProgressDialog.setButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            add.interrupt();
        }
    });
    OnCancelListener ocl = new OnCancelListener() {
        public void onCancel(DialogInterface arg0) {
            add.interrupt();
        }
    };
    myOtherProgressDialog.setOnCancelListener(ocl);
    closeMenu();
    myOtherProgressDialog.show();
    add.start();
}

From source file:net.sylvek.sharemyposition.ShareMyPosition.java

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    default:/*from  w  w  w  .ja v  a2s  .c o m*/
        return super.onCreateDialog(id);
    case MAP_DLG:
        final View sharedMapView = LayoutInflater.from(this).inflate(R.layout.sharedmap, null);
        final FrameLayout map = (FrameLayout) sharedMapView.findViewById(R.id.sharedmap);
        map.addView(this.sharedMap);
        final CheckBox latlonAddress = (CheckBox) sharedMapView.findViewById(R.id.add_lat_lon_location);
        final CheckBox geocodeAddress = (CheckBox) sharedMapView.findViewById(R.id.add_address_location);
        final RadioButton nourl = (RadioButton) sharedMapView.findViewById(R.id.add_no_url_location);
        final RadioButton url = (RadioButton) sharedMapView.findViewById(R.id.add_url_location);
        final RadioButton gmap = (RadioButton) sharedMapView.findViewById(R.id.add_native_location);
        final EditText body = (EditText) sharedMapView.findViewById(R.id.body);
        final ToggleButton track = (ToggleButton) sharedMapView.findViewById(R.id.add_track_location);

        latlonAddress.setChecked(pref.getBoolean(PREF_LAT_LON_CHECKED, true));
        geocodeAddress.setChecked(pref.getBoolean(PREF_ADDRESS_CHECKED, true));
        final boolean isUrl = pref.getBoolean(PREF_URL_CHECKED, true);
        final boolean isGmap = pref.getBoolean(PREF_GMAP_CHECKED, false);
        url.setChecked(isUrl);
        gmap.setChecked(isGmap);
        nourl.setChecked(!isUrl && !isGmap);
        body.setText(pref.getString(PREF_BODY_DEFAULT, getString(R.string.body)));
        track.setChecked(pref.getBoolean(PREF_TRACK_CHECKED, false));

        if (track.isChecked()) {
            latlonAddress.setEnabled(false);
            latlonAddress.setChecked(false);
            geocodeAddress.setEnabled(false);
            geocodeAddress.setChecked(false);
            url.setEnabled(false);
            url.setChecked(true);
            gmap.setEnabled(false);
            gmap.setChecked(false);
            nourl.setEnabled(false);
            nourl.setChecked(false);
        }

        track.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                latlonAddress.setEnabled(!isChecked);
                latlonAddress.setChecked(!isChecked);
                geocodeAddress.setEnabled(!isChecked);
                geocodeAddress.setChecked(!isChecked);
                url.setEnabled(!isChecked);
                url.setChecked(true);
                gmap.setEnabled(!isChecked);
                gmap.setChecked(!isChecked);
                nourl.setEnabled(!isChecked);
                nourl.setChecked(!isChecked);
            }
        });

        return new AlertDialog.Builder(this).setTitle(R.string.app_name).setView(sharedMapView)
                .setOnCancelListener(new OnCancelListener() {

                    @Override
                    public void onCancel(DialogInterface arg0) {
                        finish();
                    }
                }).setNeutralButton(R.string.options, new OnClickListener() {

                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        /* needed to display neutral button */
                    }
                }).setPositiveButton(R.string.share_it, new OnClickListener() {

                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        final boolean isLatLong = ((CheckBox) sharedMapView
                                .findViewById(R.id.add_lat_lon_location)).isChecked();
                        final boolean isGeocodeAddress = ((CheckBox) sharedMapView
                                .findViewById(R.id.add_address_location)).isChecked();
                        final boolean isUrl = ((RadioButton) sharedMapView.findViewById(R.id.add_url_location))
                                .isChecked();
                        final boolean isGmap = ((RadioButton) sharedMapView
                                .findViewById(R.id.add_native_location)).isChecked();
                        final EditText body = (EditText) sharedMapView.findViewById(R.id.body);
                        final boolean isTracked = ((ToggleButton) sharedMapView
                                .findViewById(R.id.add_track_location)).isChecked();
                        final String uuid = UUID.randomUUID().toString();

                        pref.edit().putBoolean(PREF_LAT_LON_CHECKED, isLatLong)
                                .putBoolean(PREF_ADDRESS_CHECKED, isGeocodeAddress)
                                .putBoolean(PREF_URL_CHECKED, isUrl).putBoolean(PREF_GMAP_CHECKED, isGmap)
                                .putString(PREF_BODY_DEFAULT, body.getText().toString())
                                .putBoolean(PREF_TRACK_CHECKED, isTracked).commit();

                        final Intent t = new Intent(Intent.ACTION_SEND);
                        t.setType("text/plain");
                        t.addCategory(Intent.CATEGORY_DEFAULT);
                        final Intent share = Intent.createChooser(t, getString(R.string.app_name));
                        final GeoPoint p = sharedMap.getMapCenter();

                        final String text = body.getText().toString();
                        share(p.getLatitude(), p.getLongitude(), t, share, text, isGeocodeAddress, isUrl,
                                isGmap, isLatLong, isTracked, uuid);
                    }
                }).create();
    case PROGRESS_DLG:
        final ProgressDialog dlg = new ProgressDialog(this);
        dlg.setTitle(getText(R.string.app_name));
        dlg.setMessage(getText(R.string.progression_desc));
        dlg.setIndeterminate(true);
        dlg.setCancelable(true);
        dlg.setOnCancelListener(new OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                finish();
            }
        });
        return dlg;
    case PROVIDERS_DLG:
        return new AlertDialog.Builder(this).setTitle(R.string.app_name).setCancelable(false)
                .setIcon(android.R.drawable.ic_menu_help).setMessage(R.string.providers_needed)
                .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }

                }).setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent gpsProperty = new Intent(
                                android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivity(gpsProperty);
                    }
                }).create();
    }
}

From source file:org.namelessrom.devicecontrol.appmanager.AppDetailsActivity.java

private void uninstall() {
    // try via native package manager api
    AppHelper.uninstallPackage(mPm, mAppItem.getPackageName());

    // build our command
    final StringBuilder sb = new StringBuilder();

    sb.append(String.format("pm uninstall %s;", mAppItem.getPackageName()));

    if (mAppItem.isSystemApp()) {
        sb.append("busybox mount -o rw,remount /system;");
    }//w ww.ja v  a 2 s.  c  o m

    sb.append(String.format("rm -rf %s;", mAppItem.getApplicationInfo().publicSourceDir));
    sb.append(String.format("rm -rf %s;", mAppItem.getApplicationInfo().sourceDir));
    sb.append(String.format("rm -rf %s;", mAppItem.getApplicationInfo().dataDir));

    if (mAppItem.isSystemApp()) {
        sb.append("busybox mount -o ro,remount /system;");
    }

    final String cmd = sb.toString();
    Logger.v(this, cmd);

    // create the dialog (will not be shown for a long amount of time though)
    final ProgressDialog dialog;
    dialog = new ProgressDialog(this);
    dialog.setTitle(R.string.uninstalling);
    dialog.setMessage(getString(R.string.applying_wait));
    dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    dialog.setCancelable(false);

    new AsyncTask<Void, Void, Void>() {

        @Override
        protected void onPreExecute() {
            dialog.show();
        }

        @Override
        protected Void doInBackground(Void... voids) {
            Utils.runRootCommand(cmd, true);
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            dialog.dismiss();
            Toast.makeText(AppDetailsActivity.this, getString(R.string.uninstall_success, mAppItem.getLabel()),
                    Toast.LENGTH_SHORT).show();
            mAppItem = null;
            finish();

        }
    }.execute();
}

From source file:com.slownet5.pgprootexplorer.filemanager.ui.FileManagerActivity.java

private void setupRoot() {
    if (alreadySetup()) {
        afterInitSetup(true);/*from  w w  w  .  java2s . c om*/
        return;
    }
    final ProgressDialog dialog = new ProgressDialog(this);
    dialog.setIndeterminate(true);
    dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    dialog.setTitle("Setting up root");
    dialog.setCancelable(false);
    ;
    dialog.setMax(100);
    final String os = SystemUtils.getSystemArchitecture();
    Log.d(TAG, "setupRoot: architecture is: " + os);
    class Setup extends AsyncTask<Void, Integer, Boolean> {

        @Override
        protected Boolean doInBackground(Void... params) {
            new File(SharedData.CRYPTO_FM_PATH).mkdirs();
            String filename = SharedData.CRYPTO_FM_PATH + "/toybox";
            AssetManager asset = getAssets();
            try {

                InputStream stream = asset.open("toybox");

                OutputStream out = new FileOutputStream(filename);
                byte[] buffer = new byte[4096];
                int read;
                int total = 0;
                while ((read = stream.read(buffer)) != -1) {
                    total += read;
                    out.write(buffer, 0, read);
                }
                Log.d(TAG, "doInBackground: total written bytes: " + total);
                stream.close();
                out.flush();
                out.close();
            } catch (IOException ex) {
                ex.printStackTrace();
                return false;
            }
            RootUtils.initRoot(filename);

            return true;
        }

        @Override
        protected void onPreExecute() {
            dialog.setMessage("Please wait....");
            dialog.show();
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            dialog.dismiss();
            if (aBoolean) {
                SharedPreferences.Editor prefs = getSharedPreferences(CommonConstants.COMMON_SHARED_PEREFS_NAME,
                        Context.MODE_PRIVATE).edit();
                prefs.putBoolean(CommonConstants.ROOT_TOYBOX, true);
                prefs.apply();
                prefs.commit();
                afterInitSetup(true);

            } else {
                afterInitSetup(aBoolean);
            }
        }
    }
    new Setup().execute();
}

From source file:com.einzig.ipst2.activities.MainActivity.java

/**
 * Wrapper function for parseEmailWork./* w  w  w  .  j ava2 s  .  c o  m*/
 * <p>
 * Builds the progress dialog for, then calls parseEmailWork
 * </p>
 *
 * @see MainActivity#parseEmailWork(Account, ProgressDialog)
 */
private void parseEmail() {
    if (Looper.myLooper() == Looper.getMainLooper()) {
        Logger.d("IS MAIN THREAD?!");
    }
    final Account account = getAccount();
    if (account != null) {
        final ProgressDialog dialog = new ProgressDialog(this, ThemeHelper.getDialogTheme(this));
        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        dialog.setIndeterminate(true);
        dialog.setTitle(getString(R.string.searching_email));
        dialog.setCanceledOnTouchOutside(false);
        dialog.setCancelable(false);
        dialog.show();
        new Thread() {
            public void run() {
                parseEmailWork(account, dialog);
            }
        }.start();
        //getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        //getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }
}

From source file:com.android.gallery3d.ingest.IngestActivity.java

private void updateProgressDialog() {
    ProgressDialog dialog = getProgressDialog();
    boolean indeterminate = (mProgressState.max == 0);
    dialog.setIndeterminate(indeterminate);
    dialog.setProgressStyle(indeterminate ? ProgressDialog.STYLE_SPINNER : ProgressDialog.STYLE_HORIZONTAL);
    if (mProgressState.title != null) {
        dialog.setTitle(mProgressState.title);
    }/*from  w  w w.ja  va 2 s .  c  o  m*/
    if (mProgressState.message != null) {
        dialog.setMessage(mProgressState.message);
    }
    if (!indeterminate) {
        dialog.setProgress(mProgressState.current);
        dialog.setMax(mProgressState.max);
    }
    if (!dialog.isShowing()) {
        dialog.show();
    }
}

From source file:fm.smart.r1.activity.ItemActivity.java

public void addToList(final String item_id) {
    final ProgressDialog myOtherProgressDialog = new ProgressDialog(this);
    myOtherProgressDialog.setTitle("Please Wait ...");
    myOtherProgressDialog.setMessage("Adding item to study list ...");
    myOtherProgressDialog.setIndeterminate(true);
    myOtherProgressDialog.setCancelable(true);

    final Thread add = new Thread() {
        public void run() {
            ItemActivity.add_item_result = addItemToList(Main.default_study_list_id, item_id,
                    ItemActivity.this);

            myOtherProgressDialog.dismiss();
            ItemActivity.this.runOnUiThread(new Thread() {
                public void run() {
                    final AlertDialog dialog = new AlertDialog.Builder(ItemActivity.this).create();
                    dialog.setTitle(ItemActivity.add_item_result.getTitle());
                    dialog.setMessage(ItemActivity.add_item_result.getMessage());
                    ItemActivity.add_item_result = null;
                    dialog.setButton("OK", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                        }/* ww w  .j  a v  a 2s .c  o m*/
                    });

                    dialog.show();
                }
            });

        }
    };
    myOtherProgressDialog.setButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            add.interrupt();
        }
    });
    OnCancelListener ocl = new OnCancelListener() {
        public void onCancel(DialogInterface arg0) {
            add.interrupt();
        }
    };
    myOtherProgressDialog.setOnCancelListener(ocl);
    closeMenu();
    myOtherProgressDialog.show();
    add.start();
}

From source file:edu.wpi.khufnagle.lighthousenavigator.PhotographsActivity.java

/**
 * Display the UI defined in activity_photographs.xml upon activity start.
 *///from w w  w  .  j a  v  a 2s .com
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.setContentView(R.layout.activity_photographs);

    /*
     * Add "up" button functionality in the left of application icon in
     * top-left corner, allowing user to return to "welcome" screen
     */
    final ActionBar ab = this.getSupportActionBar();
    ab.setDisplayHomeAsUpEnabled(true);
    ab.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);

    /*
     * Create "navigation spinner" in activity action bar that allows user to
     * view a different content screen
     */
    final ArrayAdapter<CharSequence> navDropDownAdapter = ArrayAdapter.createFromResource(this,
            R.array.ab_content_activities_names, R.layout.ab_navigation_dropdown_item);
    ab.setListNavigationCallbacks(navDropDownAdapter, this);
    ab.setSelectedNavigationItem(ContentActivity.PHOTOGRAPHS.getABDropDownListIndex());

    // Retrieve name of lighthouse that user is viewing
    final Bundle extras = this.getIntent().getExtras();
    final String lighthouseNameSelected = extras.getString("lighthousename");

    // Lighthouse data guaranteed to exist ("Welcome" activity performs data
    // existence validation)
    final LighthouseDataParser lighthouseInformationParser = new LighthouseDataParser(
            this.getApplicationContext(), lighthouseNameSelected);
    lighthouseInformationParser.parseLighthouseData();
    this.currentLighthouse = lighthouseInformationParser.getLighthouse();

    /*
     * Complete Flickr downloading task only if a network connection exists
     * _and_ the cache is empty or contains information about a lighthouse
     * other than the "desired" one
     */
    this.userConnectedToInternet = this.networkConnectionExists();
    FlickrDownloadHandler downloadHandler = null;

    if (this.userConnectedToInternet) {
        if (!this.photoCacheExists()) {
            if (!PhotographsActivity.downloadingThreadStarted) {
                Log.d("LIGHTNAVDEBUG", "Creating dialog...");

                // Display dialog informing user about download progress
                final ProgressDialog flickrPhotoDownloadDialog = new ProgressDialog(this,
                        ProgressDialog.STYLE_SPINNER);
                flickrPhotoDownloadDialog.setTitle("Downloading Flickr photos");
                flickrPhotoDownloadDialog.setMessage("Downloading photographs from Flickr...");
                flickrPhotoDownloadDialog.setCancelable(true);

                flickrPhotoDownloadDialog.show();

                final HashSet<Photograph> flickrPhotos = new HashSet<Photograph>();

                /*
                 * Start background thread that will complete actual downloading
                 * process
                 */
                PhotographsActivity.downloadingThreadStarted = true;
                downloadHandler = new FlickrDownloadHandler(this, this.currentLighthouse, flickrPhotos,
                        flickrPhotoDownloadDialog);

                final FlickrPhotoDownloadThread downloadThread = new FlickrPhotoDownloadThread(
                        this.getApplicationContext(), this.currentLighthouse, downloadHandler,
                        PhotographsActivity.XML_DOWNLOAD_COMPLETE, PhotographsActivity.INTERRUPT);
                Log.d("LIGHTNAVDEBUG", "Flickr download XML thread started");
                downloadThread.start();

                /*
                 * Interrupt (stop) currently-running thread if user cancels
                 * downloading operation explicitly
                 */
                flickrPhotoDownloadDialog.setOnCancelListener(new OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface di) {
                        if (downloadThread.isAlive()) {
                            downloadThread.interrupt();
                        } else if (PhotographsActivity.this.parseOutputThread != null
                                && PhotographsActivity.this.parseOutputThread.isAlive()) {
                            PhotographsActivity.this.parseOutputThread.interrupt();
                        } else {
                            // Do nothing
                        }
                    }
                });
            }
        } else {

            final ArrayList<Photograph> lighthousePhotos = this.currentLighthouse.getAlbum()
                    .get(ActivityVisible.PHOTOGRAPHS);
            lighthousePhotos.clear();
            final File downloadCacheDir = new File(this.getFilesDir() + "/download-cache/");
            final File[] downloadCacheDirContents = downloadCacheDir.listFiles();
            for (int i = 0; i < downloadCacheDirContents.length; i++) {
                final String downloadCacheDirContentName = downloadCacheDirContents[i].getName();
                final String[] downloadCacheDirContentPieces = downloadCacheDirContentName.split("_");
                final Long photoID = Long.parseLong(downloadCacheDirContentPieces[2]);
                final String ownerName = downloadCacheDirContentPieces[3].replace("~", " ");
                final String creativeCommonsLicenseIDString = downloadCacheDirContentPieces[4].substring(0, 1);
                final int creativeCommonsLicenseID = Integer.parseInt(creativeCommonsLicenseIDString);
                final CreativeCommonsLicenseType licenseType = CreativeCommonsLicenseType
                        .convertToLicenseEnum(creativeCommonsLicenseID);
                lighthousePhotos.add(new Photograph(photoID, ownerName, licenseType,
                        "/download-cache/" + downloadCacheDirContentName));
            }
            this.currentLighthouse.getAlbum().put(ActivityVisible.PHOTOGRAPHS, lighthousePhotos);
        }
    }

    if (!this.userConnectedToInternet || this.userConnectedToInternet && this.photoCacheExists()
            || downloadHandler != null && downloadHandler.getFlickrOperationsComplete()) {
        // Display first photograph as "selected" photograph in top-left corner
        // by default
        final ArrayList<Photograph> photoSet = this.currentLighthouse.getAlbum()
                .get(ActivityVisible.PHOTOGRAPHS);
        final Photograph currentPhotoOnLeftSide = photoSet.get(0);

        final ImageView currentPhotoView = (ImageView) this.findViewById(R.id.iv_photographs_current_image);
        if (this.userConnectedToInternet) {
            currentPhotoView.setImageDrawable(Drawable.createFromPath(
                    PhotographsActivity.this.getFilesDir() + currentPhotoOnLeftSide.getInternalStorageLoc()));
        } else {
            currentPhotoView.setImageResource(currentPhotoOnLeftSide.getResID());
        }

        // Add credits for "default" main photograph
        final TextView owner = (TextView) this.findViewById(R.id.tv_photographs_photographer);
        final TextView licenseType = (TextView) this.findViewById(R.id.tv_photographs_license);
        owner.setText("Uploaded by: " + currentPhotoOnLeftSide.getOwner());
        licenseType.setText("License: " + currentPhotoOnLeftSide.getLicenseTypeAbbreviation());

        /*
         * Display Google Map as a SupportMapFragment (instead of MapFragment
         * for compatibility with Android 2.x)
         */
        /*
         * BIG thanks to http://www.truiton.com/2013/05/
         * android-supportmapfragment-example/ for getting this part of the app
         * working
         */
        final FragmentManager fm = this.getSupportFragmentManager();
        final Fragment mapFragment = fm.findFragmentById(R.id.frag_photographs_map);
        final SupportMapFragment smf = (SupportMapFragment) mapFragment;
        smf.getMap();
        final GoogleMap supportMap = smf.getMap();

        /*
         * Center map at lighthouse location, at a zoom level of 12 with no
         * tilt, facing due north
         */
        final LatLng lighthouseLocation = new LatLng(this.currentLighthouse.getCoordinates().getLatitude(),
                this.currentLighthouse.getCoordinates().getLongitude());
        final float zoomLevel = 12.0f;
        final float tiltAngle = 0.0f;
        final float bearing = 0.0f;
        final CameraPosition cameraPos = new CameraPosition(lighthouseLocation, zoomLevel, tiltAngle, bearing);
        supportMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPos));

        /*
         * Allows user to open a maps application (such as Google Maps) upon
         * selecting the map fragment
         */
        /*
         * Courtesy of:
         * http://stackoverflow.com/questions/6205827/how-to-open-standard
         * -google-map-application-from-my-application
         */
        supportMap.setOnMapClickListener(new OnMapClickListener() {

            @Override
            public void onMapClick(LatLng lighthouseCoordinates) {
                final String uri = String.format(Locale.US, "geo:%f,%f", lighthouseCoordinates.latitude,
                        lighthouseCoordinates.longitude);
                final Intent googleMapsIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
                PhotographsActivity.this.startActivity(googleMapsIntent);
            }
        });

        this.gv = (GridView) this.findViewById(R.id.gv_photographs_thumbnails);

        /*
         * Photographs in the "current lighthouse album" are from Flickr if the
         * album is empty or if the first (or _any_) of the elements in the
         * album do not have a "proper" static resource ID
         */
        this.photosFromFlickr = this.currentLighthouse.getAlbum().get(ActivityVisible.PHOTOGRAPHS).isEmpty()
                || this.currentLighthouse.getAlbum().get(ActivityVisible.PHOTOGRAPHS).iterator().next()
                        .getResID() == 0;

        final LighthouseImageAdapter thumbnailAdapter = new LighthouseImageAdapter(this,
                this.currentLighthouse.getAlbum().get(ActivityVisible.PHOTOGRAPHS), this.photosFromFlickr);

        this.gv.setAdapter(thumbnailAdapter);

        this.gv.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                // Determine which photograph from the list was selected...
                final Photograph photoClicked = (Photograph) thumbnailAdapter.getItem(position);
                final int photoClickedResID = photoClicked.getResID();

                // ...and change the information in the top-left corner
                // accordingly
                if (PhotographsActivity.this.userConnectedToInternet) {
                    currentPhotoView.setImageDrawable(Drawable.createFromPath(
                            PhotographsActivity.this.getFilesDir() + photoClicked.getInternalStorageLoc()));
                } else {
                    currentPhotoView.setImageResource(photoClickedResID);
                }
                owner.setText("Uploaded by: " + photoClicked.getOwner());
                licenseType.setText("License: " + photoClicked.getLicenseTypeAbbreviation());
            }
        });
    }
}

From source file:fm.smart.r1.ItemActivity.java

public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // this should be called once image has been chosen by user
    // using requestCode to pass item id - haven't worked out any other way
    // to do it//from  ww w.  j a  v a  2s . c om
    // if (requestCode == SELECT_IMAGE)
    if (resultCode == Activity.RESULT_OK) {
        // TODO check if user is logged in
        if (LoginActivity.isNotLoggedIn(this)) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setClassName(this, LoginActivity.class.getName());
            intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
            // avoid navigation back to this?
            LoginActivity.return_to = ItemActivity.class.getName();
            LoginActivity.params = new HashMap<String, String>();
            LoginActivity.params.put("item_id", (String) item.getId());
            startActivity(intent);
            // TODO in this case forcing the user to rechoose the image
            // seems a little
            // rude - should probably auto-submit here ...
        } else {
            // Bundle extras = data.getExtras();
            // String sentence_id = (String) extras.get("sentence_id");
            final ProgressDialog myOtherProgressDialog = new ProgressDialog(this);
            myOtherProgressDialog.setTitle("Please Wait ...");
            myOtherProgressDialog.setMessage("Uploading image ...");
            myOtherProgressDialog.setIndeterminate(true);
            myOtherProgressDialog.setCancelable(true);

            final Thread add_image = new Thread() {
                public void run() {
                    // TODO needs to check for interruptibility

                    String sentence_id = Integer.toString(requestCode);
                    Uri selectedImage = data.getData();
                    // Bitmap bitmap = Media.getBitmap(getContentResolver(),
                    // selectedImage);
                    // ByteArrayOutputStream bytes = new
                    // ByteArrayOutputStream();
                    // bitmap.compress(Bitmap.CompressFormat.JPEG, 40,
                    // bytes);
                    // ByteArrayInputStream fileInputStream = new
                    // ByteArrayInputStream(
                    // bytes.toByteArray());

                    // TODO Might have to save to file system first to get
                    // this
                    // to work,
                    // argh!
                    // could think of it as saving to cache ...

                    // add image to sentence
                    FileInputStream is = null;
                    FileOutputStream os = null;
                    File file = null;
                    ContentResolver resolver = getContentResolver();
                    try {
                        Bitmap bitmap = Media.getBitmap(getContentResolver(), selectedImage);
                        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
                        // ByteArrayInputStream bais = new
                        // ByteArrayInputStream(bytes.toByteArray());

                        // FileDescriptor fd =
                        // resolver.openFileDescriptor(selectedImage,
                        // "r").getFileDescriptor();
                        // is = new FileInputStream(fd);

                        String filename = "test.jpg";
                        File dir = ItemActivity.this.getDir("images", MODE_WORLD_READABLE);
                        file = new File(dir, filename);
                        os = new FileOutputStream(file);

                        // while (bais.available() > 0) {
                        // / os.write(bais.read());
                        // }
                        os.write(bytes.toByteArray());

                        os.close();

                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } finally {
                        if (os != null) {
                            try {
                                os.close();
                            } catch (IOException e) {
                            }
                        }
                        if (is != null) {
                            try {
                                is.close();
                            } catch (IOException e) {
                            }
                        }
                    }

                    // File file = new
                    // File(Uri.decode(selectedImage.toString()));

                    // ensure item is in users default list

                    ItemActivity.add_item_result = new AddItemResult(Main.lookup.addItemToGoal(Main.transport,
                            Main.default_study_goal_id, item.getId(), null));

                    Result result = ItemActivity.add_item_result;

                    if (ItemActivity.add_item_result.success()
                            || ItemActivity.add_item_result.alreadyInList()) {

                        // ensure sentence is in users default goal

                        ItemActivity.add_sentence_goal_result = new AddSentenceResult(
                                Main.lookup.addSentenceToGoal(Main.transport, Main.default_study_goal_id,
                                        item.getId(), sentence_id, null));

                        result = ItemActivity.add_sentence_goal_result;
                        if (ItemActivity.add_sentence_goal_result.success()) {

                            String media_entity = "http://test.com/test.jpg";
                            String author = "tansaku";
                            String author_url = "http://smart.fm/users/tansaku";
                            Log.d("DEBUG-IMAGE-URI", selectedImage.toString());
                            ItemActivity.add_image_result = addImage(file, media_entity, author, author_url,
                                    "1", sentence_id, (String) item.getId(), Main.default_study_goal_id);
                            result = ItemActivity.add_image_result;
                        }
                    }
                    final Result display = result;
                    myOtherProgressDialog.dismiss();
                    ItemActivity.this.runOnUiThread(new Thread() {
                        public void run() {
                            final AlertDialog dialog = new AlertDialog.Builder(ItemActivity.this).create();
                            dialog.setTitle(display.getTitle());
                            dialog.setMessage(display.getMessage());
                            dialog.setButton("OK", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    if (ItemActivity.add_image_result != null
                                            && ItemActivity.add_image_result.success()) {
                                        ItemListActivity.loadItem(ItemActivity.this, item.getId().toString());
                                    }
                                }
                            });

                            dialog.show();
                        }
                    });

                }

            };

            myOtherProgressDialog.setButton("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    add_image.interrupt();
                }
            });
            OnCancelListener ocl = new OnCancelListener() {
                public void onCancel(DialogInterface arg0) {
                    add_image.interrupt();
                }
            };
            myOtherProgressDialog.setOnCancelListener(ocl);
            closeMenu();
            myOtherProgressDialog.show();
            add_image.start();

        }
    }
}

From source file:net.gerosyab.dailylog.activity.MainActivity.java

private void importCategory() {
    DialogProperties properties = new DialogProperties();
    properties.selection_mode = DialogConfigs.SINGLE_MODE;
    properties.selection_type = DialogConfigs.FILE_SELECT;
    properties.root = new File(DialogConfigs.DEFAULT_DIR);
    properties.extensions = null;/* w  w  w  .ja v a2  s.c om*/

    dialog = new FilePickerDialog(MainActivity.this, properties);

    dialog.setDialogSelectionListener(new DialogSelectionListener() {
        @Override
        public void onSelectedFilePaths(String[] files) {

            ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressDialog.setTitle("Importing data [" + files[0] + "]");
            progressDialog.show();

            //files is the array of the paths of files selected by the Application User.
            try {
                String newCategoryUUID = UUID.randomUUID().toString();
                //                    CSVReader reader = new CSVReader(new InputStreamReader(new FileInputStream(files[0]), "UTF-8"), '\t');
                CSVReader reader = new CSVReader(new InputStreamReader(new FileInputStream(files[0]), "UTF-8"),
                        ',');
                String[] nextLine;
                long lineNum = 0;

                boolean dbVersionCheck = false, categoryNameCheck = false, categoryUnitCheck = false;
                boolean categoryTypeCheck = false, defaultValueCheck = false, headerCheck = false;
                boolean isCategoryNameExists = false, rowDataCheck = false, dataCheck = false;
                String dbVersion = null, categoryName = null, categoryUnit = null;
                long categoryType = -1, defaultValue = -1;

                //                    Category category = null;
                List<Record> records = new ArrayList<Record>();

                while ((nextLine = reader.readNext()) != null) {
                    // nextLine[] is an array of values from the line
                    String temp2 = "";
                    for (int i = 0; i < nextLine.length; i++) {
                        temp2 += nextLine[i] + ", ";
                    }
                    MyLog.d("opencsv", temp2);

                    if (lineNum == 0) {
                        //header
                        MyLog.d("opencsv", "nextLine.length : " + nextLine.length);
                        for (int i = 0; i < nextLine.length; i++) {
                            String[] split2 = nextLine[i].split(":");
                            MyLog.d("opencsv", "split2.length : " + split2.length);
                            MyLog.d("opencsv", "split2[0] : " + split2[0]);
                            if (split2[0].replaceAll("\\s+", "").equals("Version")) {
                                if (split2[1] != null && !split2[1].equals("")) {
                                    dbVersion = split2[1];
                                    dbVersionCheck = true;
                                }
                            } else if (split2[0].replaceAll("\\s+", "").equals("Name")) {
                                if (split2[1] != null && !split2[1].equals("")) {
                                    categoryName = split2[1];
                                    if (categoryName.length() <= Category.getMaxCategoryNameLength()) {
                                        categoryNameCheck = true;
                                    }
                                }
                            } else if (split2[0].replaceAll("\\s+", "").equals("Unit")) {
                                if (split2.length == 1) {
                                    categoryUnitCheck = true;
                                } else if (split2[1] != null && !split2[1].equals("")) {
                                    categoryUnit = split2[1];
                                    categoryUnitCheck = true;
                                }
                            } else if (split2[0].replaceAll("\\s+", "").equals("Type")) {
                                if (split2[1] != null && !split2[1].equals("")) {
                                    if (split2[1].equals("0") || split2[1].equals("1")
                                            || split2[1].equals("2")) {
                                        categoryType = Long.parseLong(split2[1]);
                                        categoryTypeCheck = true;
                                    }
                                }
                            } else if (split2[0].replaceAll("\\s+", "").equals("DefaultValue")) {
                                if (split2.length == 1) {
                                    defaultValueCheck = true;
                                } else if (split2[1] != null && !split2[1].equals("")) {
                                    if (NumberUtils.isDigits(split2[1]) && NumberUtils.isNumber(split2[1])) {
                                        defaultValue = Long.parseLong(split2[1]);
                                        MyLog.d("opencsv", "split2[1] : " + split2[1]);
                                        if (defaultValue >= 0) {
                                            defaultValueCheck = true;
                                        }
                                    }
                                }
                            }
                        }

                        if (dbVersionCheck && categoryNameCheck && categoryTypeCheck) {
                            if (categoryType == 1) {
                                //number
                                if (categoryUnitCheck && defaultValueCheck) {
                                    headerCheck = true;
                                }
                            } else {
                                //boolean, string
                                headerCheck = true;
                            }
                        }

                        if (!headerCheck) {
                            break; //header parsing, data checking failed
                        } else if (Category.isCategoryNameExists(realm, categoryName)) {
                            isCategoryNameExists = true;
                            break;
                        } else {
                            //                                category = new Category(categoryName, categoryUnit, Category.getLastOrderNum(realm), categoryType);
                        }
                    } else {
                        //data
                        Record record;
                        rowDataCheck = true;
                        if (nextLine.length != 2) {
                            rowDataCheck = false;
                            break;
                        } else {
                            record = new Record();
                            record.setRecordType(categoryType);
                            DateTime dateTime = StaticData.fmtForBackup.parseDateTime(nextLine[0]);
                            if (dateTime != null) {
                                record.setDate(new java.sql.Date(dateTime.toDate().getTime()));
                            } else {
                                rowDataCheck = false;
                                break;
                            }

                            if (categoryType == StaticData.RECORD_TYPE_BOOLEAN) {
                                if (nextLine[1].equals("true")) {
                                    record.setBool(true);
                                } else {
                                    rowDataCheck = false;
                                    break;
                                }
                            } else if (categoryType == StaticData.RECORD_TYPE_NUMBER) {
                                if (NumberUtils.isNumber(nextLine[1]) && NumberUtils.isDigits(nextLine[1])) {
                                    long value = Long.parseLong(nextLine[1]);
                                    if (value > Category.getMaxValue()) {
                                        rowDataCheck = false;
                                        break;
                                    } else {
                                        record.setNumber(value);
                                    }
                                } else {
                                    dataCheck = false;
                                    break;
                                }

                            } else if (categoryType == StaticData.RECORD_TYPE_MEMO) {
                                String value = nextLine[1];
                                if (value.length() > Category.getMaxMemoLength()) {
                                    rowDataCheck = false;
                                    break;
                                } else {
                                    record.setString(nextLine[1]);
                                }
                            }
                        }
                        if (record != null && rowDataCheck == true) {
                            record.setCategoryId(newCategoryUUID);
                            record.setRecordId(UUID.randomUUID().toString());
                            records.add(record);
                        }
                    }
                    lineNum++;
                }

                if (!headerCheck) {
                    Toast.makeText(context, "Data file's header context/value is not correct",
                            Toast.LENGTH_LONG).show();
                } else if (isCategoryNameExists) {
                    Toast.makeText(context, "Category Name [" + categoryName + "] is already exists",
                            Toast.LENGTH_LONG).show();
                } else if (!rowDataCheck) {
                    Toast.makeText(context, "Data file's record data is not correct", Toast.LENGTH_LONG).show();
                } else {
                    long newOrder = Category.getNewOrderNum(realm);
                    realm.beginTransaction();
                    Category category = realm.createObject(Category.class, newCategoryUUID);
                    category.setName(categoryName);
                    category.setUnit(categoryUnit);
                    category.setOrder(newOrder);
                    category.setRecordType(categoryType);
                    realm.insert(category);
                    realm.insertOrUpdate(records);
                    realm.commitTransaction();
                    Toast.makeText(context, "Data import [ " + categoryName + " ] is completed!!",
                            Toast.LENGTH_LONG).show();
                    //                        refreshList();
                    //                        categoryHolderList.add(getHolderFromCategory(category));
                    //                        mDragListView.getAdapter().notifyDataSetChanged();
                    //                        mDragListView.getAdapter().notifyItemInserted((int) newOrder);
                    //                        setCategoryHolderList();
                    //                        mDragListView.getAdapter().setItemList(categoryHolderList);
                    adapter.notifyDataSetChanged();
                }
            } catch (FileNotFoundException e) {
                Toast.makeText(context, "Selected file is not found", Toast.LENGTH_LONG).show();
                e.printStackTrace();
            } catch (IOException e) {
                Toast.makeText(context, "File I/O exception occured", Toast.LENGTH_LONG).show();
                e.printStackTrace();
            } finally {
                progressDialog.dismiss();
            }
        }
    });

    dialog.show();
}