Example usage for android.widget Toast show

List of usage examples for android.widget Toast show

Introduction

In this page you can find the example usage for android.widget Toast show.

Prototype

public void show() 

Source Link

Document

Show the view for the specified duration.

Usage

From source file:com.lofland.housebot.BotController.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.housebot);// www. ja  v a  2  s .  c om
    Log.d(TAG, "onCreate");

    /*
     * TODO: If you need to maintain and pass around context:
     * http://stackoverflow.com/questions/987072/using-application-context-everywhere
     */

    // Display start up toast:
    // http://developer.android.com/guide/topics/ui/notifiers/toasts.html
    Context context = getApplicationContext();
    CharSequence text = "ex Nehilo!";
    int duration = Toast.LENGTH_SHORT;
    Toast toast = Toast.makeText(context, text, duration);
    // Display said toast
    toast.show();

    /*
     *  Turn on WiFi if it is off
     *  http://stackoverflow.com/questions/8863509/how-to-programmatically-turn-off-wifi-on-android-device
     */
    WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
    wifiManager.setWifiEnabled(true);

    // Prevent keyboard from popping up as soon as app launches: (it works!)
    this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

    /*
     * Keep the screen on, because as long as we are talking to the robot, this needs to be up http://stackoverflow.com/questions/9335908/how-to- prevent-the-screen-of
     * -an-android-device-to-turn-off-during-the-execution
     */
    this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    /*
     * One or more of these three lines sets the screen to minimum brightness, Which should extend battery drain, and be less distracting on the robot.
     */
    final WindowManager.LayoutParams winParams = this.getWindow().getAttributes();
    winParams.screenBrightness = 0.01f;
    winParams.buttonBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_OFF;

    // The "Connect" screen has a "Name" and "Address box"
    // I'm not really sure what one puts in these, and if you leave them
    // empty it works fine.
    // So not 110% sure what to do with these. Can the text just be: ""?
    // Just comment these out, and run the command with nulls?
    // mName = (EditText) findViewById(R.id.name_edit);
    // mAddress = (EditText) findViewById(R.id.address_edit);
    // The NXT Remote Control app pops up a list of seen NXTs, so maybe I
    // need to implement that instead.

    // Text to speech
    tts = new TextToSpeech(this, this);

    btnSpeak = (Button) findViewById(R.id.btnSpeak);

    txtText = (EditText) findViewById(R.id.txtSpeakText);

    // Now we need a Robot object before we an use any Roboty values!
    // We can pass defaults in or use the ones it provides
    myRobot = new Robot(INITIALTRAVELSPEED, INITIALROTATESPEED, DEFAULTVIEWANGLE);
    // We may have to pass this robot around a bit. ;)

    // Status Lines
    TextView distanceText = (TextView) findViewById(R.id.distanceText);
    distanceText.setText("???");
    TextView distanceLeftText = (TextView) findViewById(R.id.distanceLeftText);
    distanceLeftText.setText("???");
    TextView distanceRightText = (TextView) findViewById(R.id.distanceRightText);
    distanceRightText.setText("???");
    TextView headingText = (TextView) findViewById(R.id.headingText);
    headingText.setText("???");
    TextView actionText = (TextView) findViewById(R.id.isDoingText);
    actionText.setText("None");

    // Travel speed slider bar
    SeekBar travelSpeedBar = (SeekBar) findViewById(R.id.travelSpeed_seekBar);
    travelSpeedBar.setProgress(myRobot.getTravelSpeed());
    travelSpeedBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            myRobot.setTravelSpeed(progress);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
        }
    });

    // View angle slider bar
    SeekBar viewAngleBar = (SeekBar) findViewById(R.id.viewAngle_seekBar);
    viewAngleBar.setProgress(myRobot.getViewAngle());
    viewAngleBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            myRobot.setViewAngle(progress);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            Log.d(TAG, "View Angle Slider ");
            /*
             * If this gets sent every few milliseconds with the normal output, then there is no need to send a specific command every time it changes!
             */
            // sendCommandToRobot(Command.VIEWANGLE);
        }
    });

    // Rotation speed slider bar speedSP_seekBar
    SeekBar rotateSpeedBar = (SeekBar) findViewById(R.id.rotateSpeed_seekBar);
    rotateSpeedBar.setProgress(myRobot.getRotateSpeed());
    rotateSpeedBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            myRobot.setRotateSpeed(progress);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
        }
    });

    /*
     * This is where we find the four direction buttons defined So we could define ALL buttons this way, set up an ENUM with all options, and call the same function for ALL
     * options!
     * 
     * Just be sure the "release" only stops the robot on these, and not every button on the screen.
     * 
     * Maybe see how the code I stole this form does it?
     */
    Button buttonUp = (Button) findViewById(R.id.forward_button);
    buttonUp.setOnTouchListener(new DirectionButtonOnTouchListener(Direction.FORWARD));
    Button buttonDown = (Button) findViewById(R.id.reverse_button);
    buttonDown.setOnTouchListener(new DirectionButtonOnTouchListener(Direction.REVERSE));
    Button buttonLeft = (Button) findViewById(R.id.left_button);
    buttonLeft.setOnTouchListener(new DirectionButtonOnTouchListener(Direction.LEFT));
    Button buttonRight = (Button) findViewById(R.id.right_button);
    buttonRight.setOnTouchListener(new DirectionButtonOnTouchListener(Direction.RIGHT));

    // button on click event
    btnSpeak.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            speakOut();
        }

    });

    /*
     * This causes the typed text to be spoken when the Enter key is pressed.
     */
    txtText.setOnKeyListener(new View.OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            // If the event is a key-down event on the "enter" button
            if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                // Perform action on key press
                // Toast.makeText(HelloFormStuff.this, edittext.getText(), Toast.LENGTH_SHORT).show();
                speakOut();
                return true;
            }
            return false;
        }
    });

    // Connect button
    connectToggleButton = (ToggleButton) findViewById(R.id.connectToggleButton);
    connectToggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                // The toggle is enabled
                Log.d(TAG, "Connect button Toggled On!");
                myRobot.setConnectRequested(true);
            } else {
                // The toggle is disabled
                Log.d(TAG, "Connect button Toggled OFF.");
                myRobot.setConnectRequested(false);
            }
        }
    });

    if (nxtStatusMessageHandler == null)
        nxtStatusMessageHandler = new StatusMessageHandler();

    mStatusThread = new StatusThread(context, nxtStatusMessageHandler);
    mStatusThread.start();

    // Start the web service!
    Log.d(TAG, "Start web service here:");
    // Initiate message handler for web service
    if (robotWebServerMessageHandler == null)
        robotWebServerMessageHandler = new WebServerMessageHandler(this); // Has to include "this" to send context, see WebServerMessageHandler for explanation

    robotWebServer = new WebServer(context, PORT, robotWebServerMessageHandler, myRobot);

    try {
        robotWebServer.start();
    } catch (IOException e) {
        Log.d(TAG, "robotWebServer failed to start");
        //e.printStackTrace();
    }

    // TODO:
    /*
     * See this reference on how to rebuild this handler in onCreate if it is gone: http://stackoverflow.com/questions/18221593/android-handler-changing-weakreference
     */
    // TODO - Should I stop this thread in Destroy or some such place?

    Log.d(TAG, "Web service was started.");

}

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

public void DisplayToast(String str) {
    Toast toast = Toast.makeText(this, str, Toast.LENGTH_SHORT);
    toast.setGravity(Gravity.BOTTOM, 0, 50);
    toast.show();
}

From source file:fiskinfoo.no.sintef.fiskinfoo.MapFragment.java

private void createProximityAlertSetupDialog() {
    final Dialog dialog = dialogInterface.getDialog(getActivity(), R.layout.dialog_proximity_alert_create,
            R.string.create_proximity_alert);

    Button setProximityAlertWatcherButton = (Button) dialog
            .findViewById(R.id.create_proximity_alert_create_alert_watcher_button);
    Button stopCurrentProximityAlertWatcherButton = (Button) dialog
            .findViewById(R.id.create_proximity_alert_stop_existing_alert_button);
    Button cancelButton = (Button) dialog.findViewById(R.id.create_proximity_alert_cancel_button);
    SeekBar seekbar = (SeekBar) dialog.findViewById(R.id.create_proximity_alert_seekBar);
    final EditText radiusEditText = (EditText) dialog.findViewById(R.id.create_proximity_alert_range_edit_text);
    final Switch formatSwitch = (Switch) dialog.findViewById(R.id.create_proximity_alert_format_switch);

    final double seekBarStepSize = (double) (getResources()
            .getInteger(R.integer.proximity_alert_maximum_warning_range_meters)
            - getResources().getInteger(R.integer.proximity_alert_minimum_warning_range_meters)) / 100;

    radiusEditText.setText(/*from w ww .j a  v a2s  . c  o m*/
            String.valueOf(getResources().getInteger(R.integer.proximity_alert_minimum_warning_range_meters)));

    formatSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                buttonView.setText(getString(R.string.range_format_nautical_miles));
            } else {
                buttonView.setText(getString(R.string.range_format_meters));
            }
        }
    });

    seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (fromUser) {
                String range = String.valueOf(
                        (int) (getResources().getInteger(R.integer.proximity_alert_minimum_warning_range_meters)
                                + (seekBarStepSize * progress)));
                radiusEditText.setText(range);
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });

    setProximityAlertWatcherButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String toastText;

            if (proximityAlertWatcher == null) {
                toastText = getString(R.string.proximity_alert_set);
            } else {

                toastText = getString(R.string.proximity_alert_replace);
            }

            if (proximityAlertWatcher != null) {
                proximityAlertWatcher.cancel(true);
            }

            mGpsLocationTracker = new GpsLocationTracker(getActivity());
            double latitude, longitude;

            if (mGpsLocationTracker.canGetLocation()) {
                latitude = mGpsLocationTracker.getLatitude();
                cachedLat = latitude;
                longitude = mGpsLocationTracker.getLongitude();
                cachedLon = longitude;
            } else {
                mGpsLocationTracker.showSettingsAlert();
                return;
            }

            if (formatSwitch.isChecked()) {
                cachedDistance = Double.valueOf(radiusEditText.getText().toString())
                        * getResources().getInteger(R.integer.meters_per_nautical_mile);
            } else {
                cachedDistance = Double.valueOf(radiusEditText.getText().toString());
            }

            dialog.dismiss();

            Response response;

            try {
                String apiName = "fishingfacility";
                String format = "OLEX";
                String filePath;
                String fileName = "collisionCheckToolsFile";

                response = barentswatchApi.getApi().geoDataDownload(apiName, format);

                if (response == null) {
                    Log.d(TAG, "RESPONSE == NULL");
                    throw new InternalError();
                }

                if (fiskInfoUtility.isExternalStorageWritable()) {
                    String directoryPath = Environment
                            .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();
                    String directoryName = "FiskInfo";
                    filePath = directoryPath + "/" + directoryName + "/";
                    InputStream zippedInputStream = null;

                    try {
                        TypedInput responseInput = response.getBody();
                        zippedInputStream = responseInput.in();
                        zippedInputStream = new GZIPInputStream(zippedInputStream);

                        InputSource inputSource = new InputSource(zippedInputStream);
                        InputStream input = new BufferedInputStream(inputSource.getByteStream());
                        byte data[];
                        data = FiskInfoUtility.toByteArray(input);

                        InputStream inputStream = new ByteArrayInputStream(data);
                        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                        FiskInfoPolygon2D serializablePolygon2D = new FiskInfoPolygon2D();

                        String line;
                        boolean startSet = false;
                        String[] convertedLine;
                        List<Point> shape = new ArrayList<>();
                        while ((line = reader.readLine()) != null) {
                            Point currPoint = new Point();
                            if (line.length() == 0 || line.equals("")) {
                                continue;
                            }
                            if (Character.isLetter(line.charAt(0))) {
                                continue;
                            }

                            convertedLine = line.split("\\s+");

                            if (line.length() > 150) {
                                Log.d(TAG, "line " + line);
                            }

                            if (convertedLine[0].startsWith("3sl")) {
                                continue;
                            }

                            if (convertedLine[3].equalsIgnoreCase("Garnstart") && startSet) {
                                if (shape.size() == 1) {
                                    // Point

                                    serializablePolygon2D.addPoint(shape.get(0));
                                    shape = new ArrayList<>();
                                } else if (shape.size() == 2) {

                                    // line
                                    serializablePolygon2D.addLine(new Line(shape.get(0), shape.get(1)));
                                    shape = new ArrayList<>();
                                } else {

                                    serializablePolygon2D.addPolygon(new Polygon(shape));
                                    shape = new ArrayList<>();
                                }
                                startSet = false;
                            }

                            if (convertedLine[3].equalsIgnoreCase("Garnstart") && !startSet) {
                                double lat = Double.parseDouble(convertedLine[0]) / 60;
                                double lon = Double.parseDouble(convertedLine[1]) / 60;
                                currPoint.setNewPointValues(lat, lon);
                                shape.add(currPoint);
                                startSet = true;
                            } else if (convertedLine[3].equalsIgnoreCase("Brunsirkel")) {
                                double lat = Double.parseDouble(convertedLine[0]) / 60;
                                double lon = Double.parseDouble(convertedLine[1]) / 60;
                                currPoint.setNewPointValues(lat, lon);
                                shape.add(currPoint);
                            }
                        }

                        reader.close();
                        new FiskInfoUtility().serializeFiskInfoPolygon2D(filePath + fileName + "." + format,
                                serializablePolygon2D);

                        tools = serializablePolygon2D;

                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (ArrayIndexOutOfBoundsException e) {
                        Log.e(TAG, "Error when trying to serialize file.");
                        Toast error = Toast.makeText(getActivity(), "Ingen redskaper i omrdet du definerte",
                                Toast.LENGTH_LONG);
                        e.printStackTrace();
                        error.show();
                        return;
                    } finally {
                        try {
                            if (zippedInputStream != null) {
                                zippedInputStream.close();
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    Toast.makeText(v.getContext(), R.string.download_failed, Toast.LENGTH_LONG).show();
                    dialog.dismiss();
                    return;
                }

            } catch (Exception e) {
                Log.d(TAG, "Could not download tools file");
                Toast.makeText(getActivity(), R.string.download_failed, Toast.LENGTH_LONG).show();
            }

            runScheduledAlarm(getResources().getInteger(R.integer.zero),
                    getResources().getInteger(R.integer.proximity_alert_interval_time_seconds));

            Toast.makeText(getActivity(), toastText, Toast.LENGTH_LONG).show();
        }
    });

    if (proximityAlertWatcher != null) {
        TypedValue outValue = new TypedValue();
        stopCurrentProximityAlertWatcherButton.setVisibility(View.VISIBLE);

        getResources().getValue(R.dimen.proximity_alert_dialog_button_text_size_small, outValue, true);
        float textSize = outValue.getFloat();

        setProximityAlertWatcherButton.setTextSize(textSize);
        stopCurrentProximityAlertWatcherButton.setTextSize(textSize);
        cancelButton.setTextSize(textSize);

        stopCurrentProximityAlertWatcherButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                proximityAlertWatcher.cancel(true);
                proximityAlertWatcher = null;
                dialog.dismiss();
            }
        });
    }

    cancelButton.setOnClickListener(onClickListenerInterface.getDismissDialogListener(dialog));

    dialog.show();
}

From source file:no.ntnu.idi.socialhitchhiking.map.MapActivityCreateOrEditRoute.java

/**
 * Starts an activity where the user can change the order of (or delete) the map points.
 *///www . j av  a2 s . co  m
private void changeOrder() {
    if (getSelectedRoute() == null || getSelectedRoute().getMapPoints() == null
            || getSelectedRoute().getMapPoints().size() == 0) {
        Toast toast = Toast.makeText(this, "You must add some points first", Toast.LENGTH_LONG);
        toast.setGravity(Gravity.BOTTOM, toast.getXOffset() / 2, toast.getYOffset() / 2);
        toast.show();
        return;
    }
    Intent dragAndDropIntent = new Intent(this,
            no.ntnu.idi.socialhitchhiking.map.draganddrop.DragAndDropListActivity.class);
    getApp().setSelectedMapRoute(selectedRoute);
    dragAndDropIntent.putExtra("type", "changeOrder");
    dragAndDropIntent.putExtra("editMode", inEditMode);
    dragAndDropIntent.putExtra("routePosition", positionOfRoute);
    startActivity(dragAndDropIntent);
    finish();
}

From source file:com.edible.ocr.CaptureActivity.java

/** Displays a pop-up message showing the name of the current OCR source language. */
void showLanguageName() {
    Toast toast = Toast.makeText(this, "OCR: " + sourceLanguageReadable, Toast.LENGTH_LONG);
    toast.setGravity(Gravity.TOP, 0, 0);
    toast.show();
}

From source file:com.edible.ocr.CaptureActivity.java

/** Called when the shutter button is pressed in continuous mode. */
void onShutterButtonPressContinuous() {
    isPaused = true;/*  w w w  . j av  a  2  s .co m*/
    handler.stop();
    beepManager.playBeepSoundAndVibrate();
    if (lastResult != null) {
        handleOcrDecode(lastResult);
    } else {
        Toast toast = Toast.makeText(this, "OCR failed. Please try again.", Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.TOP, 0, 0);
        toast.show();
        resumeContinuousDecoding();
    }
}

From source file:com.edible.ocr.CaptureActivity.java

@Override
public boolean onContextItemSelected(MenuItem item) {
    ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
    switch (item.getItemId()) {

    case OPTIONS_COPY_RECOGNIZED_TEXT_ID:
        clipboardManager.setText(ocrResultView.getText());
        if (clipboardManager.hasText()) {
            Toast toast = Toast.makeText(this, "Text copied.", Toast.LENGTH_LONG);
            toast.setGravity(Gravity.BOTTOM, 0, 0);
            toast.show();
        }//from  w  w  w . j  a v  a 2  s .co m
        return true;
    case OPTIONS_SHARE_RECOGNIZED_TEXT_ID:
        Intent shareRecognizedTextIntent = new Intent(android.content.Intent.ACTION_SEND);
        shareRecognizedTextIntent.setType("text/plain");
        shareRecognizedTextIntent.putExtra(android.content.Intent.EXTRA_TEXT, ocrResultView.getText());
        startActivity(Intent.createChooser(shareRecognizedTextIntent, "Share via"));
        return true;
    case OPTIONS_COPY_TRANSLATED_TEXT_ID:
        clipboardManager.setText(translationView.getText());
        if (clipboardManager.hasText()) {
            Toast toast = Toast.makeText(this, "Text copied.", Toast.LENGTH_LONG);
            toast.setGravity(Gravity.BOTTOM, 0, 0);
            toast.show();
        }
        return true;
    case OPTIONS_SHARE_TRANSLATED_TEXT_ID:
        Intent shareTranslatedTextIntent = new Intent(android.content.Intent.ACTION_SEND);
        shareTranslatedTextIntent.setType("text/plain");
        shareTranslatedTextIntent.putExtra(android.content.Intent.EXTRA_TEXT, translationView.getText());
        startActivity(Intent.createChooser(shareTranslatedTextIntent, "Share via"));
        return true;
    default:
        return super.onContextItemSelected(item);
    }
}

From source file:org.nla.tarotdroid.lib.ui.GameSetHistoryActivity.java

/**
 * Starts the whole Facebook post process.
 * //  www. j a v  a2  s .  c o m
 * @param session
 */
private void launchPostProcess(final Session session) {

    LayoutInflater inflater = getLayoutInflater();
    View layout = inflater.inflate(R.layout.toast, (ViewGroup) findViewById(R.id.toast_layout_root));

    ImageView image = (ImageView) layout.findViewById(R.id.image);
    image.setImageResource(R.drawable.icon_facebook_released);
    TextView text = (TextView) layout.findViewById(R.id.text);
    text.setText("Publication en cours");

    Toast toast = new Toast(getApplicationContext());
    toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
    toast.setDuration(Toast.LENGTH_LONG);
    toast.setView(layout);
    toast.show();

    Request request = Request.newMeRequest(session, new Request.GraphUserCallback() {

        @Override
        public void onCompleted(GraphUser user, Response response) {
            if (session == Session.getActiveSession()) {
                if (user != null) {
                    int notificationId = FacebookHelper
                            .showNotificationStartProgress(GameSetHistoryActivity.this);
                    AppContext.getApplication().getNotificationIds().put(tempGameSet.getUuid(), notificationId);

                    AppContext.getApplication().setLoggedFacebookUser(user);
                    UpSyncGameSetTask task = new UpSyncGameSetTask(GameSetHistoryActivity.this, progressDialog);
                    task.setCallback(GameSetHistoryActivity.this.upSyncCallback);
                    task.execute(tempGameSet);
                    currentRunningTask = task;
                }
            }
            if (response.getError() != null) {
                // //progressDialog.dismiss();
                // Session newSession = new
                // Session(GameSetHistoryActivity.this);
                // Session.setActiveSession(newSession);
                // newSession.openForPublish(new
                // Session.OpenRequest(GameSetHistoryActivity.this).setPermissions(Arrays.asList("publish_actions",
                // "email")).setCallback(facebookSessionStatusCallback));
            }
        }
    });
    request.executeAsync();
}

From source file:com.edible.ocr.CaptureActivity.java

/**
 * Displays information relating to the result of OCR, and requests a translation if necessary.
 * //ww  w .j a  v  a 2  s  .c o m
 * @param ocrResult Object representing successful OCR results
 * @return True if a non-null result was received for OCR
 */
boolean handleOcrDecode(OcrResult ocrResult) {
    lastResult = ocrResult;

    // Test whether the result is null
    if (ocrResult.getText() == null || ocrResult.getText().equals("")) {
        Toast toast = Toast.makeText(this, "OCR failed. Please try again.", Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.TOP, 0, 0);
        toast.show();
        return false;
    }

    // Turn off capture-related UI elements
    shutterButton.setVisibility(View.GONE);
    statusViewBottom.setVisibility(View.GONE);
    statusViewTop.setVisibility(View.GONE);
    cameraButtonView.setVisibility(View.GONE);
    viewfinderView.setVisibility(View.GONE);
    resultView.setVisibility(View.VISIBLE);

    ImageView bitmapImageView = (ImageView) findViewById(R.id.image_view);
    lastBitmap = ocrResult.getBitmap();
    if (lastBitmap == null) {
        bitmapImageView.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher));
    } else {
        bitmapImageView.setImageBitmap(lastBitmap);
    }

    // Display the recognized text
    TextView sourceLanguageTextView = (TextView) findViewById(R.id.source_language_text_view);
    sourceLanguageTextView.setText(sourceLanguageReadable);
    TextView ocrResultTextView = (TextView) findViewById(R.id.ocr_result_text_view);
    ocrResultTextView.setText(stripNoise(ocrResult.getText()));
    // Crudely scale betweeen 22 and 32 -- bigger font for shorter text
    int scaledSize = Math.max(22, 32 - ocrResult.getText().length() / 4);
    ocrResultTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, scaledSize);

    TextView translationLanguageLabelTextView = (TextView) findViewById(
            R.id.translation_language_label_text_view);
    TextView translationLanguageTextView = (TextView) findViewById(R.id.translation_language_text_view);
    TextView translationTextView = (TextView) findViewById(R.id.translation_text_view);
    if (isTranslationActive) {
        // Handle translation text fields
        translationLanguageLabelTextView.setVisibility(View.VISIBLE);
        translationLanguageTextView.setText(targetLanguageReadable);
        translationLanguageTextView.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL), Typeface.NORMAL);
        translationLanguageTextView.setVisibility(View.VISIBLE);

        // Activate/re-activate the indeterminate progress indicator
        translationTextView.setVisibility(View.GONE);
        progressView.setVisibility(View.VISIBLE);
        setProgressBarVisibility(true);

        // Get the translation asynchronously
        new TranslateAsyncTask(this, sourceLanguageCodeTranslation, targetLanguageCodeTranslation,
                stripNoise(ocrResult.getText())).execute();
    } else {
        translationLanguageLabelTextView.setVisibility(View.GONE);
        translationLanguageTextView.setVisibility(View.GONE);
        translationTextView.setVisibility(View.GONE);
        progressView.setVisibility(View.GONE);
        setProgressBarVisibility(false);
    }
    return true;
}

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

public void carinfo(final String phonenum, final String carnum, final String carbrand, final String carmodel,
        final String carcolor, final String car_capacity, int type) {
    // TODO Auto-generated method stub

    String carinfotype;// w w  w  .  j  a  v  a 2 s . c  om
    if (type == 1) {
        carinfotype = getString(R.string.uri_addcarinfo_action);
    } else {
        carinfotype = getString(R.string.uri_updatecarinfo_action);
    }

    String carinfo_baseurl = getString(R.string.uri_base) + getString(R.string.uri_CarInfo) + carinfotype;
    // + "carnum=" + carnum + "&phonenum="
    // + phonenum + "&carbrand=" + carbrand + "&carmodel=" + carmodel
    // + "&carcolor=" + carcolor +"&capacity=" + car_capacity;

    // "http://192.168.1.111:8080/CarsharingServer/CarInfo!changeinfo.action?";

    // Uri.encode(modify_baseurl, "@#&=*+-_.,:!?()/~'%");// 

    Log.d("carinfo_URL", carinfo_baseurl);
    // Instantiate the RequestQueue.
    // Request a string response from the provided URL.
    StringRequest stringRequest = new StringRequest(Request.Method.POST, carinfo_baseurl,
            new Response.Listener<String>() {

                @Override
                public void onResponse(String response) {
                    Log.d("carinfo_result", response);
                    JSONObject json1 = null;
                    try {
                        json1 = new JSONObject(response);
                        carinfook = json1.getBoolean("result");
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    if (carinfook == false) {
                        Toast errorinfo = Toast.makeText(getApplicationContext(), "",
                                Toast.LENGTH_LONG);
                        errorinfo.show();
                    }

                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e("carinfo_result", error.getMessage(), error);
                    // Toast errorinfo = Toast.makeText(null,
                    // "", Toast.LENGTH_LONG);
                    // errorinfo.show();
                }
            }) {
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put("carnum", carnum);
            params.put("phonenum", phonenum);
            params.put("carbrand", carbrand);
            params.put("carmodel", carmodel);
            params.put("carcolor", carcolor);
            params.put("capacity", car_capacity);
            return params;
        }
    };

    queue.add(stringRequest);
}