Example usage for android.widget TextView getText

List of usage examples for android.widget TextView getText

Introduction

In this page you can find the example usage for android.widget TextView getText.

Prototype

@ViewDebug.CapturedViewProperty
public CharSequence getText() 

Source Link

Document

Return the text that TextView is displaying.

Usage

From source file:com.filelocker.andy.MainActivity.java

public void lockButton_Click(View view) {

    TextView vPasswordText = (TextView) findViewById(R.id.passwordText);
    TextView vFileChooserText = (TextView) findViewById(R.id.fileChooserText);

    String myPassword = vPasswordText.getText().toString();

    vPasswordText.setText("");

    if (vFileChooserText.getText().toString().equals("") || myPassword.equals("")) {
        Toast toast;//from   w  ww . j a va 2 s  .  c  o  m
        if (vFileChooserText.getText().toString().equals("")) {
            toast = Toast.makeText(getApplicationContext(), "File Not Choosen", Toast.LENGTH_LONG);
            toast.show();
        } else if (myPassword.equals("")) {
            toast = Toast.makeText(getApplicationContext(), "Password Field Empty", Toast.LENGTH_LONG);
            toast.show();
        }

        return;
    } else if (!(vFileChooserText.getText().toString()
            .substring(vFileChooserText.getText().toString().lastIndexOf('.') + 1).equals("encrypt"))) {

        AES_Encryption en = new AES_Encryption(myPassword);
        /*
         * setup encryption cipher using password. print out iv and salt
         */
        try {
            File vInFile = new File(vFileChooserText.getText().toString());

            if (vInFile.exists() == false) {
                throw new FileNotFoundException("File Not Found");
            }

            en.setupEncrypt();
        } catch (InvalidKeyException ex) {
            ex.printStackTrace();
        } catch (NoSuchAlgorithmException ex) {
            ex.printStackTrace();
        } catch (InvalidKeySpecException ex) {
            ex.printStackTrace();
        } catch (NoSuchPaddingException ex) {
            ex.printStackTrace();
        } catch (InvalidParameterSpecException ex) {
            ex.printStackTrace();
        } catch (IllegalBlockSizeException ex) {
            ex.printStackTrace();
        } catch (BadPaddingException ex) {
            ex.printStackTrace();
        } catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        }

        /*
         * write out encrypted file
         */
        try {

            File vInFile = new File(vFileChooserText.getText().toString());
            File vOutFile = new File(vFileChooserText.getText().toString() + ".encrypt");

            if (vInFile.exists() == false) {
                throw new FileNotFoundException("File Not Found");
            }

            en.WriteEncryptedFile(vInFile, vOutFile);

            Toast toast = Toast.makeText(getApplicationContext(), "Encryption Complete", Toast.LENGTH_LONG);
            toast.show();
            vInFile.delete();

        } catch (IllegalBlockSizeException ex) {
            ex.printStackTrace();
        } catch (BadPaddingException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    } else {

        /*
         * decrypt file
         */
        AES_Encryption dc = new AES_Encryption(myPassword);
        try {
            File vInFile = new File(vFileChooserText.getText().toString());

            if (vInFile.exists() == false) {
                throw new FileNotFoundException("File Not Found");
            }

            dc.setupDecrypt(vInFile);
        } catch (InvalidKeyException ex) {
            ex.printStackTrace();
        } catch (NoSuchAlgorithmException ex) {
            ex.printStackTrace();
        } catch (InvalidKeySpecException ex) {
            ex.printStackTrace();
        } catch (NoSuchPaddingException ex) {
            ex.printStackTrace();
        } catch (InvalidAlgorithmParameterException ex) {
            ex.printStackTrace();
        } catch (DecoderException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {

            ex.printStackTrace();
        }

        /*
         * write out decrypted file
         */
        try {
            File vInFile = new File(vFileChooserText.getText().toString());
            File vOutFile = new File(vFileChooserText.getText().toString().substring(0,
                    vFileChooserText.getText().toString().length() - 8));

            if (vInFile.exists() == false) {
                throw new FileNotFoundException("File Not Found");
            }

            dc.ReadEncryptedFile(vInFile, vOutFile);
            vInFile.delete();

            Toast toast = Toast.makeText(getApplicationContext(), "Decryption Complete", Toast.LENGTH_LONG);
            toast.show();
        } catch (IllegalBlockSizeException ex) {
            ex.printStackTrace();
        } catch (BadPaddingException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}

From source file:com.groksolutions.grok.mobile.chart.AbstractAnomalyChartFragment.java

protected void updateName(final View parent, final AnomalyChartData data) {
    final TextView textView = (TextView) parent.findViewById(R.id.name);
    if (textView != null) {
        final CharSequence oldName = textView.getText();
        if (data == null) {
            textView.setText(null);//from  ww w . j  av a2  s . c om
            textView.setSelected(false);
        } else if (!oldName.equals(data.getName())) {
            textView.setText(data.getName());
            textView.setSelected(true);
        }
        parent.forceLayout();
    }
}

From source file:com.cypress.cysmart.CommonFragments.NavigationDrawerFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    mDrawerListView = (ExpandableListView) inflater.inflate(R.layout.fragment_navigation_drawer, container,
            false);/*  w ww  .j a v  a 2 s  .  c  o m*/
    // Navigation drawer title with custom layout
    ViewGroup header = (ViewGroup) inflater.inflate(R.layout.fragment_drawer_header, mDrawerListView, false);
    mDrawerListView.addHeaderView(header, null, false);
    // Adding NavigationDrawer items to array
    mNavDrawerItems = new ArrayList<NavigationDrawerModel>();
    // load slide menu items
    mNavMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
    // Navigation drawer icons from resources
    mNavMenuIcons = getResources().obtainTypedArray(R.array.nav_drawer_icons);
    /**
     * Adding NavigationDrawer items to array
     */
    mNavDrawerItems = new ArrayList<NavigationDrawerModel>();
    mNavDrawerChildItems = new HashMap<NavigationDrawerModel, List<String>>();

    // BLE Devices
    mNavDrawerItems.add(new NavigationDrawerModel(mNavMenuTitles[0], mNavMenuIcons.getResourceId(0, -1)));
    // Cypress
    mNavDrawerItems.add(new NavigationDrawerModel(mNavMenuTitles[1], mNavMenuIcons.getResourceId(1, -1)));
    //Cypress subitems
    List<String> subitems = new ArrayList<String>();
    subitems.add(getResources().getString(R.string.navigation_drawer_child_home));
    subitems.add(getResources().getString(R.string.navigation_drawer_child_ble));
    subitems.add(getResources().getString(R.string.navigation_drawer_child_mobile));
    subitems.add(getResources().getString(R.string.navigation_drawer_child_contact));
    mNavDrawerChildItems.put(mNavDrawerItems.get(1), subitems);

    // Contact US
    mNavDrawerItems.add(new NavigationDrawerModel(mNavMenuTitles[2], mNavMenuIcons.getResourceId(2, -1)));

    // Setting the NavigationDrawer list adapter
    mAdapter = new NavDrawerListAdapter(getActivity(), mNavDrawerItems);
    mNavigationItemsAdapter = new NavDrawerExpandableListAdapter(getActivity(), mNavDrawerItems,
            mNavDrawerChildItems);
    mDrawerListView.setAdapter(mNavigationItemsAdapter);
    mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
    mDrawerListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
        @Override
        public boolean onGroupClick(ExpandableListView expandableListView, View view, int groupPosition,
                long l) {
            if (groupPosition == 1) {
                return false;
            } else {
                selectItem(groupPosition);
                return true;
            }

        }
    });
    mDrawerListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
        @Override
        public boolean onChildClick(ExpandableListView expandableListView, View view, int groupPosition,
                int childPosition, long l) {
            if (groupPosition == 1) {
                TextView childText = (TextView) view.findViewById(R.id.lblListItem);
                selectChildView(childText.getText().toString());
                return true;
            } else {
                return false;
            }

        }
    });
    mDrawerListView.expandGroup(1);
    return mDrawerListView;
}

From source file:com.google.android.gms.samples.vision.face.multitracker.MultiTrackerActivity.java

/**
 * Creates and starts the camera.  Note that this uses a higher resolution in comparison
 * to other detection examples to enable the barcode detector to detect small barcodes
 * at long distances./*  w w w  .ja v  a2s.  c om*/
 */
private void createCameraSource() {

    Context context = getApplicationContext();

    // A face detector is created to track faces.  An associated multi-processor instance
    // is set to receive the face detection results, track the faces, and maintain graphics for
    // each face on screen.  The factory is used by the multi-processor to create a separate
    // tracker instance for each face.
    //        FaceDetector faceDetector = new FaceDetector.Builder(context).build();
    //        FaceTrackerFactory faceFactory = new FaceTrackerFactory(mGraphicOverlay);
    //        faceDetector.setProcessor(
    //                new MultiProcessor.Builder<>(faceFactory).build());

    // A barcode detector is created to track barcodes.  An associated multi-processor instance
    // is set to receive the barcode detection results, track the barcodes, and maintain
    // graphics for each barcode on screen.  The factory is used by the multi-processor to
    // create a separate tracker instance for each barcode.
    BarcodeDetector barcodeDetector = new BarcodeDetector.Builder(context).build();
    scanner.addObserver(sender);

    //        Log.i("sa.IP", "value:" + sa.retrieve("IP"));
    //        Log.i("sa.Port", "value:" + sa.retrieve("Port"));
    sender = XMLRPCSender.getInstance();
    Log.i("sender", "IP" + sender.ip);

    BarcodeTrackerFactory barcodeFactory = new BarcodeTrackerFactory(mGraphicOverlay,
            new GraphicTracker.Callback() {
                @Override
                public void onFound(String barcodeValue) {
                    Scan scan = new Scan(barcodeValue);
                    scanner.insertScan(scan);
                    try {
                        Log.d(TAG, "Barcode in Multitracker = " + barcodeValue);
                        Log.i("Sender IP", "Value:" + sender.ip);
                        TextView bcTV = (TextView) findViewById(R.id.barcodeTV);
                        bcTV.setText(barcodeValue + "\n" + bcTV.getText());
                        Button allB = (Button) findViewById(R.id.allButton);
                        Button listB = (Button) findViewById(R.id.listButton);
                        Button singleB = (Button) findViewById(R.id.singleButton);

                        //RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.main);
                        //remoteViews.setTextViewText(R.id.allButton, scanner.totalScanCount().toString());
                        allB.setText(scanner.totalScanCount());
                        listB.setText(scanner.listScanCount());
                        singleB.setText("1");
                    } catch (Exception ex) {
                        Log.e(ex.getMessage(), "Expected error: ");
                    }

                }
            });
    //        MultiProcessor<Barcode> barcodeMultiProcessor = new MultiProcessor.Builder<>(barcodeFactory).build();
    //        barcodeDetector.setProcessor(barcodeMultiProcessor);
    barcodeDetector.setProcessor(new MultiProcessor.Builder<>(barcodeFactory).build());

    // A multi-detector groups the two detectors together as one detector.  All images received
    // by this detector from the camera will be sent to each of the underlying detectors, which
    // will each do face and barcode detection, respectively.  The detection results from each
    // are then sent to associated tracker instances which maintain per-item graphics on the
    // screen.
    MultiDetector multiDetector = new MultiDetector.Builder()
            //.add(faceDetector)
            .add(barcodeDetector).build();

    if (!multiDetector.isOperational()) {
        // Note: The first time that an app using the barcode or face API is installed on a
        // device, GMS will download a native libraries to the device in order to do detection.
        // Usually this completes before the app is run for the first time.  But if that
        // download has not yet completed, then the above call will not detect any barcodes
        // and/or faces.
        //
        // isOperational() can be used to check if the required native libraries are currently
        // available.  The detectors will automatically become operational once the library
        // downloads complete on device.
        Log.w(TAG, "Detector dependencies are not yet available.");

        // Check for low storage.  If there is low storage, the native library will not be
        // downloaded, so detection will not become operational.
        IntentFilter lowstorageFilter = new IntentFilter(Intent.ACTION_DEVICE_STORAGE_LOW);
        boolean hasLowStorage = registerReceiver(null, lowstorageFilter) != null;

        if (hasLowStorage) {
            Toast.makeText(this, R.string.low_storage_error, Toast.LENGTH_LONG).show();
            Log.w(TAG, getString(R.string.low_storage_error));
        }
    }

    // Creates and starts the camera.  Note that this uses a higher resolution in comparison
    // to other detection examples to enable the barcode detector to detect small barcodes
    // at long distances.
    //        mCameraSource = new CameraSource.Builder(getApplicationContext(), multiDetector)
    //                .setFacing(CameraSource.CAMERA_FACING_BACK)
    //                .setRequestedPreviewSize(1600, 1024)
    //                .setRequestedFps(15.0f)
    //                .build();
    CameraSource.Builder builder = new CameraSource.Builder(getApplicationContext(), barcodeDetector)
            .setFacing(CameraSource.CAMERA_FACING_BACK).setRequestedPreviewSize(2560, 1440)
            .setRequestedFps(15.0f);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        builder = builder.setAutoFocusEnabled(true);
    }
    mCameraSource = builder.build();
}

From source file:com.bringcommunications.etherpay.SendActivity.java

public void do_pay(View view) {
    if (send_is_done)
        return;//  w ww .j a v a 2s  .c o  m
    //validate size... we check for sufficient balance later...
    EditText size_view = (EditText) findViewById(R.id.size);
    String user_size_str = size_view.getText().toString();
    float user_size = Float.valueOf(user_size_str);
    eth_size = (denomination == Denomination.ETH) ? user_size : user_size / 1000;
    if (eth_size == 0) {
        Toast.makeText(context, "Cannot send zero ETH", Toast.LENGTH_LONG).show();
        return;
    }
    if (show_gas) {
        TextView gas_view = (TextView) findViewById(R.id.gas);
        String gas_limit_str = gas_view.getText().toString().trim();
        try {
            gas_limit = Long.valueOf(gas_limit_str);
        } catch (NumberFormatException e) {
            Toast.makeText(context, "Unable to parse Gas limit: " + gas_limit_str, Toast.LENGTH_LONG).show();
            return;
        }
    }
    if (gas_limit < Util.DEFAULT_GAS_LIMIT) {
        Toast.makeText(context, "Gas limit is too low -- transaction might not succeed!", Toast.LENGTH_LONG)
                .show();
        return;
    }
    //ensure sufficient funds
    long gas_price = preferences.getLong("gas_price", Util.DEFAULT_GAS_PRICE);
    float max_gas_eth = (gas_limit * gas_price) / WEI_PER_ETH;
    if (eth_size + max_gas_eth > eth_balance) {
        String balance_str = String.format("%1.06f", eth_balance);
        String size_str = String.format("%1.06f", eth_size);
        String gas_str = String.format("%1.08f", max_gas_eth);
        String msg = "Balance (" + balance_str + ") is not sufficient to cover " + size_str + " ETH, plus "
                + gas_str + " GAS";
        Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
        return;
    }
    //validate to_addr
    if (!to_addr.startsWith("0x") || to_addr.length() != 42) {
        Toast.makeText(context, "Recipient address is not valid; length is " + to_addr.length(),
                Toast.LENGTH_LONG).show();
        return;
    }
    if (to_addr.equals(acct_addr)) {
        Toast.makeText(context, "Recipient cannot be the same as your account address", Toast.LENGTH_LONG)
                .show();
        return;
    }
    EditText data_view = (EditText) findViewById(R.id.data);
    data = data_view.getText().toString();
    long size_wei = (long) (eth_size * WEI_PER_ETH);
    Payment_Processor.send(this, context, "", to_addr, size_wei, gas_limit, data.getBytes(), false);
    send_is_done = true;
    Button pay_view = (Button) findViewById(R.id.pay_button);
    pay_view.setClickable(false);
}

From source file:info.semanticsoftware.semassist.android.activity.AuthenticationActivity.java

/** Sends an authentication request when the save button is pushed.
 * @param v view /*from w w  w  .j  a v  a2 s .  co m*/
 */
public void onSaveClick(View v) {
    TextView tvUsername = (TextView) this.findViewById(R.id.uc_txt_username);
    TextView tvPassword = (TextView) this.findViewById(R.id.uc_txt_password);

    //Qualified username, i.e, user@semanticassistants.com
    String qUsername = tvUsername.getText().toString();
    String username = null;
    if (qUsername.indexOf("@") > 0) {
        username = qUsername.substring(0, qUsername.indexOf("@"));
    } else {
        username = qUsername;
    }
    String password = tvPassword.getText().toString();

    //TODO do client-side validation like password length etc.
    String response = authenicate(username, password);
    if (!response.equals(Constants.AUTHENTICATION_FAIL)) {
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        Editor editor = settings.edit();
        editor.putString("username", username);
        editor.putString("password", password);
        //FIXME replace this with a descent XML parser
        String acctype = "";
        int start = response.indexOf("<accType>");
        int end = response.indexOf("</accType>");
        if (start > -1 && end > -1) {
            acctype = response.substring(start + "<accType>".length(), end);
        }
        editor.putString("acctype", acctype);
        String sessionId = "";
        start = response.indexOf("<sessionId>");
        end = response.indexOf("</sessionId>");
        if (start > -1 && end > -1) {
            sessionId = response.substring(start + "<sessionId>".length(), end);
        }
        editor.putString("sessionId", sessionId);
        String reqNum = "";
        start = response.indexOf("<reqNum>");
        end = response.indexOf("</reqNum>");
        if (start > -1 && end > -1) {
            reqNum = response.substring(start + "<reqNum>".length(), end);
        }
        editor.putString("reqNum", reqNum);
        boolean result = editor.commit();
        if (result) {
            Toast.makeText(this, R.string.authenticationSuccess, Toast.LENGTH_LONG).show();
            String accountType = this.getIntent().getStringExtra("auth.token");
            if (accountType == null) {
                accountType = SemAssistAuthenticator.ACCOUNT_TYPE;
            }

            AccountManager accMgr = AccountManager.get(this);

            // Add the account to the Android Account Manager
            String accountName = username + "@semanticassistants.com";
            final Account account = new Account(accountName, accountType);
            accMgr.addAccountExplicitly(account, password, null);

            // Inform the caller (could be the Android Account Manager or the SA app) that the process was successful
            final Intent intent = new Intent();
            intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, accountName);
            intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, accountType);
            intent.putExtra(AccountManager.KEY_AUTHTOKEN, accountType);
            this.setAccountAuthenticatorResult(intent.getExtras());
            this.setResult(RESULT_OK, intent);
            this.finish();
        } else {
            Toast.makeText(this, "Could not write the preferences.", Toast.LENGTH_LONG).show();
        }
    } else {
        Toast.makeText(this, R.string.authenticationFail, Toast.LENGTH_LONG).show();
    }
}

From source file:aleajactatest.appiumcalculator.CalculatorFragment.java

/**
 * Initializes the click listeners on the buttons
 *//*from  w  w  w.j a  va  2  s  . c o m*/
private void initButtonsClickListeners() {

    View.OnClickListener globalClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                if (v != null && !(v instanceof Button))
                    return;
                if (mIsNewCompute) {
                    initDefaultValues();
                    mIsNewCompute = false;
                }
                TextView tvScore = (TextView) getActivity().findViewById(R.id.tvScore);
                Button b = (Button) v;
                String val = b.getText().toString();
                // Updates the display field
                String text = tvScore.getText() + "";
                tvScore.setText(text + val);
                // ...
                switch (val) {
                case "0":
                case "1":
                case "2":
                case "3":
                case "4":
                case "5":
                case "6":
                case "7":
                case "8":
                case "9":
                    if (mOperation == Operation.NOPE) {
                        mLeftPart = Integer.parseInt(val);
                    } else {
                        mRightPart = Integer.parseInt(val);
                    }
                    break;
                case "+":
                    mOperation = Operation.ADD;
                    break;
                case "-":
                    mOperation = Operation.SUB;
                    break;
                case "/":
                    mOperation = Operation.DIV;
                    break;
                case "X":
                    mOperation = Operation.MULT;
                    break;
                case "=":
                    mScore = mCalculator.compute(mLeftPart, mOperation, mRightPart);
                    tvScore.setText(Double.toString(mScore));
                    mIsNewCompute = true;
                    break;
                case "Clean":
                default:
                    initDefaultValues();
                    break;
                }
            } catch (Exception e) {
                Log.e("CalculatorActivity", e.getMessage());
                TextView tvLog = (TextView) getActivity().findViewById(R.id.tvLog);
                tvLog.setText(e.getMessage());
            }
        }
    };

    View parent = getView();
    parent.findViewById(R.id.button0).setOnClickListener(globalClickListener);
    parent.findViewById(R.id.button1).setOnClickListener(globalClickListener);
    parent.findViewById(R.id.button2).setOnClickListener(globalClickListener);
    parent.findViewById(R.id.button3).setOnClickListener(globalClickListener);
    parent.findViewById(R.id.button0).setOnClickListener(globalClickListener);
    parent.findViewById(R.id.button5).setOnClickListener(globalClickListener);
    parent.findViewById(R.id.button6).setOnClickListener(globalClickListener);
    parent.findViewById(R.id.button7).setOnClickListener(globalClickListener);
    parent.findViewById(R.id.button8).setOnClickListener(globalClickListener);
    parent.findViewById(R.id.button9).setOnClickListener(globalClickListener);
    parent.findViewById(R.id.buttonAdd).setOnClickListener(globalClickListener);
    parent.findViewById(R.id.buttonDiv).setOnClickListener(globalClickListener);
    parent.findViewById(R.id.buttonSub).setOnClickListener(globalClickListener);
    parent.findViewById(R.id.buttonMul).setOnClickListener(globalClickListener);
    parent.findViewById(R.id.buttonEqual).setOnClickListener(globalClickListener);
    parent.findViewById(R.id.buttonClean).setOnClickListener(globalClickListener);

}

From source file:com.bluetooth.comp529.bluetoothchatproj.chat.BluetoothChatFragment.java

/**
 * Set up the UI and background operations for chat.
 *//*from   w  w w .  j a  v a2s.  co  m*/
private void setupChat() {
    Log.d(TAG, "setupChat()");

    // Initialize the array adapter for the conversation thread
    mConversationArrayAdapter = new ArrayAdapter<String>(getActivity(), R.layout.message);

    mConversationView.setAdapter(mConversationArrayAdapter);

    // Initialize the compose field with a listener for the return key
    mOutEditText.setOnEditorActionListener(mWriteListener);

    // Initialize the send button with a listener that for click events
    mSendButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // Send a message using content of the edit text widget
            View view = getView();
            if (null != view) {
                TextView textView = (TextView) view.findViewById(R.id.edit_text_out);
                String message = textView.getText().toString();
                sendMessageToAll(message);
            }
        }
    });

    // Initialize the BluetoothChatService to perform bluetooth connections
    mChatService = new BluetoothChatService(mHandler);
    Log.d(TAG, "mChatService is Not NULL now");

    // Initialize the buffer for outgoing messages
    mOutStringBuffer = new StringBuffer("");
}

From source file:com.nest5.businessClient.AccountsActivity.java

/**
 * Sets up the 'connect' screen content.
 *///from www  .java 2 s  .  c  om
private void setConnectScreenContent() {
    List<String> accounts = getGoogleAccounts();
    if (accounts.size() == 0) {
        // Show a dialog and invoke the "Add Account" activity if requested
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setMessage(R.string.needs_account);
        builder.setPositiveButton(R.string.add_account, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                startActivity(new Intent(Settings.ACTION_ADD_ACCOUNT));
            }
        });
        builder.setNegativeButton(R.string.skip, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });
        builder.setIcon(android.R.drawable.stat_sys_warning);
        builder.setTitle(R.string.attention);
        builder.show();
    } else {
        final ListView listView = (ListView) findViewById(R.id.select_account);
        listView.setAdapter(new ArrayAdapter<String>(mContext, R.layout.account, accounts));
        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        listView.setItemChecked(mAccountSelectedPosition, true);

        final Button connectButton = (Button) findViewById(R.id.connect);
        connectButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                // Set "connecting" status
                SharedPreferences prefs = Util.getSharedPreferences(mContext);
                prefs.edit().putString(Util.CONNECTION_STATUS, Util.CONNECTING).commit();
                // Get account name
                mAccountSelectedPosition = listView.getCheckedItemPosition();
                TextView account = (TextView) listView.getChildAt(mAccountSelectedPosition);
                // Register
                register((String) account.getText());
                finish();
            }
        });
    }

    // internetConnectionStatus = (ImageView) findViewById(R.id.header_connection_status);
    SharedPreferences prefs = Util.getSharedPreferences(mContext);
    if (!isNetworkAvailable()) {
        internetConnectionStatus.setImageResource(R.drawable.error);

        prefs.edit().putInt(Util.INTERNET_CONNECTION, Util.INTERNET_DISCONNECTED).commit();
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(
                "No tienes una conexin a internet activa. Habiltala haciendo click en aceptar y seleccionando luego una red.")
                .setCancelable(false).setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
                        startActivityForResult(intent, 1);
                    }
                }).setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        finish();
                    }
                }).show();

    } else {
        prefs.edit().putInt(Util.INTERNET_CONNECTION, Util.INTERNET_CONNECTED).commit();
    }
}

From source file:cl.ipp.katbag.fragment.Edit.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    v = inflater.inflate(R.layout.fragment_edit, container, false);
    mainActivity = (MainActivity) super.getActivity();

    notRegister = (TextView) v.findViewById(R.id.edit_not_register);
    editMode = false;//  ww w  .  java 2s. co m
    loadListView();

    editListView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if (!editMode) {
                TextView idApp = (TextView) view.findViewById(R.id.edit_row_id);
                TextView nameApp = (TextView) view.findViewById(R.id.edit_row_name);
                TextView typeApp = (TextView) view.findViewById(R.id.edit_row_type_app);

                // initialize parameters of add class
                Add.id_app = Long.valueOf(idApp.getText().toString());
                Add.name_app_text = nameApp.getText().toString();

                Bundle bundle = new Bundle();
                bundle.putString("type_app", typeApp.getText().toString());

                mFragment = new Add();
                mFragment.setArguments(bundle);
                FragmentTransaction t = getActivity().getSupportFragmentManager().beginTransaction();
                t.replace(R.id.fragment_main_container, mFragment);
                t.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                t.addToBackStack(mFragment.getClass().getSimpleName());
                t.commit();
            }
        }
    });

    // id exposes
    editListView.setOnItemLongClickListener(new OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            TextView idApp = (TextView) arg1.findViewById(R.id.edit_row_id);
            KatbagUtilities.message(mainActivity.context,
                    getString(R.string.edit_get_id) + " " + idApp.getText().toString());
            return false;
        }
    });

    return v;
}