Example usage for android.text Editable toString

List of usage examples for android.text Editable toString

Introduction

In this page you can find the example usage for android.text Editable toString.

Prototype

public String toString();

Source Link

Document

Returns a string containing the characters in this sequence in the same order as this sequence.

Usage

From source file:com.synox.android.authentication.AuthenticatorActivity.java

/**
 * /* w  w  w.  ja v  a 2 s .  com*/
 * @param savedInstanceState        Saved activity state, as in {{@link #onCreate(Bundle)}
 */
private void initServerPreFragment(Bundle savedInstanceState) {

    /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
    boolean isUrlInputAllowed = getResources().getBoolean(R.bool.show_server_url_input);
    if (savedInstanceState == null) {
        if (mAccount != null) {
            mServerInfo.mBaseUrl = mAccountMgr.getUserData(mAccount, Constants.KEY_OC_BASE_URL);
            // TODO do next in a setter for mBaseUrl
            mServerInfo.mIsSslConn = mServerInfo.mBaseUrl.startsWith("https://");
            mServerInfo.mVersion = AccountUtils.getServerVersion(mAccount);
        } else {
            mServerInfo.mBaseUrl = getString(R.string.server_url).trim();
            mServerInfo.mIsSslConn = mServerInfo.mBaseUrl.startsWith("https://");
        }
    } else {
        mServerStatusText = savedInstanceState.getInt(KEY_SERVER_STATUS_TEXT);
        mServerStatusIcon = savedInstanceState.getInt(KEY_SERVER_STATUS_ICON);

        mServerIsValid = savedInstanceState.getBoolean(KEY_SERVER_VALID);
        mServerIsChecked = savedInstanceState.getBoolean(KEY_SERVER_CHECKED);

        // TODO parcelable
        mServerInfo.mIsSslConn = savedInstanceState.getBoolean(KEY_IS_SSL_CONN);
        mServerInfo.mBaseUrl = savedInstanceState.getString(KEY_HOST_URL_TEXT);
        String ocVersion = savedInstanceState.getString(KEY_OC_VERSION);
        if (ocVersion != null) {
            mServerInfo.mVersion = new OwnCloudVersion(ocVersion);
        }
        mServerInfo.mAuthMethod = AuthenticationMethod
                .valueOf(savedInstanceState.getString(KEY_SERVER_AUTH_METHOD));

    }

    /// step 2 - set properties of UI elements (text, visibility, enabled...)
    mHostUrlInput = (EditText) findViewById(R.id.hostUrlInput);
    // Convert IDN to Unicode
    mHostUrlInput.setText(DisplayUtils.convertIdn(mServerInfo.mBaseUrl, false));
    if (mAction != ACTION_CREATE) {
        /// lock things that should not change
        mHostUrlInput.setEnabled(false);
        mHostUrlInput.setFocusable(false);
    }
    if (isUrlInputAllowed) {
        mRefreshButton = findViewById(R.id.embeddedRefreshButton);
    } else {
        findViewById(R.id.hostUrlFrame).setVisibility(View.GONE);
        mRefreshButton = findViewById(R.id.centeredRefreshButton);
    }
    showRefreshButton(mServerIsChecked && !mServerIsValid && mWaitingForOpId > Integer.MAX_VALUE);
    mServerStatusView = (TextView) findViewById(R.id.server_status_text);
    showServerStatus();

    /// step 3 - bind some listeners and options
    mHostUrlInput.setImeOptions(EditorInfo.IME_ACTION_NEXT);
    mHostUrlInput.setOnEditorActionListener(this);

    /// step 4 - create listeners that will be bound at onResume
    mHostUrlInputWatcher = new TextWatcher() {

        @Override
        public void afterTextChanged(Editable s) {
            if (mOkButton.isEnabled()
                    && !mServerInfo.mBaseUrl.equals(normalizeUrl(s.toString(), mServerInfo.mIsSslConn))) {
                mOkButton.setEnabled(false);
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (mAuthStatusIcon != 0) {
                Log_OC.d(TAG, "onTextChanged: hiding authentication status");
                mAuthStatusIcon = 0;
                mAuthStatusText = 0;
                showAuthStatus();
            }
        }
    };

    // TODO find out if this is really necessary, or if it can done in a different way
    findViewById(R.id.scroll).setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType())
                        .equals(mAuthTokenType) && mHostUrlInput.hasFocus()) {
                    checkOcServer();
                }
            }
            return false;
        }
    });

    /// step 4 - mark automatic check to be started when OperationsService is ready
    mPendingAutoCheck = (savedInstanceState == null && (mAction != ACTION_CREATE || !isUrlInputAllowed));
}

From source file:me.tahnok.bluefruit.le.connect.app.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Init variables
    mBleManager = BleManager.getInstance(this);
    restoreRetainedDataFragment();/*from  w  ww. j  av  a2s.  c  o  m*/
    mPeripheralList = new PeripheralList();

    // UI
    mScannedDevicesListView = (ExpandableHeightExpandableListView) findViewById(R.id.scannedDevicesListView);
    mScannedDevicesAdapter = new ExpandableListAdapter();
    mScannedDevicesListView.setAdapter(mScannedDevicesAdapter);
    mScannedDevicesListView.setExpanded(true);

    mScannedDevicesListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
        @Override
        public void onGroupExpand(int groupPosition) {
        }
    });

    mScanButton = (Button) findViewById(R.id.scanButton);

    mNoDevicesTextView = (TextView) findViewById(R.id.nodevicesTextView);
    mDevicesScrollView = (ScrollView) findViewById(R.id.devicesScrollView);
    mDevicesScrollView.setVisibility(View.GONE);

    mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
    mSwipeRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
        @Override
        public void onRefresh() {
            mScannedDevices.clear();
            startScan(null);

            mSwipeRefreshLayout.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mSwipeRefreshLayout.setRefreshing(false);
                }
            }, 500);
        }
    });

    mFiltersPanelView = findViewById(R.id.filtersExpansionView);
    mFiltersExpandImageView = (ImageView) findViewById(R.id.filtersExpandImageView);
    mFiltersClearButton = (ImageButton) findViewById(R.id.filtersClearButton);
    mFiltersTitleTextView = (TextView) findViewById(R.id.filtersTitleTextView);
    mFiltersNameEditText = (EditText) findViewById(R.id.filtersNameEditText);
    mFiltersNameEditText.addTextChangedListener(new TextWatcher() {

        public void afterTextChanged(Editable s) {
            String text = s.toString();
            mPeripheralList.setFilterName(text);
            updateFilters();
        }

        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
    });
    mFiltersRssiSeekBar = (SeekBar) findViewById(R.id.filtersRssiSeekBar);
    mFiltersRssiSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            int rssiValue = -seekBar.getProgress();
            mPeripheralList.setFilterRssiValue(rssiValue);
            updateRssiValue();
            updateFilters();
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });
    mFiltersRssiValueTextView = (TextView) findViewById(R.id.filtersRssiValueTextView);
    mFiltersUnnamedCheckBox = (CheckBox) findViewById(R.id.filtersUnnamedCheckBox);
    mFiltersUnnamedCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            mPeripheralList.setFilterUnnamedEnabled(isChecked);
            updateFilters();
        }
    });

    // Filters
    SharedPreferences preferences = getSharedPreferences(kPreferences, MODE_PRIVATE);
    boolean filtersIsPanelOpen = preferences.getBoolean(kPreferences_filtersPanelOpen, false);
    openFiltersPanel(filtersIsPanelOpen, false);
    updateFiltersTitle();
    mFiltersNameEditText.setText(mPeripheralList.getFilterName());
    setRssiSliderValue(mPeripheralList.getFilterRssiValue());
    mFiltersUnnamedCheckBox.setChecked(mPeripheralList.isFilterUnnamedEnabled());

    // Setup when activity is created for the first time
    if (savedInstanceState == null) {
        // Read preferences
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        boolean autoResetBluetoothOnStart = sharedPreferences.getBoolean("pref_resetble", false);
        boolean disableWifi = sharedPreferences.getBoolean("pref_disableWifi", false);
        boolean updatesEnabled = sharedPreferences.getBoolean("pref_updatesenabled", true);

        // Update SoftwareUpdateManager
        if (updatesEnabled) {
            mFirmwareUpdater = new FirmwareUpdater(this, this);
            mFirmwareUpdater.refreshSoftwareUpdatesDatabase();
        }

        // Turn off wifi
        if (disableWifi) {
            final boolean isWifiEnabled = BleUtils.isWifiEnabled(this);
            if (isWifiEnabled) {
                BleUtils.enableWifi(false, this);
                mShouldEnableWifiOnQuit = true;
            }
        }

        // Check if bluetooth adapter is available
        final boolean wasBluetoothEnabled = manageBluetoothAvailability();
        final boolean areLocationServicesReadyForScanning = manageLocationServiceAvailabilityForScanning();

        // Reset bluetooth
        if (autoResetBluetoothOnStart && wasBluetoothEnabled && areLocationServicesReadyForScanning) {
            BleUtils.resetBluetoothAdapter(this, this);
        }
    }

    // Request Bluetooth scanning persmissions
    requestLocationPermissionIfNeeded();
}

From source file:com.cesquerr.becky.app.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Init variables
    mBleManager = BleManager.getInstance(this);
    restoreRetainedDataFragment();/*w  ww.  j a  va2 s  .  c  o  m*/
    mPeripheralList = new PeripheralList();

    // UI
    mScannedDevicesListView = (ExpandableHeightExpandableListView) findViewById(R.id.scannedDevicesListView);
    mScannedDevicesAdapter = new ExpandableListAdapter();
    mScannedDevicesListView.setAdapter(mScannedDevicesAdapter);
    mScannedDevicesListView.setExpanded(true);

    mScannedDevicesListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
        @Override
        public void onGroupExpand(int groupPosition) {
        }
    });

    mScanButton = (Button) findViewById(R.id.scanButton);

    mNoDevicesTextView = (TextView) findViewById(R.id.nodevicesTextView);
    mDevicesScrollView = (ScrollView) findViewById(R.id.devicesScrollView);
    mDevicesScrollView.setVisibility(View.GONE);

    mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
    mSwipeRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
        @Override
        public void onRefresh() {
            mScannedDevices.clear();
            startScan(null);

            mSwipeRefreshLayout.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mSwipeRefreshLayout.setRefreshing(false);
                }
            }, 500);
        }
    });

    mFiltersPanelView = findViewById(R.id.filtersExpansionView);
    mFiltersExpandImageView = (ImageView) findViewById(R.id.filtersExpandImageView);
    mFiltersClearButton = (ImageButton) findViewById(R.id.filtersClearButton);
    mFiltersTitleTextView = (TextView) findViewById(R.id.filtersTitleTextView);
    mFiltersNameEditText = (EditText) findViewById(R.id.filtersNameEditText);
    mFiltersNameEditText.addTextChangedListener(new TextWatcher() {

        public void afterTextChanged(Editable s) {
            String text = s.toString();
            mPeripheralList.setFilterName(text);
            updateFilters();
        }

        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
    });
    mFiltersRssiSeekBar = (SeekBar) findViewById(R.id.filtersRssiSeekBar);
    mFiltersRssiSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            int rssiValue = -seekBar.getProgress();
            mPeripheralList.setFilterRssiValue(rssiValue);
            updateRssiValue();
            updateFilters();
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });
    mFiltersRssiValueTextView = (TextView) findViewById(R.id.filtersRssiValueTextView);
    mFiltersUnnamedCheckBox = (CheckBox) findViewById(R.id.filtersUnnamedCheckBox);
    mFiltersUnnamedCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            mPeripheralList.setFilterUnnamedEnabled(isChecked);
            updateFilters();
        }
    });
    mFiltersUartCheckBox = (CheckBox) findViewById(R.id.filtersUartCheckBox);
    mFiltersUartCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            mPeripheralList.setFilterOnlyUartEnabled(isChecked);
            updateFilters();
        }
    });

    // Filters
    SharedPreferences preferences = getSharedPreferences(kPreferences, MODE_PRIVATE);
    boolean filtersIsPanelOpen = preferences.getBoolean(kPreferences_filtersPanelOpen, false);
    openFiltersPanel(filtersIsPanelOpen, false);
    updateFiltersTitle();
    mFiltersNameEditText.setText(mPeripheralList.getFilterName());
    setRssiSliderValue(mPeripheralList.getFilterRssiValue());
    mFiltersUnnamedCheckBox.setChecked(mPeripheralList.isFilterUnnamedEnabled());
    mFiltersUartCheckBox.setChecked(mPeripheralList.isFilterOnlyUartEnabled());

    // Setup when activity is created for the first time
    if (savedInstanceState == null) {
        // Read preferences
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        boolean autoResetBluetoothOnStart = sharedPreferences.getBoolean("pref_resetble", false);
        boolean disableWifi = sharedPreferences.getBoolean("pref_disableWifi", false);
        boolean updatesEnabled = sharedPreferences.getBoolean("pref_updatesenabled", true);

        // Update SoftwareUpdateManager
        if (updatesEnabled) {
            mFirmwareUpdater = new FirmwareUpdater(this, this);
            mFirmwareUpdater.refreshSoftwareUpdatesDatabase();
        }

        // Turn off wifi
        if (disableWifi) {
            final boolean isWifiEnabled = BleUtils.isWifiEnabled(this);
            if (isWifiEnabled) {
                BleUtils.enableWifi(false, this);
                mShouldEnableWifiOnQuit = true;
            }
        }

        // Check if bluetooth adapter is available
        final boolean wasBluetoothEnabled = manageBluetoothAvailability();
        final boolean areLocationServicesReadyForScanning = manageLocationServiceAvailabilityForScanning();

        // Reset bluetooth
        if (autoResetBluetoothOnStart && wasBluetoothEnabled && areLocationServicesReadyForScanning) {
            BleUtils.resetBluetoothAdapter(this, this);
        }
    }

    // Request Bluetooth scanning permissions
    requestLocationPermissionIfNeeded();
}

From source file:com.openatk.planting.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    dbHelper = new DatabaseHelper(this);

    FragmentManager fm = getSupportFragmentManager();
    fragMap = (SupportMapFragment) fm.findFragmentById(R.id.map);

    fragmentEditField = (FragmentEditJobPopup) fm.findFragmentByTag("edit_job");

    if (savedInstanceState == null) {
        // First incarnation of this activity.
        fragMap.setRetainInstance(true);
    } else {/*from  ww w.ja  va  2s.  c o  m*/
        // Reincarnated activity. The obtained map is the same map instance
        // in the previous
        // activity life cycle. There is no need to reinitialize it.
        map = fragMap.getMap();
    }
    checkGPS();

    actionBar = getActionBar();
    // Specify that a dropdown list should be displayed in the action bar.
    // actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);

    // Hide the title
    actionBar.setDisplayShowTitleEnabled(false);
    actionBar.setDisplayUseLogoEnabled(false);

    actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM, ActionBar.DISPLAY_SHOW_CUSTOM);
    View view;
    LayoutInflater inflater = (LayoutInflater) this.getApplicationContext()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    view = inflater.inflate(R.layout.action_bar, null);
    RelativeLayout item = (RelativeLayout) view.findViewById(R.id.action_bar_layout);
    spinnerMenu = (Spinner) view.findViewById(R.id.action_bar_operation_spinner);
    actionBarSearch = (EditText) view.findViewById(R.id.action_bar_search_box);
    actionBar.setCustomView(item, new ActionBar.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT,
            ActionBar.LayoutParams.WRAP_CONTENT, Gravity.CENTER_VERTICAL | Gravity.LEFT));

    actionBarSearch.setOnFocusChangeListener(new OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus == false) {
                InputMethodManager imm = (InputMethodManager) v.getContext()
                        .getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
            }
        }
    });
    actionBarSearch.addTextChangedListener(new TextWatcher() {
        @Override
        public void afterTextChanged(Editable s) {
            if (fragmentListView != null)
                fragmentListView.search(s.toString());
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }
    });

    Fragment fragment = fm.findFragmentById(R.id.list_view);
    FragmentTransaction ft = fm.beginTransaction();
    ft.hide(fragment);
    ft.commit();

    //Trello
    trelloController = new TrelloController(getApplicationContext());
    syncController = new SyncController(getApplicationContext(), trelloController, this);
    trelloController.setSyncController(syncController);

    // Get last selected operation
    if (savedInstanceState != null) {
        // Find current field
        currentField = FindFieldById(savedInstanceState.getInt("currentField"));

        // Find current job
        currentJob = FindJobById(savedInstanceState.getInt("currentJob"));

        // Find current operation
        currentOperationId = savedInstanceState.getInt("currentOperationId");

        editIsShowing = savedInstanceState.getInt("editIsShowing");
        addIsShowing = savedInstanceState.getInt("addIsShowing");

        this.addingBoundary = savedInstanceState.getString("drawingBoundary", "");

        // Switch to correct state
        setState(savedInstanceState.getInt("mCurrentState"), false);
    }

    // Load operations from database
    loadOperations();

    // Specify a SpinnerAdapter to populate the dropdown list.
    spinnerMenuAdapter = new ArrayAdapter<Operation>(this, R.layout.operation_list_item, operationsList);
    spinnerMenu.setAdapter(spinnerMenuAdapter);
    // Load current from preferences
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    currentOperationId = prefs.getInt("currentOperationId", 0);
    this.showingHazards = prefs.getBoolean("showingHazards", false);
    selectCurrentOperationInSpinner();
    spinnerMenu.setOnItemSelectedListener(this);

    setUpMapIfNeeded();

    Intent intent = this.getIntent();
    String todo = intent.getStringExtra("todo");
    if (todo != null) {
        if (todo.contentEquals("sync")) {
            trelloController.sync();
        }
    }
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}

From source file:com.adafruit.bluefruit.le.connect.app.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    activity = this;
    setContentView(R.layout.activity_main);

    // Init variables
    mBleManager = BleManager.getInstance(this);
    restoreRetainedDataFragment();/*from w w  w  .  ja v a2s . c o m*/
    mPeripheralList = new PeripheralList();

    // UI
    mScannedDevicesListView = (ExpandableHeightExpandableListView) findViewById(R.id.scannedDevicesListView);
    mScannedDevicesAdapter = new ExpandableListAdapter();
    mScannedDevicesListView.setAdapter(mScannedDevicesAdapter);
    mScannedDevicesListView.setExpanded(true);

    mScannedDevicesListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
        @Override
        public void onGroupExpand(int groupPosition) {
        }
    });

    mScanButton = (Button) findViewById(R.id.scanButton);

    mNoDevicesTextView = (TextView) findViewById(R.id.nodevicesTextView);
    mDevicesScrollView = (ScrollView) findViewById(R.id.devicesScrollView);
    mDevicesScrollView.setVisibility(View.GONE);

    mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
    mSwipeRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
        @Override
        public void onRefresh() {
            mScannedDevices.clear();
            startScan(null);

            mSwipeRefreshLayout.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mSwipeRefreshLayout.setRefreshing(false);
                }
            }, 500);
        }
    });

    mFiltersPanelView = findViewById(R.id.filtersExpansionView);
    mFiltersExpandImageView = (ImageView) findViewById(R.id.filtersExpandImageView);
    mFiltersClearButton = (ImageButton) findViewById(R.id.filtersClearButton);
    mFiltersTitleTextView = (TextView) findViewById(R.id.filtersTitleTextView);
    mFiltersNameEditText = (EditText) findViewById(R.id.filtersNameEditText);
    mFiltersNameEditText.addTextChangedListener(new TextWatcher() {

        public void afterTextChanged(Editable s) {
            String text = s.toString();
            mPeripheralList.setFilterName(text);
            updateFilters();
        }

        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
    });
    mFiltersRssiSeekBar = (SeekBar) findViewById(R.id.filtersRssiSeekBar);
    mFiltersRssiSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            int rssiValue = -seekBar.getProgress();
            mPeripheralList.setFilterRssiValue(rssiValue);
            updateRssiValue();
            updateFilters();
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });
    mFiltersRssiValueTextView = (TextView) findViewById(R.id.filtersRssiValueTextView);
    mFiltersUnnamedCheckBox = (CheckBox) findViewById(R.id.filtersUnnamedCheckBox);
    mFiltersUnnamedCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            mPeripheralList.setFilterUnnamedEnabled(isChecked);
            updateFilters();
        }
    });
    mFiltersUartCheckBox = (CheckBox) findViewById(R.id.filtersUartCheckBox);
    mFiltersUartCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            mPeripheralList.setFilterOnlyUartEnabled(isChecked);
            updateFilters();
        }
    });

    // Filters
    SharedPreferences preferences = getSharedPreferences(kPreferences, MODE_PRIVATE);
    boolean filtersIsPanelOpen = preferences.getBoolean(kPreferences_filtersPanelOpen, false);
    openFiltersPanel(filtersIsPanelOpen, false);
    updateFiltersTitle();
    mFiltersNameEditText.setText(mPeripheralList.getFilterName());
    setRssiSliderValue(mPeripheralList.getFilterRssiValue());
    mFiltersUnnamedCheckBox.setChecked(mPeripheralList.isFilterUnnamedEnabled());
    mFiltersUartCheckBox.setChecked(mPeripheralList.isFilterOnlyUartEnabled());

    // Setup when activity is created for the first time
    if (savedInstanceState == null) {
        // Read preferences
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        boolean autoResetBluetoothOnStart = sharedPreferences.getBoolean("pref_resetble", false);
        boolean disableWifi = sharedPreferences.getBoolean("pref_disableWifi", false);
        boolean updatesEnabled = sharedPreferences.getBoolean("pref_updatesenabled", true);

        // Update SoftwareUpdateManager
        if (updatesEnabled) {
            mFirmwareUpdater = new FirmwareUpdater(this, this);
            mFirmwareUpdater.refreshSoftwareUpdatesDatabase();
        }

        // Turn off wifi
        if (disableWifi) {
            final boolean isWifiEnabled = BleUtils.isWifiEnabled(this);
            if (isWifiEnabled) {
                BleUtils.enableWifi(false, this);
                mShouldEnableWifiOnQuit = true;
            }
        }

        // Check if bluetooth adapter is available
        final boolean wasBluetoothEnabled = manageBluetoothAvailability();
        final boolean areLocationServicesReadyForScanning = manageLocationServiceAvailabilityForScanning();

        // Reset bluetooth
        if (autoResetBluetoothOnStart && wasBluetoothEnabled && areLocationServicesReadyForScanning) {
            BleUtils.resetBluetoothAdapter(this, this);
        }
    }

    // Request Bluetooth scanning persmissions
    requestLocationPermissionIfNeeded();
}

From source file:com.sonetel.ui.dialpad.DialerFragment.java

public void afterTextChanged(Editable input) {
    // Change state of digit dialer
    final boolean notEmpty = digits.length() != 0;
    //digitsWrapper.setBackgroundDrawable(notEmpty ? digitsBackground : digitsEmptyBackground);
    callBar.setEnabled(notEmpty);//from w w w . j ava  2s  .  c om

    if (!notEmpty && isDigit) {
        digits.setCursorVisible(false);
    }
    applyTextToAutoComplete();
    checkDialingCountry(input.toString());

}

From source file:foam.opensauces.StarwispBuilder.java

public void Build(final StarwispActivity ctx, final String ctxname, JSONArray arr, ViewGroup parent) {

    try {/*  ww  w  .  j  a  v  a2 s.  c  o  m*/
        String type = arr.getString(0);

        //Log.i("starwisp","building started "+type);

        if (type.equals("build-fragment")) {
            String name = arr.getString(1);
            int ID = arr.getInt(2);
            Fragment fragment = ActivityManager.GetFragment(name);
            LinearLayout inner = new LinearLayout(ctx);
            inner.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));
            inner.setId(ID);
            FragmentTransaction fragmentTransaction = ctx.getSupportFragmentManager().beginTransaction();
            fragmentTransaction.add(ID, fragment);
            fragmentTransaction.commit();
            parent.addView(inner);
            return;
        }

        if (type.equals("linear-layout")) {
            LinearLayout v = new LinearLayout(ctx);
            v.setId(arr.getInt(1));
            v.setOrientation(BuildOrientation(arr.getString(2)));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));
            //v.setPadding(2,2,2,2);
            JSONArray col = arr.getJSONArray(4);
            v.setBackgroundColor(Color.argb(col.getInt(3), col.getInt(0), col.getInt(1), col.getInt(2)));
            parent.addView(v);
            JSONArray children = arr.getJSONArray(5);
            for (int i = 0; i < children.length(); i++) {
                Build(ctx, ctxname, new JSONArray(children.getString(i)), v);
            }
            return;
        }

        if (type.equals("draggable")) {
            final LinearLayout v = new LinearLayout(ctx);
            final int id = arr.getInt(1);
            v.setPadding(20, 20, 20, 20);
            v.setId(id);
            v.setOrientation(BuildOrientation(arr.getString(2)));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));
            v.setClickable(true);
            v.setFocusable(true);

            JSONArray col = arr.getJSONArray(4);
            v.setBackgroundResource(R.drawable.draggable);

            GradientDrawable drawable = (GradientDrawable) v.getBackground();
            final int colour = Color.argb(col.getInt(3), col.getInt(0), col.getInt(1), col.getInt(2));
            drawable.setColor(colour);

            parent.addView(v);
            JSONArray children = arr.getJSONArray(5);
            for (int i = 0; i < children.length(); i++) {
                Build(ctx, ctxname, new JSONArray(children.getString(i)), v);
            }

            // Sets a long click listener for the ImageView using an anonymous listener object that
            // implements the OnLongClickListener interface
            /*                v.setOnLongClickListener(new View.OnLongClickListener() {
            public boolean onLongClick(View vv) {
                if (id!=99) {
                    ClipData dragData = ClipData.newPlainText("simple text", ""+id);
                    View.DragShadowBuilder myShadow = new MyDragShadowBuilder(v);
                    Log.i("starwisp","start drag id "+vv.getId());
                    v.startDrag(dragData, myShadow, null, 0);
                    v.setVisibility(View.GONE);
                    return true;
                }
                return false;
            }
                            });
            */
            // Sets a long click listener for the ImageView using an anonymous listener object that
            // implements the OnLongClickListener interface
            v.setOnTouchListener(new View.OnTouchListener() {
                public boolean onTouch(View vv, MotionEvent event) {
                    if (event.getAction() == MotionEvent.ACTION_DOWN && id != 99) {
                        //                            ClipData dragData = ClipData.newPlainText("simple text", ""+id);

                        ClipData dragData = new ClipData(
                                new ClipDescription(null, new String[] { ClipDescription.MIMETYPE_TEXT_PLAIN }),
                                new ClipData.Item("" + id));

                        View.DragShadowBuilder myShadow = new MyDragShadowBuilder(v);
                        Log.i("starwisp", "start drag id " + vv.getId());
                        v.startDrag(dragData, myShadow, null, 0);
                        v.setVisibility(View.GONE);
                        return true;
                    }
                    return false;
                }
            });

            v.setOnDragListener(new View.OnDragListener() {
                public boolean onDrag(View vv, DragEvent event) {
                    final int action = event.getAction();
                    switch (action) {
                    case DragEvent.ACTION_DRAG_STARTED:
                        if (event.getClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)) {
                            // returns true to indicate that the View can accept the dragged data.
                            return true;
                        } else {
                            // Returns false. During the current drag and drop operation, this View will
                            // not receive events again until ACTION_DRAG_ENDED is sent.
                            return false;
                        }
                    case DragEvent.ACTION_DRAG_ENTERED: {
                        return true;
                    }
                    case DragEvent.ACTION_DRAG_LOCATION:
                        return true;
                    case DragEvent.ACTION_DRAG_EXITED: {
                        return true;
                    }
                    case DragEvent.ACTION_DROP: {
                        ClipData.Item item = event.getClipData().getItemAt(0);
                        String dragData = item.getText().toString();
                        Log.i("starwisp", "Dragged view is " + dragData);
                        int otherid = Integer.parseInt(dragData);
                        View otherw = ctx.findViewById(otherid);
                        Log.i("starwisp", "removing from parent " + ((View) otherw.getParent()).getId());

                        // check we are not adding to ourself
                        if (id != otherid) {
                            ((ViewManager) otherw.getParent()).removeView(otherw);
                            Log.i("starwisp", "adding to " + id);
                            v.addView(otherw);
                        }
                        otherw.setVisibility(View.VISIBLE);
                        return true;
                    }
                    case DragEvent.ACTION_DRAG_ENDED: {
                        if (event.getResult()) {
                        } else {
                        }
                        ;
                        return true;
                    }
                    // An unknown action type was received.
                    default:
                        Log.e("starwisp", "Unknown action type received by OnDragListener.");
                        break;
                    }
                    ;
                    return true;
                }
            });
            return;
        }

        if (type.equals("frame-layout")) {
            FrameLayout v = new FrameLayout(ctx);
            v.setId(arr.getInt(1));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            parent.addView(v);
            JSONArray children = arr.getJSONArray(3);
            for (int i = 0; i < children.length(); i++) {
                Build(ctx, ctxname, new JSONArray(children.getString(i)), v);
            }
            return;
        }

        /*
        if (type.equals("grid-layout")) {
        GridLayout v = new GridLayout(ctx);
        v.setId(arr.getInt(1));
        v.setRowCount(arr.getInt(2));
        //v.setColumnCount(arr.getInt(2));
        v.setOrientation(BuildOrientation(arr.getString(3)));
        v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4)));
                
        parent.addView(v);
        JSONArray children = arr.getJSONArray(5);
        for (int i=0; i<children.length(); i++) {
            Build(ctx,ctxname,new JSONArray(children.getString(i)), v);
        }
                
        return;
        }
        */

        if (type.equals("scroll-view")) {
            HorizontalScrollView v = new HorizontalScrollView(ctx);
            v.setId(arr.getInt(1));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            parent.addView(v);
            JSONArray children = arr.getJSONArray(3);
            for (int i = 0; i < children.length(); i++) {
                Build(ctx, ctxname, new JSONArray(children.getString(i)), v);
            }
            return;
        }

        if (type.equals("scroll-view-vert")) {
            ScrollView v = new ScrollView(ctx);
            v.setId(arr.getInt(1));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            parent.addView(v);
            JSONArray children = arr.getJSONArray(3);
            for (int i = 0; i < children.length(); i++) {
                Build(ctx, ctxname, new JSONArray(children.getString(i)), v);
            }
            return;
        }

        if (type.equals("view-pager")) {
            ViewPager v = new ViewPager(ctx);
            v.setId(arr.getInt(1));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            v.setOffscreenPageLimit(3);
            final JSONArray items = arr.getJSONArray(3);

            v.setAdapter(new FragmentPagerAdapter(ctx.getSupportFragmentManager()) {

                @Override
                public int getCount() {
                    return items.length();
                }

                @Override
                public Fragment getItem(int position) {
                    try {
                        String fragname = items.getString(position);
                        return ActivityManager.GetFragment(fragname);
                    } catch (JSONException e) {
                        Log.e("starwisp", "Error parsing data " + e.toString());
                    }
                    return null;
                }
            });
            parent.addView(v);
            return;
        }

        if (type.equals("space")) {
            // Space v = new Space(ctx); (class not found runtime error??)
            TextView v = new TextView(ctx);
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            parent.addView(v);
        }

        if (type.equals("image-view")) {
            ImageView v = new ImageView(ctx);
            v.setId(arr.getInt(1));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));

            String image = arr.getString(2);

            if (image.startsWith("/")) {
                Bitmap bitmap = BitmapFactory.decodeFile(image);
                v.setImageBitmap(bitmap);
            } else {
                int id = ctx.getResources().getIdentifier(image, "drawable", ctx.getPackageName());
                v.setImageResource(id);
            }

            parent.addView(v);
        }

        if (type.equals("text-view")) {
            TextView v = new TextView(ctx);
            v.setId(arr.getInt(1));
            v.setText(Html.fromHtml(arr.getString(2)));
            v.setTextSize(arr.getInt(3));
            v.setMovementMethod(LinkMovementMethod.getInstance());
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4)));
            v.setClickable(false);
            v.setEnabled(false);

            v.setOnTouchListener(new View.OnTouchListener() {
                public boolean onTouch(View vv, MotionEvent event) {
                    return false;
                }
            });

            if (arr.length() > 5) {
                if (arr.getString(5).equals("left")) {
                    v.setGravity(Gravity.LEFT);
                } else {
                    if (arr.getString(5).equals("fill")) {
                        v.setGravity(Gravity.FILL);
                    } else {
                        v.setGravity(Gravity.CENTER);
                    }
                }
            } else {
                v.setGravity(Gravity.LEFT);
            }
            v.setTypeface(((StarwispActivity) ctx).m_Typeface);
            parent.addView(v);
        }

        if (type.equals("debug-text-view")) {
            TextView v = (TextView) ctx.getLayoutInflater().inflate(R.layout.debug_text, null);
            //                v.setBackgroundResource(R.color.black);
            v.setId(arr.getInt(1));
            //                v.setText(Html.fromHtml(arr.getString(2)));
            //                v.setTextColor(R.color.white);
            //                v.setTextSize(arr.getInt(3));
            //                v.setMovementMethod(LinkMovementMethod.getInstance());
            //                v.setMaxLines(10);
            //                v.setVerticalScrollBarEnabled(true);
            //                v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4)));
            //v.setMovementMethod(new ScrollingMovementMethod());

            /*
            if (arr.length()>5) {
            if (arr.getString(5).equals("left")) {
                v.setGravity(Gravity.LEFT);
            } else {
                if (arr.getString(5).equals("fill")) {
                    v.setGravity(Gravity.FILL);
                } else {
                    v.setGravity(Gravity.CENTER);
                }
            }
            } else {
            v.setGravity(Gravity.LEFT);
            }
            v.setTypeface(((StarwispActivity)ctx).m_Typeface);*/
            parent.addView(v);
        }

        if (type.equals("web-view")) {
            WebView v = new WebView(ctx);
            v.setId(arr.getInt(1));
            v.setVerticalScrollBarEnabled(false);
            v.loadData(arr.getString(2), "text/html", "utf-8");
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));
            parent.addView(v);
        }

        if (type.equals("edit-text")) {
            final EditText v = new EditText(ctx);
            v.setId(arr.getInt(1));
            v.setText(arr.getString(2));
            v.setTextSize(arr.getInt(3));

            String inputtype = arr.getString(4);
            if (inputtype.equals("text")) {
                //v.setInputType(InputType.TYPE_CLASS_TEXT);
            } else if (inputtype.equals("numeric")) {
                v.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
            } else if (inputtype.equals("email")) {
                v.setInputType(InputType.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS);
            }

            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(5)));
            v.setTypeface(((StarwispActivity) ctx).m_Typeface);
            final String fn = arr.getString(5);
            //v.setSingleLine(true);

            v.addTextChangedListener(new TextWatcher() {
                public void afterTextChanged(Editable s) {
                    CallbackArgs(ctx, ctxname, v.getId(), "\"" + s.toString() + "\"");
                }

                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }

                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }
            });

            parent.addView(v);
        }

        if (type.equals("button")) {
            Button v = new Button(ctx);
            v.setId(arr.getInt(1));
            v.setText(arr.getString(2));
            v.setTextSize(arr.getInt(3));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4)));
            v.setTypeface(((StarwispActivity) ctx).m_Typeface);
            final String fn = arr.getString(5);
            v.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    Callback(ctx, ctxname, v.getId());
                }
            });

            parent.addView(v);
        }

        if (type.equals("toggle-button")) {
            ToggleButton v = new ToggleButton(ctx);
            if (arr.getString(5).equals("fancy")) {
                v = (ToggleButton) ctx.getLayoutInflater().inflate(R.layout.toggle_button_fancy, null);
            }

            if (arr.getString(5).equals("yes")) {
                v = (ToggleButton) ctx.getLayoutInflater().inflate(R.layout.toggle_button_yes, null);
            }

            if (arr.getString(5).equals("maybe")) {
                v = (ToggleButton) ctx.getLayoutInflater().inflate(R.layout.toggle_button_maybe, null);
            }

            if (arr.getString(5).equals("no")) {
                v = (ToggleButton) ctx.getLayoutInflater().inflate(R.layout.toggle_button_no, null);
            }

            v.setId(arr.getInt(1));
            v.setText(arr.getString(2));
            v.setTextSize(arr.getInt(3));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4)));
            v.setTypeface(((StarwispActivity) ctx).m_Typeface);
            final String fn = arr.getString(6);
            v.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    String arg = "#f";
                    if (((ToggleButton) v).isChecked())
                        arg = "#t";
                    CallbackArgs(ctx, ctxname, v.getId(), arg);
                }
            });
            parent.addView(v);
        }

        if (type.equals("seek-bar")) {
            SeekBar v = new SeekBar(ctx);
            v.setId(arr.getInt(1));
            v.setMax(arr.getInt(2));
            v.setProgress(arr.getInt(2) / 2);
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));
            final String fn = arr.getString(4);

            v.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                public void onProgressChanged(SeekBar v, int a, boolean s) {
                    CallbackArgs(ctx, ctxname, v.getId(), Integer.toString(a));
                }

                public void onStartTrackingTouch(SeekBar v) {
                }

                public void onStopTrackingTouch(SeekBar v) {
                }
            });
            parent.addView(v);
        }

        if (type.equals("spinner")) {
            Spinner v = new Spinner(ctx);
            final int wid = arr.getInt(1);
            v.setId(wid);
            final JSONArray items = arr.getJSONArray(2);
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));
            ArrayList<String> spinnerArray = new ArrayList<String>();

            for (int i = 0; i < items.length(); i++) {
                spinnerArray.add(items.getString(i));
            }

            ArrayAdapter spinnerArrayAdapter = new ArrayAdapter<String>(ctx, R.layout.spinner_item,
                    spinnerArray) {
                public View getView(int position, View convertView, ViewGroup parent) {
                    View v = super.getView(position, convertView, parent);
                    ((TextView) v).setTypeface(((StarwispActivity) ctx).m_Typeface);
                    return v;
                }
            };

            spinnerArrayAdapter.setDropDownViewResource(R.layout.spinner_layout);

            v.setAdapter(spinnerArrayAdapter);
            v.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                public void onItemSelected(AdapterView<?> a, View v, int pos, long id) {
                    try {
                        CallbackArgs(ctx, ctxname, wid, "\"" + items.getString(pos) + "\"");
                    } catch (JSONException e) {
                        Log.e("starwisp", "Error parsing data " + e.toString());
                    }
                }

                public void onNothingSelected(AdapterView<?> v) {
                }
            });

            parent.addView(v);
        }

        if (type.equals("canvas")) {
            StarwispCanvas v = new StarwispCanvas(ctx);
            final int wid = arr.getInt(1);
            v.setId(wid);
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            v.SetDrawList(arr.getJSONArray(3));
            parent.addView(v);
        }

        if (type.equals("camera-preview")) {
            PictureTaker pt = new PictureTaker();
            CameraPreview v = new CameraPreview(ctx, pt);
            final int wid = arr.getInt(1);
            v.setId(wid);

            //              LinearLayout.LayoutParams lp =
            //  new LinearLayout.LayoutParams(minWidth, minHeight, 1);

            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));

            //                v.setLayoutParams(lp);
            parent.addView(v);
        }

        if (type.equals("button-grid")) {
            LinearLayout horiz = new LinearLayout(ctx);
            final int id = arr.getInt(1);
            final String buttontype = arr.getString(2);
            horiz.setId(id);
            horiz.setOrientation(LinearLayout.HORIZONTAL);
            parent.addView(horiz);
            int height = arr.getInt(3);
            int textsize = arr.getInt(4);
            LinearLayout.LayoutParams lp = BuildLayoutParams(arr.getJSONArray(5));
            JSONArray buttons = arr.getJSONArray(6);
            int count = buttons.length();
            int vertcount = 0;
            LinearLayout vert = null;

            for (int i = 0; i < count; i++) {
                JSONArray button = buttons.getJSONArray(i);

                if (vertcount == 0) {
                    vert = new LinearLayout(ctx);
                    vert.setId(0);
                    vert.setOrientation(LinearLayout.VERTICAL);
                    horiz.addView(vert);
                }
                vertcount = (vertcount + 1) % height;

                if (buttontype.equals("button")) {
                    Button b = new Button(ctx);
                    b.setId(button.getInt(0));
                    b.setText(button.getString(1));
                    b.setTextSize(textsize);
                    b.setLayoutParams(lp);
                    b.setTypeface(((StarwispActivity) ctx).m_Typeface);
                    final String fn = arr.getString(6);
                    b.setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                            CallbackArgs(ctx, ctxname, id, "" + v.getId() + " #t");
                        }
                    });
                    vert.addView(b);
                } else if (buttontype.equals("toggle")) {
                    ToggleButton b = new ToggleButton(ctx);
                    b.setId(button.getInt(0));
                    b.setText(button.getString(1));
                    b.setTextSize(textsize);
                    b.setLayoutParams(lp);
                    b.setTypeface(((StarwispActivity) ctx).m_Typeface);
                    final String fn = arr.getString(6);
                    b.setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                            String arg = "#f";
                            if (((ToggleButton) v).isChecked())
                                arg = "#t";
                            CallbackArgs(ctx, ctxname, id, "" + v.getId() + " " + arg);
                        }
                    });
                    vert.addView(b);
                }
            }
        }

    } catch (JSONException e) {
        Log.e("starwisp", "Error parsing [" + arr.toString() + "] " + e.toString());
    }

    //Log.i("starwisp","building ended");

}

From source file:pro.dbro.bart.TheActivity.java

/** Called when the activity is first created. */
@Override/*from  w w  w. j ava2s  .  c  om*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //TESTING: enable crittercism
    Crittercism.init(getApplicationContext(), SECRETS.CRITTERCISM_SECRET);

    if (Build.VERSION.SDK_INT < 11) {
        //If API 14+, The ActionBar will be hidden with this call
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    }
    setContentView(R.layout.main);
    tableLayout = (TableLayout) findViewById(R.id.tableLayout);
    tableContainerLayout = (LinearLayout) findViewById(R.id.tableContainerLayout);
    c = this;
    res = getResources();
    prefs = getSharedPreferences("PREFS", 0);
    editor = prefs.edit();

    if (prefs.getBoolean("first_timer", true)) {
        TextView greetingTv = (TextView) View.inflate(c, R.layout.tabletext, null);
        greetingTv.setText(Html.fromHtml(getString(R.string.greeting)));
        greetingTv.setTextSize(18);
        greetingTv.setPadding(0, 0, 0, 0);
        greetingTv.setMovementMethod(LinkMovementMethod.getInstance());
        new AlertDialog.Builder(c).setTitle("Welcome to Open BART").setIcon(R.drawable.ic_launcher)
                .setView(greetingTv).setPositiveButton("Okay!", null).show();

        editor.putBoolean("first_timer", false);
        editor.commit();
    }
    // LocalBroadCast Stuff
    LocalBroadcastManager.getInstance(this).registerReceiver(serviceStateMessageReceiver,
            new IntentFilter("service_status_change"));

    // infoLayout is at the bottom of the screen
    // currently contains the stop service label 
    infoLayout = (LinearLayout) findViewById(R.id.infoLayout);

    // Assign the stationSuggestions Set
    stationSuggestions = new ArrayList();

    // Assign the bart station list to the autocompletetextviews 
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line,
            BART.STATIONS);
    originTextView = (AutoCompleteTextView) findViewById(R.id.originTv);
    // Set tag for array adapter switch
    originTextView.setTag(R.id.TextInputShowingSuggestions, "false");

    fareTv = (TextView) findViewById(R.id.fareTv);
    stopServiceTv = (TextView) findViewById(R.id.stopServiceTv);

    destinationTextView = (AutoCompleteTextView) findViewById(R.id.destinationTv);
    destinationTextView.setTag(R.id.TextInputShowingSuggestions, "false");
    destinationTextView.setAdapter(adapter);
    originTextView.setAdapter(adapter);

    // Retrieve TextView inputs from saved preferences
    if (prefs.contains("origin") && prefs.contains("destination")) {
        //state= originTextView,destinationTextView
        String origin = prefs.getString("origin", "");
        String destination = prefs.getString("destination", "");
        if (origin.compareTo("") != 0)
            originTextView.setThreshold(200); // disable auto-complete until new text entered
        if (destination.compareTo("") != 0)
            destinationTextView.setThreshold(200); // disable auto-complete until new text entered

        originTextView.setText(origin);
        destinationTextView.setText(destination);
        validateInputAndDoRequest();
    }

    // Retrieve station suggestions from file storage
    try {
        ArrayList<StationSuggestion> storedSuggestions = (ArrayList<StationSuggestion>) LocalPersistence
                .readObjectFromFile(c, res.getResourceEntryName(R.string.StationSuggestionFileName));
        // If stored StationSuggestions are found, apply them
        if (storedSuggestions != null) {
            stationSuggestions = storedSuggestions;
            Log.d("stationSuggestions", "Loaded");
        } else
            Log.d("stationSuggestions", "Not Found");

    } catch (Throwable t) {
        // don't sweat it
    }

    ImageButton map = (ImageButton) findViewById(R.id.map);
    map.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            Intent intent = new Intent(c, MapActivity.class);
            startActivity(intent);
        }

    });

    ImageButton reverse = (ImageButton) findViewById(R.id.reverse);
    reverse.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            Editable originTempText = originTextView.getText();
            originTextView.setText(destinationTextView.getText());
            destinationTextView.setText(originTempText);

            validateInputAndDoRequest();
        }
    });

    // Handles restoring TextView input when focus lost, if no new input entered
    // previous input is stored in the target View Tag attribute
    // Assumes the target view is a TextView
    // TODO:This works but starts autocomplete when the view loses focus after clicking outside the autocomplete listview
    OnFocusChangeListener inputOnFocusChangeListener = new OnFocusChangeListener() {
        @Override
        public void onFocusChange(View inputTextView, boolean hasFocus) {
            if (inputTextView.getTag(R.id.TextInputMemory) != null && !hasFocus
                    && ((TextView) inputTextView).getText().toString().compareTo("") == 0) {
                //Log.v("InputTextViewTagGet","orig: "+ inputTextView.getTag());
                ((TextView) inputTextView).setText(inputTextView.getTag(R.id.TextInputMemory).toString());
            }
        }
    };

    originTextView.setOnFocusChangeListener(inputOnFocusChangeListener);
    destinationTextView.setOnFocusChangeListener(inputOnFocusChangeListener);

    // When the TextView is clicked, store current text in TextView's Tag property, clear displayed text 
    // and enable Auto-Completing after first character entered
    OnTouchListener inputOnTouchListener = new OnTouchListener() {
        @Override
        public boolean onTouch(View inputTextView, MotionEvent me) {
            // Only perform this logic on finger-down
            if (me.getAction() == me.ACTION_DOWN) {
                inputTextView.setTag(R.id.TextInputMemory, ((TextView) inputTextView).getText().toString());
                Log.d("adapterSwitch", "suggestions");
                ((AutoCompleteTextView) inputTextView).setThreshold(1);
                ((TextView) inputTextView).setText("");

                // TESTING 
                // set tag to be retrieved on input entered to set adapter back to station list
                // The key of a tag must be a unique ID resource
                inputTextView.setTag(R.id.TextInputShowingSuggestions, "true");
                ArrayList<StationSuggestion> prunedSuggestions = new ArrayList<StationSuggestion>();
                // copy suggestions

                for (int x = 0; x < stationSuggestions.size(); x++) {
                    prunedSuggestions.add(stationSuggestions.get(x));
                }

                // Check for and remove other text input's value from stationSuggestions
                if (inputTextView.equals(findViewById(R.id.originTv))) {
                    // If the originTv is clicked, remove the destinationTv's value from prunedSuggestions
                    if (prunedSuggestions.contains(new StationSuggestion(
                            ((TextView) findViewById(R.id.destinationTv)).getText().toString(), "recent"))) {
                        prunedSuggestions.remove(new StationSuggestion(
                                ((TextView) findViewById(R.id.destinationTv)).getText().toString(), "recent"));
                    }
                } else if (inputTextView.equals(findViewById(R.id.destinationTv))) {
                    // If the originTv is clicked, remove the destinationTv's value from prunedSuggestions
                    if (prunedSuggestions.contains(new StationSuggestion(
                            ((TextView) findViewById(R.id.originTv)).getText().toString(), "recent"))) {
                        prunedSuggestions.remove(new StationSuggestion(
                                ((TextView) findViewById(R.id.originTv)).getText().toString(), "recent"));
                    }
                }

                //if(stationSuggestions.contains(new StationSuggestion(((TextView)inputTextView).getText().toString(),"recent")))

                // if available, add localStation to prunedSuggestions
                if (localStation.compareTo("") != 0) {
                    if (BART.REVERSE_STATION_MAP.get(localStation) != null) {
                        // If a valid localStation (based on DeviceLocation) is available: 
                        // remove localStations from recent suggestions (if it exists there)
                        // and add as nearby station
                        prunedSuggestions.remove(
                                new StationSuggestion(BART.REVERSE_STATION_MAP.get(localStation), "recent"));
                        prunedSuggestions.add(
                                new StationSuggestion(BART.REVERSE_STATION_MAP.get(localStation), "nearby"));
                    }
                }

                // TESTING: Set Custom ArrayAdapter to hold recent/nearby stations
                TextPlusIconArrayAdapter adapter = new TextPlusIconArrayAdapter(c, prunedSuggestions);
                ((AutoCompleteTextView) inputTextView).setAdapter(adapter);
                // force drop-down to appear, overriding requirement that at least one char is entered
                ((AutoCompleteTextView) inputTextView).showDropDown();

                // ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                // android.R.layout.simple_dropdown_item_1line, BART.STATIONS);
            }
            // Allow Android to handle additional actions - i.e: TextView takes focus
            return false;
        }
    };

    originTextView.setOnTouchListener(inputOnTouchListener);
    destinationTextView.setOnTouchListener(inputOnTouchListener);

    // Autocomplete ListView item select listener

    originTextView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View arg1, int position, long arg3) {
            Log.d("OriginTextView", "item clicked");
            AutoCompleteTextView originTextView = (AutoCompleteTextView) findViewById(R.id.originTv);
            originTextView.setThreshold(200);
            //hideSoftKeyboard(arg1);
            // calling hideSoftKeyboard with arg1 doesn't work with stationSuggestion adapter
            hideSoftKeyboard(findViewById(R.id.inputLinearLayout));

            // Add selected station to stationSuggestions ArrayList if it doesn't exist
            if (!stationSuggestions
                    .contains((new StationSuggestion(originTextView.getText().toString(), "recent")))) {
                stationSuggestions.add(0, new StationSuggestion(originTextView.getText().toString(), "recent"));
                // if the stationSuggestion arraylist is over the max size, remove the last item
                if (stationSuggestions.size() > STATION_SUGGESTION_SIZE) {
                    stationSuggestions.remove(stationSuggestions.size() - 1);
                }
            }
            // Else, increment click count for that recent
            else {
                stationSuggestions
                        .get(stationSuggestions.indexOf(
                                (new StationSuggestion(originTextView.getText().toString(), "recent"))))
                        .addHit();
            }
            validateInputAndDoRequest();

        }
    });

    destinationTextView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View arg1, int position, long arg3) {
            Log.d("DestinationTextView", "item clicked");

            // Actv not available as arg1
            AutoCompleteTextView destinationTextView = (AutoCompleteTextView) findViewById(R.id.destinationTv);
            destinationTextView.setThreshold(200);
            //hideSoftKeyboard(arg1);
            hideSoftKeyboard(findViewById(R.id.inputLinearLayout));

            // Add selected station to stationSuggestions set
            if (!stationSuggestions
                    .contains((new StationSuggestion(destinationTextView.getText().toString(), "recent")))) {
                Log.d("DestinationTextView", "adding station");
                stationSuggestions.add(0,
                        new StationSuggestion(destinationTextView.getText().toString(), "recent"));
                if (stationSuggestions.size() > STATION_SUGGESTION_SIZE) {
                    stationSuggestions.remove(stationSuggestions.size() - 1);
                }
            }
            // If station exists in StationSuggestions, increment hit
            else {
                stationSuggestions
                        .get(stationSuggestions.indexOf(
                                (new StationSuggestion(destinationTextView.getText().toString(), "recent"))))
                        .addHit();
                //Log.d("DestinationTextView",String.valueOf(stationSuggestions.get(stationSuggestions.indexOf((new StationSuggestion(destinationTextView.getText().toString(),"recent")))).hits));
            }

            //If a valid origin station is not entered, return
            if (BART.STATION_MAP.get(originTextView.getText().toString()) == null)
                return;
            validateInputAndDoRequest();
            //lastRequest = "etd";
            //String url = "http://api.bart.gov/api/etd.aspx?cmd=etd&orig="+originStation+"&key=MW9S-E7SL-26DU-VV8V";
            // TEMP: For testing route function
            //lastRequest = "route";
            //bartApiRequest();
        }
    });

    //OnKeyListener only gets physical device keyboard events (except the softkeyboard delete key. hmmm)
    originTextView.addTextChangedListener(new TextWatcher() {
        public void afterTextChanged(Editable s) {
            //Log.d("seachScreen", "afterTextChanged"); 
        }

        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            //Log.d("seachScreen", "beforeTextChanged"); 
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {

            ArrayAdapter<String> adapter = new ArrayAdapter<String>(c,
                    android.R.layout.simple_dropdown_item_1line, BART.STATIONS);
            if (((String) ((TextView) findViewById(R.id.originTv)).getTag(R.id.TextInputShowingSuggestions))
                    .compareTo("true") == 0) {
                ((TextView) findViewById(R.id.originTv)).setTag(R.id.TextInputShowingSuggestions, "false");
                ((AutoCompleteTextView) findViewById(R.id.originTv)).setAdapter(adapter);
            }

            Log.d("seachScreen", s.toString());
        }

    });
    destinationTextView.addTextChangedListener(new TextWatcher() {
        public void afterTextChanged(Editable s) {
            //Log.d("seachScreen", "afterTextChanged"); 
        }

        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            //Log.d("seachScreen", "beforeTextChanged"); 
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(c,
                    android.R.layout.simple_dropdown_item_1line, BART.STATIONS);
            if (((String) ((TextView) findViewById(R.id.destinationTv))
                    .getTag(R.id.TextInputShowingSuggestions)).compareTo("true") == 0) {
                ((TextView) findViewById(R.id.destinationTv)).setTag(R.id.TextInputShowingSuggestions, "false");
                ((AutoCompleteTextView) findViewById(R.id.destinationTv)).setAdapter(adapter);
            }
            Log.d("seachScreen", s.toString());
        }

    });

}

From source file:com.android.ex.chips.RecipientEditTextView.java

ArrayList<DrawableRecipientChip> handlePaste() {
    final String text = getText().toString();
    final int originalTokenStart = mTokenizer.findTokenStart(text, getSelectionEnd());
    final String lastAddress = text.substring(originalTokenStart);
    int tokenStart = originalTokenStart;
    int prevTokenStart = 0;
    DrawableRecipientChip findChip = null;
    final ArrayList<DrawableRecipientChip> created = new ArrayList<DrawableRecipientChip>();
    if (tokenStart != 0) {
        // There are things before this!
        while (tokenStart != 0 && findChip == null && tokenStart != prevTokenStart) {
            prevTokenStart = tokenStart;
            tokenStart = mTokenizer.findTokenStart(text, tokenStart);
            findChip = findChip(tokenStart);
            if (tokenStart == originalTokenStart && findChip == null)
                break;
        }//from  w  w  w  .  j  a  v  a 2 s.co  m
        if (tokenStart != originalTokenStart) {
            if (findChip != null)
                tokenStart = prevTokenStart;
            int tokenEnd;
            DrawableRecipientChip createdChip;
            while (tokenStart < originalTokenStart) {
                tokenEnd = movePastTerminators(mTokenizer.findTokenEnd(getText().toString(), tokenStart));
                commitChip(tokenStart, tokenEnd, getText());
                createdChip = findChip(tokenStart);
                if (createdChip == null)
                    break;
                // +1 for the space at the end.
                tokenStart = getSpannable().getSpanEnd(createdChip) + 1;
                created.add(createdChip);
            }
        }
    }
    // Take a look at the last token. If the token has been completed with a
    // commit character, create a chip.
    if (isCompletedToken(lastAddress)) {
        final Editable editable = getText();
        tokenStart = editable.toString().indexOf(lastAddress, originalTokenStart);
        commitChip(tokenStart, editable.length(), editable);
        created.add(findChip(tokenStart));
    }
    return created;
}

From source file:foam.starwisp.StarwispBuilder.java

public void Build(final StarwispActivity ctx, final String ctxname, JSONArray arr, ViewGroup parent) {

    if (StarwispLinearLayout.m_DisplayMetrics == null) {
        StarwispLinearLayout.m_DisplayMetrics = ctx.getResources().getDisplayMetrics();
    }/*from   w w  w. ja v  a2  s  . com*/

    try {
        String type = arr.getString(0);

        //Log.i("starwisp","building started "+type);

        if (type.equals("build-fragment")) {
            String name = arr.getString(1);
            int ID = arr.getInt(2);
            Fragment fragment = ActivityManager.GetFragment(name);
            LinearLayout inner = new LinearLayout(ctx);
            inner.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));
            inner.setId(ID);
            FragmentTransaction fragmentTransaction = ctx.getSupportFragmentManager().beginTransaction();
            fragmentTransaction.add(ID, fragment);
            fragmentTransaction.commit();
            parent.addView(inner);
            return;
        }

        if (type.equals("map")) {
            int ID = arr.getInt(1);
            LinearLayout inner = new LinearLayout(ctx);
            inner.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            inner.setId(ID);
            Fragment mapfrag = SupportMapFragment.newInstance();
            FragmentTransaction fragmentTransaction = ctx.getSupportFragmentManager().beginTransaction();
            fragmentTransaction.add(ID, mapfrag);
            fragmentTransaction.commit();
            parent.addView(inner);
            return;
        }

        if (type.equals("drawmap")) {
            final LinearLayout inner = new LinearLayout(ctx);
            inner.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            DrawableMap dm = new DrawableMap();
            dm.init(arr.getInt(1), inner, (StarwispActivity) ctx, this, arr.getString(3));
            parent.addView(inner);
            m_DMaps.put(arr.getInt(1), dm);
            return;
        }

        if (type.equals("linear-layout")) {
            StarwispLinearLayout.Build(this, ctx, ctxname, arr, parent);
            return;
        }

        if (type.equals("relative-layout")) {
            StarwispRelativeLayout.Build(this, ctx, ctxname, arr, parent);
            return;
        }

        if (type.equals("draggable")) {
            final LinearLayout v = new LinearLayout(ctx);
            final int id = arr.getInt(1);
            final String behaviour_type = arr.getString(5);
            v.setPadding(20, 20, 20, 10);
            v.setId(id);
            v.setOrientation(StarwispLinearLayout.BuildOrientation(arr.getString(2)));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));
            v.setClickable(true);
            v.setFocusable(true);

            JSONArray col = arr.getJSONArray(4);
            v.setBackgroundResource(R.drawable.draggable);

            GradientDrawable drawable = (GradientDrawable) v.getBackground();
            final int colour = Color.argb(col.getInt(3), col.getInt(0), col.getInt(1), col.getInt(2));
            drawable.setColor(colour);

            /*LayerDrawable bgDrawable = (LayerDrawable)v.getBackground();
            GradientDrawable bgShape = (GradientDrawable)bgDrawable.findDrawableByLayerId(R.id.draggableshape);
            bgShape.setColor(colour);*/
            /*v.getBackground().setColorFilter(colour, PorterDuff.Mode.MULTIPLY);*/

            parent.addView(v);
            JSONArray children = arr.getJSONArray(6);
            for (int i = 0; i < children.length(); i++) {
                Build(ctx, ctxname, new JSONArray(children.getString(i)), v);
            }

            // Sets a long click listener for the ImageView using an anonymous listener object that
            // implements the OnLongClickListener interface
            if (!behaviour_type.equals("drop-only") && !behaviour_type.equals("drop-only-consume")) {
                v.setOnLongClickListener(new View.OnLongClickListener() {
                    public boolean onLongClick(View vv) {
                        if (id != 99) {
                            ClipData dragData = new ClipData(
                                    new ClipDescription("" + id,
                                            new String[] { ClipDescription.MIMETYPE_TEXT_PLAIN }),
                                    new ClipData.Item("" + id));

                            View.DragShadowBuilder myShadow = new MyDragShadowBuilder(v);
                            Log.i("starwisp", "start drag id " + vv.getId() + " " + v);
                            v.startDrag(dragData, myShadow, v, 0);
                            v.setVisibility(View.GONE);
                            return true;
                        }
                        return false;
                    }
                });
            }

            if (!behaviour_type.equals("drag-only")) {
                // ye gads - needed as drag/drop doesn't deal with nested targets
                final StarwispBuilder that = this;

                v.setOnDragListener(new View.OnDragListener() {
                    public boolean onDrag(View vv, DragEvent event) {

                        //Log.i("starwisp","on drag event happened");

                        final int action = event.getAction();
                        switch (action) {
                        case DragEvent.ACTION_DRAG_STARTED:
                            //Log.i("starwisp","Drag started"+v );
                            if (event.getClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)) {
                                // returns true to indicate that the View can accept the dragged data.
                                return true;
                            } else {
                                // Returns false. During the current drag and drop operation, this View will
                                // not receive events again until ACTION_DRAG_ENDED is sent.
                                return false;
                            }
                        case DragEvent.ACTION_DRAG_ENTERED: {
                            if (that.m_LastDragHighlighted != null) {
                                that.m_LastDragHighlighted.getBackground().setColorFilter(null);
                            }
                            v.getBackground().setColorFilter(0x77777777, PorterDuff.Mode.MULTIPLY);
                            that.m_LastDragHighlighted = v;
                            //Log.i("starwisp","Drag entered"+v );
                            return true;
                        }
                        case DragEvent.ACTION_DRAG_LOCATION: {
                            //View dragee = (View)event.getLocalState();
                            //dragee.setVisibility(View.VISIBLE);
                            //Log.i("starwisp","Drag location"+v );
                            return true;
                        }
                        case DragEvent.ACTION_DRAG_EXITED: {
                            //Log.i("starwisp","Drag exited "+v );
                            v.getBackground().setColorFilter(null);
                            return true;
                        }
                        case DragEvent.ACTION_DROP: {
                            v.getBackground().setColorFilter(null);
                            //Log.i("starwisp","Drag dropped "+v );
                            View otherw = (View) event.getLocalState();
                            //Log.i("starwisp","removing from parent "+((View)otherw.getParent()).getId());

                            // check we are not adding to ourself
                            if (id != otherw.getId()) {
                                ((ViewManager) otherw.getParent()).removeView(otherw);
                                //Log.i("starwisp","adding to " + id);

                                if (!behaviour_type.equals("drop-only-consume")) {
                                    v.addView(otherw);
                                }
                            }
                            otherw.setVisibility(View.VISIBLE);
                            return true;
                        }
                        case DragEvent.ACTION_DRAG_ENDED: {
                            //Log.i("starwisp","Drag ended "+v );
                            v.getBackground().setColorFilter(null);

                            View dragee = (View) event.getLocalState();
                            dragee.setVisibility(View.VISIBLE);

                            if (event.getResult()) {
                                //Log.i("starwisp","sucess " );
                            } else {
                                //Log.i("starwisp","fail " );
                            }
                            ;
                            return true;
                        }
                        // An unknown action type was received.
                        default:
                            //Log.e("starwisp","Unknown action type received by OnDragListener.");
                            break;
                        }
                        ;
                        return true;
                    }
                });
                return;
            }
        }

        if (type.equals("frame-layout")) {
            FrameLayout v = new FrameLayout(ctx);
            v.setId(arr.getInt(1));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            parent.addView(v);
            JSONArray children = arr.getJSONArray(3);
            for (int i = 0; i < children.length(); i++) {
                Build(ctx, ctxname, new JSONArray(children.getString(i)), v);
            }
            return;
        }

        /*
        if (type.equals("grid-layout")) {
        GridLayout v = new GridLayout(ctx);
        v.setId(arr.getInt(1));
        v.setRowCount(arr.getInt(2));
        //v.setColumnCount(arr.getInt(2));
        v.setOrientation(BuildOrientation(arr.getString(3)));
        v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4)));
                
        parent.addView(v);
        JSONArray children = arr.getJSONArray(5);
        for (int i=0; i<children.length(); i++) {
            Build(ctx,ctxname,new JSONArray(children.getString(i)), v);
        }
                
        return;
        }
        */

        if (type.equals("scroll-view")) {
            HorizontalScrollView v = new HorizontalScrollView(ctx);
            v.setId(arr.getInt(1));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            parent.addView(v);
            JSONArray children = arr.getJSONArray(3);
            for (int i = 0; i < children.length(); i++) {
                Build(ctx, ctxname, new JSONArray(children.getString(i)), v);
            }
            return;
        }

        if (type.equals("scroll-view-vert")) {
            ScrollView v = new ScrollView(ctx);
            v.setId(arr.getInt(1));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            parent.addView(v);
            JSONArray children = arr.getJSONArray(3);
            for (int i = 0; i < children.length(); i++) {
                Build(ctx, ctxname, new JSONArray(children.getString(i)), v);
            }
            return;
        }

        if (type.equals("view-pager")) {
            ViewPager v = new ViewPager(ctx);
            v.setId(arr.getInt(1));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            v.setOffscreenPageLimit(3);
            final JSONArray items = arr.getJSONArray(3);

            v.setAdapter(new FragmentPagerAdapter(ctx.getSupportFragmentManager()) {

                @Override
                public int getCount() {
                    return items.length();
                }

                @Override
                public Fragment getItem(int position) {
                    try {
                        String fragname = items.getString(position);
                        return ActivityManager.GetFragment(fragname);
                    } catch (JSONException e) {
                        Log.e("starwisp", "Error parsing fragment data " + e.toString());
                    }
                    return null;
                }
            });
            parent.addView(v);
            return;
        }

        if (type.equals("space")) {
            // Space v = new Space(ctx); (class not found runtime error??)
            TextView v = new TextView(ctx);
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            parent.addView(v);
        }

        if (type.equals("image-view")) {
            ImageView v = new ImageView(ctx);
            v.setId(arr.getInt(1));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));
            v.setAdjustViewBounds(true);

            String image = arr.getString(2);

            if (image.startsWith("/")) {
                Bitmap b = BitmapCache.Load(image);
                if (b != null) {
                    v.setImageBitmap(b);
                }
            } else {
                int id = ctx.getResources().getIdentifier(image, "drawable", ctx.getPackageName());
                v.setImageResource(id);
            }

            parent.addView(v);
        }

        if (type.equals("image-button")) {
            ImageButton v = new ImageButton(ctx);
            v.setId(arr.getInt(1));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));

            String image = arr.getString(2);

            if (image.startsWith("/")) {
                v.setImageBitmap(BitmapCache.Load(image));
            } else {
                int id = ctx.getResources().getIdentifier(image, "drawable", ctx.getPackageName());
                v.setImageResource(id);
            }

            final String fn = arr.getString(4);
            v.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    Callback(ctx, ctxname, v.getId());
                }
            });

            v.setAdjustViewBounds(true);
            v.setScaleType(ImageView.ScaleType.CENTER_INSIDE);

            parent.addView(v);
        }

        if (type.equals("text-view")) {
            TextView v = new TextView(ctx);
            v.setId(arr.getInt(1));
            v.setText(Html.fromHtml(arr.getString(2)), BufferType.SPANNABLE);
            v.setTextSize(arr.getInt(3));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4)));
            v.setLinkTextColor(0xff00aa00);

            // uncomment all this to get hyperlinks to work in text...
            // should make this an option of course

            //v.setClickable(true); // make links
            //v.setMovementMethod(LinkMovementMethod.getInstance());
            //v.setEnabled(true);   // go to browser
            /*v.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(View vv, MotionEvent event) {
                return false;
            }
            };*/

            if (arr.length() > 5) {
                if (arr.getString(5).equals("left")) {
                    v.setGravity(Gravity.LEFT);
                } else {
                    if (arr.getString(5).equals("fill")) {
                        v.setGravity(Gravity.FILL);
                    } else {
                        v.setGravity(Gravity.CENTER);
                    }
                }
            } else {
                v.setGravity(Gravity.CENTER);
            }
            v.setTypeface(((StarwispActivity) ctx).m_Typeface);
            parent.addView(v);
        }

        if (type.equals("debug-text-view")) {
            TextView v = (TextView) ctx.getLayoutInflater().inflate(R.layout.debug_text, null);
            //                v.setBackgroundResource(R.color.black);
            v.setId(arr.getInt(1));
            //                v.setText(Html.fromHtml(arr.getString(2)));
            //                v.setTextColor(R.color.white);
            //                v.setTextSize(arr.getInt(3));
            //                v.setMovementMethod(LinkMovementMethod.getInstance());
            //                v.setMaxLines(10);
            //                v.setVerticalScrollBarEnabled(true);
            //                v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4)));
            //v.setMovementMethod(new ScrollingMovementMethod());

            /*
            if (arr.length()>5) {
            if (arr.getString(5).equals("left")) {
                v.setGravity(Gravity.LEFT);
            } else {
                if (arr.getString(5).equals("fill")) {
                    v.setGravity(Gravity.FILL);
                } else {
                    v.setGravity(Gravity.CENTER);
                }
            }
            } else {
            v.setGravity(Gravity.LEFT);
            }
            v.setTypeface(((StarwispActivity)ctx).m_Typeface);*/
            parent.addView(v);
        }

        if (type.equals("web-view")) {
            WebView v = new WebView(ctx);
            v.setId(arr.getInt(1));
            v.setVerticalScrollBarEnabled(false);
            v.loadData(arr.getString(2), "text/html", "utf-8");
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));
            parent.addView(v);
        }

        if (type.equals("edit-text")) {
            final EditText v = new EditText(ctx);
            v.setId(arr.getInt(1));
            v.setText(arr.getString(2));
            v.setTextSize(arr.getInt(3));
            v.setGravity(Gravity.LEFT | Gravity.TOP);

            String inputtype = arr.getString(4);
            if (inputtype.equals("text")) {
                //v.setInputType(InputType.TYPE_CLASS_TEXT);
            } else if (inputtype.equals("numeric")) {
                v.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL
                        | InputType.TYPE_NUMBER_FLAG_SIGNED);
            } else if (inputtype.equals("email")) {
                v.setInputType(InputType.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS);
            }

            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(5)));
            v.setTypeface(((StarwispActivity) ctx).m_Typeface);
            final String fn = arr.getString(5);
            //v.setSingleLine(true);

            v.addTextChangedListener(new TextWatcher() {
                public void afterTextChanged(Editable s) {
                    CallbackArgs(ctx, ctxname, v.getId(), "\"" + s.toString() + "\"");
                }

                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }

                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }
            });

            parent.addView(v);
        }

        if (type.equals("button")) {
            Button v = new Button(ctx);
            v.setId(arr.getInt(1));
            v.setText(arr.getString(2));
            v.setTextSize(arr.getInt(3));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4)));
            v.setTypeface(((StarwispActivity) ctx).m_Typeface);
            final String fn = arr.getString(5);
            v.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    Callback(ctx, ctxname, v.getId());
                }
            });

            parent.addView(v);
        }

        if (type.equals("colour-button")) {
            Button v = new Button(ctx);
            v.setId(arr.getInt(1));
            v.setText(arr.getString(2));
            v.setTextSize(arr.getInt(3));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4)));
            v.setTypeface(((StarwispActivity) ctx).m_Typeface);
            JSONArray col = arr.getJSONArray(6);
            v.getBackground().setColorFilter(
                    Color.argb(col.getInt(3), col.getInt(0), col.getInt(1), col.getInt(2)),
                    PorterDuff.Mode.MULTIPLY);
            final String fn = arr.getString(5);
            v.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    Callback(ctx, ctxname, v.getId());
                }
            });
            parent.addView(v);
        }

        if (type.equals("toggle-button")) {
            ToggleButton v = new ToggleButton(ctx);
            if (arr.getString(5).equals("fancy")) {
                v = (ToggleButton) ctx.getLayoutInflater().inflate(R.layout.toggle_button_fancy, null);
            }

            if (arr.getString(5).equals("yes")) {
                v = (ToggleButton) ctx.getLayoutInflater().inflate(R.layout.toggle_button_yes, null);
            }

            if (arr.getString(5).equals("maybe")) {
                v = (ToggleButton) ctx.getLayoutInflater().inflate(R.layout.toggle_button_maybe, null);
            }

            if (arr.getString(5).equals("no")) {
                v = (ToggleButton) ctx.getLayoutInflater().inflate(R.layout.toggle_button_no, null);
            }

            v.setId(arr.getInt(1));
            v.setText(arr.getString(2));
            v.setTextSize(arr.getInt(3));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4)));
            v.setTypeface(((StarwispActivity) ctx).m_Typeface);
            final String fn = arr.getString(6);
            v.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    String arg = "#f";
                    if (((ToggleButton) v).isChecked())
                        arg = "#t";
                    CallbackArgs(ctx, ctxname, v.getId(), arg);
                }
            });
            parent.addView(v);
        }

        if (type.equals("seek-bar")) {
            SeekBar v = new SeekBar(ctx);
            v.setId(arr.getInt(1));
            v.setMax(arr.getInt(2));
            v.setProgress(arr.getInt(2) / 2);
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));
            final String fn = arr.getString(4);

            v.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                public void onProgressChanged(SeekBar v, int a, boolean s) {
                    CallbackArgs(ctx, ctxname, v.getId(), Integer.toString(a));
                }

                public void onStartTrackingTouch(SeekBar v) {
                }

                public void onStopTrackingTouch(SeekBar v) {
                }
            });
            parent.addView(v);
        }

        if (type.equals("spinner")) {
            Spinner v = new Spinner(ctx);
            final int wid = arr.getInt(1);
            v.setId(wid);
            final JSONArray items = arr.getJSONArray(2);
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));
            v.setMinimumWidth(100); // stops tiny buttons
            ArrayList<String> spinnerArray = new ArrayList<String>();

            for (int i = 0; i < items.length(); i++) {
                spinnerArray.add(items.getString(i));
            }

            ArrayAdapter spinnerArrayAdapter = new ArrayAdapter<String>(ctx, R.layout.spinner_item,
                    spinnerArray) {
                public View getView(int position, View convertView, ViewGroup parent) {
                    View v = super.getView(position, convertView, parent);
                    ((TextView) v).setTypeface(((StarwispActivity) ctx).m_Typeface);
                    return v;
                }
            };

            spinnerArrayAdapter.setDropDownViewResource(R.layout.spinner_layout);

            v.setAdapter(spinnerArrayAdapter);
            v.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                public void onItemSelected(AdapterView<?> a, View v, int pos, long id) {
                    CallbackArgs(ctx, ctxname, wid, "" + pos);
                }

                public void onNothingSelected(AdapterView<?> v) {
                }
            });

            parent.addView(v);
        }

        if (type.equals("nomadic")) {
            final int wid = arr.getInt(1);
            NomadicSurfaceView v = new NomadicSurfaceView(ctx, wid);
            v.setId(wid);
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            Log.e("starwisp", "built the thing");
            parent.addView(v);
            Log.e("starwisp", "addit to the view");
        }

        if (type.equals("canvas")) {
            StarwispCanvas v = new StarwispCanvas(ctx);
            final int wid = arr.getInt(1);
            v.setId(wid);
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            v.SetDrawList(arr.getJSONArray(3));
            parent.addView(v);
        }

        if (type.equals("camera-preview")) {
            PictureTaker pt = new PictureTaker();
            CameraPreview v = new CameraPreview(ctx, pt);
            final int wid = arr.getInt(1);
            v.setId(wid);
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            parent.addView(v);

            Log.i("starwisp", "in camera-preview...");

            List<List<String>> info = v.mPictureTaker.GetInfo();
            // can't find a way to do this via a callback yet
            String arg = "'(";
            for (List<String> e : info) {
                arg += "(" + e.get(0) + " " + e.get(1) + ")";
                //Log.i("starwisp","converting prop "+arg);
            }
            arg += ")";
            m_Scheme.eval("(set! camera-properties " + arg + ")");
        }

        if (type.equals("button-grid")) {
            LinearLayout horiz = new LinearLayout(ctx);
            final int id = arr.getInt(1);
            final String buttontype = arr.getString(2);
            horiz.setId(id);
            horiz.setOrientation(LinearLayout.HORIZONTAL);
            parent.addView(horiz);
            int height = arr.getInt(3);
            int textsize = arr.getInt(4);
            LayoutParams lp = BuildLayoutParams(arr.getJSONArray(5));
            JSONArray buttons = arr.getJSONArray(6);
            int count = buttons.length();
            int vertcount = 0;
            LinearLayout vert = null;

            for (int i = 0; i < count; i++) {
                JSONArray button = buttons.getJSONArray(i);

                if (vertcount == 0) {
                    vert = new LinearLayout(ctx);
                    vert.setId(0);
                    vert.setOrientation(LinearLayout.VERTICAL);
                    horiz.addView(vert);
                }
                vertcount = (vertcount + 1) % height;

                if (buttontype.equals("button")) {
                    Button b = new Button(ctx);
                    b.setId(button.getInt(0));
                    b.setText(button.getString(1));
                    b.setTextSize(textsize);
                    b.setLayoutParams(lp);
                    b.setTypeface(((StarwispActivity) ctx).m_Typeface);
                    final String fn = arr.getString(6);
                    b.setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                            CallbackArgs(ctx, ctxname, id, "" + v.getId() + " #t");
                        }
                    });
                    vert.addView(b);
                } else if (buttontype.equals("toggle")) {
                    ToggleButton b = new ToggleButton(ctx);
                    b.setId(button.getInt(0));
                    b.setText(button.getString(1));
                    b.setTextSize(textsize);
                    b.setLayoutParams(lp);
                    b.setTypeface(((StarwispActivity) ctx).m_Typeface);
                    final String fn = arr.getString(6);
                    b.setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                            String arg = "#f";
                            if (((ToggleButton) v).isChecked())
                                arg = "#t";
                            CallbackArgs(ctx, ctxname, id, "" + v.getId() + " " + arg);
                        }
                    });
                    vert.addView(b);
                }
            }
        }

    } catch (JSONException e) {
        Log.e("starwisp", "Error parsing [" + arr.toString() + "] " + e.toString());
    }

    //Log.i("starwisp","building ended");

}