Example usage for android.app TimePickerDialog show

List of usage examples for android.app TimePickerDialog show

Introduction

In this page you can find the example usage for android.app TimePickerDialog show.

Prototype

@Override
    public void show() 

Source Link

Usage

From source file:com.rsmsa.accapp.MainActivity.java

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

    // enable ActionBar app icon to behave as action to toggle nav drawer
    getActionBar().setDisplayHomeAsUpEnabled(true);
    getActionBar().setHomeButtonEnabled(true);

    mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);

    gridView = (ListView) findViewById(R.id.headergridview);

    /**/*  w  w  w.  j  a  v  a 2  s.c  o  m*/
     * Temporary header
     */

    if (!hasheader) {
        tempHeader = (View) getLayoutInflater().inflate(R.layout.temp, null);
        gridView.addHeaderView(tempHeader);
        gridView.setAdapter(new gridViewAdapter(MainActivity.this));
        hasheader = true;
        tempFlag = true;

    }

    imgPreview = (ImageView) tempHeader.findViewById(R.id.imgPreview);
    videoPreview = (VideoView) tempHeader.findViewById(R.id.videoPreview);
    btnCapturePicture = (ImageButton) tempHeader.findViewById(R.id.btnCapturePicture);
    btnRecordVideo = (ImageButton) tempHeader.findViewById(R.id.btnCaptureVideo);
    /**
     * Capture image button click event
     */
    btnCapturePicture.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // capture picture
            captureImage();
        }
    });

    /**
     * Record video button click event
     */
    btnRecordVideo.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // record video
            recordVideo();
        }
    });

    // Checking camera availability
    if (!isDeviceSupportCamera()) {
        Toast.makeText(getApplicationContext(), "Sorry! Your device doesn't support camera", Toast.LENGTH_LONG)
                .show();
        // will close the app if the device does't have camera
        finish();
    }

    //get GPS location

    SetLocation = (Button) tempHeader.findViewById(R.id.btnLoc);

    SetLocation.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // create class object
            gps = new GPSTracker(MainActivity.this);

            // check if GPS enabled
            if (gps.canGetLocation()) {

                double latitude = gps.getLatitude();
                double longitude = gps.getLongitude();

                //location text view
                TextView location = (TextView) tempHeader.findViewById(R.id.loc);

                location.setText("Lat: " + latitude + "Long: " + longitude);

            } else {
                // can't get location
                // GPS or Network is not enabled
                // Ask user to enable GPS/network in settings
                gps.showSettingsAlert();
            }

        }
    });

    /**
     * header instance
     */
    header = (View) getLayoutInflater().inflate(R.layout.activity_accident, null);
    /**
     * Defining all layout items
     **/
    inputReg = (EditText) header.findViewById(R.id.reg_ref);

    inputFatal = (EditText) header.findViewById(R.id.fatal_edit);

    inputInjuries = (EditText) header.findViewById(R.id.injury_edit);

    inputSimple = (EditText) header.findViewById(R.id.simple_edit);

    damage = (EditText) header.findViewById(R.id.not_injured_edit);

    area_name = (EditText) header.findViewById(R.id.name);

    district = (EditText) header.findViewById(R.id.district);

    region = (EditText) header.findViewById(R.id.city);

    road_name = (EditText) header.findViewById(R.id.road_name);

    road_no = (EditText) header.findViewById(R.id.road_number);

    road_mark = (EditText) header.findViewById(R.id.road_mark);

    intersection_name = (EditText) header.findViewById(R.id.intersection_name);

    intersection_no = (EditText) header.findViewById(R.id.intersection_number);

    intersection_mark = (EditText) header.findViewById(R.id.intersection_mark);

    mDate = (EditText) header.findViewById(R.id.date);

    mTime = (EditText) header.findViewById(R.id.time);

    //Textchanges

    inputReg.addTextChangedListener(new EditTextWatcher(inputReg));

    inputFatal.addTextChangedListener(new EditTextWatcher(inputFatal));
    inputInjuries.addTextChangedListener(new EditTextWatcher(inputInjuries));
    inputSimple.addTextChangedListener(new EditTextWatcher(inputSimple));
    damage.addTextChangedListener(new EditTextWatcher(damage));

    area_name.addTextChangedListener(new EditTextWatcher(area_name));
    district.addTextChangedListener(new EditTextWatcher(district));
    region.addTextChangedListener(new EditTextWatcher(region));

    mDate.addTextChangedListener(new EditTextWatcher(mDate));
    mTime.addTextChangedListener(new EditTextWatcher(mTime));

    road_name.addTextChangedListener(new EditTextWatcher(road_name));
    road_no.addTextChangedListener(new EditTextWatcher(road_no));
    road_mark.addTextChangedListener(new EditTextWatcher(road_mark));
    intersection_name.addTextChangedListener(new EditTextWatcher(intersection_name));
    intersection_no.addTextChangedListener(new EditTextWatcher(intersection_no));
    intersection_mark.addTextChangedListener(new EditTextWatcher(intersection_mark));

    cal = Calendar.getInstance();

    day = cal.get(Calendar.DAY_OF_MONTH);

    month = cal.get(Calendar.MONTH);

    year = cal.get(Calendar.YEAR);

    hour = cal.get(Calendar.HOUR_OF_DAY);

    min = cal.get(Calendar.MINUTE);

    datePicker = (Button) header.findViewById(R.id.date_picker);
    datePicker.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            DatePickerDialog datePickerDialog = new DatePickerDialog(MainActivity.this, datePickerListener,
                    year, month, day);
            datePickerDialog.show();

        }
    });

    timePicker = (Button) header.findViewById(R.id.time_picker);
    timePicker.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            TimePickerDialog timePickerDialog = new TimePickerDialog(MainActivity.this, timePickerListener,
                    hour, min, true);
            timePickerDialog.show();
        }
    });

    // set a custom shadow that overlays the main content when the drawer
    // opens
    mDrawer.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);

    _initMenu();

    mDrawerToggle = new CustomActionBarDrawerToggle(this, mDrawer);

    nextButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent passenger = new Intent(MainActivity.this, Passenger.class);
            startActivity(passenger);
        }
    });
    mDrawer.setDrawerListener(mDrawerToggle);

    /**
     * instantiate ViewPager
     */
    mPager = (AutoScrollViewPager) header.findViewById(R.id.pager);
    mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
    mPager.setPageTransformer(true, new DepthPageTransformer());
    mPager.setAdapter(mPagerAdapter);

    PageListener pageListener = new PageListener();
    mPager.setOnPageChangeListener(pageListener);

}

From source file:shetye.prathamesh.notifyme.Utilities.java

public void createWhenDialog(final Context context, final Activity parentActivity, final Notif note,
        final boolean back) {
    mDialog = new Dialog(context);
    mDialog.setContentView(R.layout.datetimepicker_dialog);
    mDialog.setTitle("When to Notify??");
    mDialogOKBtn = (Button) mDialog.findViewById(R.id.btn_ok);
    mDialogOKBtn.setOnClickListener(new View.OnClickListener() {
        @Override// w  w w .j a v a 2s  . c  om
        public void onClick(View v) {
            note.setNotification_when(getSelectedTime());
            DatabaseHelper.getInstance(context).addNotif(note);
            setZoneInTimer(context, note);
            mDialog.dismiss();
            if (parentActivity != null) {
                if (back) {
                    parentActivity.finishAfterTransition();
                } else {
                    ((Notifications) parentActivity).refreshNotifications();
                }
            }
        }
    });
    mDialogOKBtn.setEnabled(false);
    mDialogCancelBtn = (Button) mDialog.findViewById(R.id.btn_cancel);
    mDialogCancelBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mDialog.dismiss();
            if (parentActivity != null) {
                parentActivity.finishAfterTransition();
            }
        }
    });
    mTimeBtn = (Button) mDialog.findViewById(R.id.btntimeset);
    mDateBtn = (Button) mDialog.findViewById(R.id.btndateset);
    final Time dtNow = new Time();
    dtNow.setToNow();
    mSelectedHours = dtNow.hour;
    mSelectedMinutes = dtNow.minute;
    mSelectedYear = dtNow.year;
    mSelectedMonth = dtNow.month;
    mSelectedDay = dtNow.monthDay;
    updateBtnText(dtNow, false, context);
    Time selectedTime = new Time();
    selectedTime.set(0, mSelectedMinutes, mSelectedHours, mSelectedDay, mSelectedMonth, mSelectedYear);
    mPastDateSelected = true;
    mTimeBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            TimePickerDialog timePickerDialog = new TimePickerDialog(context,
                    new TimePickerDialog.OnTimeSetListener() {
                        @Override
                        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                            Time selectedTime = new Time();
                            mSelectedHours = hourOfDay;
                            mSelectedMinutes = minute;
                            selectedTime.set(0, mSelectedMinutes, mSelectedHours, mSelectedDay, mSelectedMonth,
                                    mSelectedYear);
                            if (Time.compare(selectedTime, dtNow) <= 0) {
                                mPastDateSelected = true;
                            } else {
                                mPastDateSelected = false;
                            }
                            updateBtnText(selectedTime, true, context);
                        }
                    }, mSelectedHours, mSelectedMinutes, false);
            timePickerDialog.show();
        }
    });
    mDateBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            DatePickerDialog datePickerDialog = new DatePickerDialog(context,
                    new DatePickerDialog.OnDateSetListener() {
                        @Override
                        public void onDateSet(DatePicker view, int yy, int mm, int dd) {
                            Time selectedTime = new Time();
                            mSelectedYear = yy;
                            mSelectedMonth = mm;
                            mSelectedDay = dd;
                            selectedTime.set(0, mSelectedMinutes, mSelectedHours, mSelectedDay, mSelectedMonth,
                                    mSelectedYear);
                            if (Time.compare(selectedTime, dtNow) <= 0) {
                                mPastDateSelected = true;
                            } else {
                                mPastDateSelected = false;
                            }
                            updateBtnText(selectedTime, false, context);
                        }
                    }, mSelectedYear, mSelectedMonth, mSelectedDay);
            datePickerDialog.show();
        }
    });
    mDialog.show();
}

From source file:za.co.neilson.alarm.preferences.AlarmPreferencesActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // requestWindowFeature(Window.FEATURE_NO_TITLE);
    ActionBar actionBar = getSupportActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);
    setContentView(R.layout.alarm_preferences);

    pref = getSharedPreferences("AppPref", MODE_PRIVATE);
    email = getIntent().getStringExtra("email");
    Log.d("? ???!!! ", "" + email);

    Bundle bundle = getIntent().getExtras();
    if (bundle != null && bundle.containsKey("alarm")) {
        setMathAlarm((Alarm) bundle.getSerializable("alarm"));
    } else {/*from   w  ww .  j a  va 2s  .  c  o m*/
        setMathAlarm(new Alarm());
    }
    if (bundle != null && bundle.containsKey("adapter")) {
        setListAdapter((AlarmPreferenceListAdapter) bundle.getSerializable("adapter"));
    } else {
        setListAdapter(new AlarmPreferenceListAdapter(this, getMathAlarm()));
    }

    getListView().setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> l, View v, int position, long id) {
            final AlarmPreferenceListAdapter alarmPreferenceListAdapter = (AlarmPreferenceListAdapter) getListAdapter();
            final AlarmPreference alarmPreference = (AlarmPreference) alarmPreferenceListAdapter
                    .getItem(position);

            AlertDialog.Builder alert;
            v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
            switch (alarmPreference.getType()) {
            case BOOLEAN:
                CheckedTextView checkedTextView = (CheckedTextView) v;
                boolean checked = !checkedTextView.isChecked();
                ((CheckedTextView) v).setChecked(checked);
                switch (alarmPreference.getKey()) {
                case ALARM_ACTIVE:
                    alarm.setAlarmActive(checked);
                    break;
                case ALARM_VIBRATE:
                    alarm.setVibrate(checked);
                    if (checked) {
                        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
                        vibrator.vibrate(1000);
                    }
                    break;
                }
                alarmPreference.setValue(checked);
                break;
            case STRING:

                alert = new AlertDialog.Builder(AlarmPreferencesActivity.this);

                alert.setTitle(alarmPreference.getTitle());
                // alert.setMessage(message);

                // Set an EditText view to get user input
                final EditText input = new EditText(AlarmPreferencesActivity.this);

                input.setText(alarmPreference.getValue().toString());

                alert.setView(input);
                alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        alarmPreference.setValue(input.getText().toString());

                        if (alarmPreference.getKey() == Key.ALARM_NAME) {
                            alarm.setAlarmName(alarmPreference.getValue().toString());
                        }

                        alarmPreferenceListAdapter.setMathAlarm(getMathAlarm());
                        alarmPreferenceListAdapter.notifyDataSetChanged();
                    }
                });
                alert.show();
                break;
            case LIST:
                alert = new AlertDialog.Builder(AlarmPreferencesActivity.this);

                alert.setTitle(alarmPreference.getTitle());
                // alert.setMessage(message);

                CharSequence[] items = new CharSequence[alarmPreference.getOptions().length];
                for (int i = 0; i < items.length; i++)
                    items[i] = alarmPreference.getOptions()[i];

                alert.setItems(items, new OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (alarmPreference.getKey()) {
                        case ALARM_DIFFICULTY:
                            Alarm.Difficulty d = Alarm.Difficulty.values()[which];
                            alarm.setDifficulty(d);
                            break;
                        case ALARM_TONE:
                            alarm.setAlarmTonePath(alarmPreferenceListAdapter.getAlarmTonePaths()[which]);
                            if (alarm.getAlarmTonePath() != null) {
                                if (mediaPlayer == null) {
                                    mediaPlayer = new MediaPlayer();
                                } else {
                                    if (mediaPlayer.isPlaying())
                                        mediaPlayer.stop();
                                    mediaPlayer.reset();
                                }
                                try {
                                    // mediaPlayer.setVolume(1.0f, 1.0f);
                                    mediaPlayer.setVolume(0.2f, 0.2f);
                                    mediaPlayer.setDataSource(AlarmPreferencesActivity.this,
                                            Uri.parse(alarm.getAlarmTonePath()));
                                    mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
                                    mediaPlayer.setLooping(false);
                                    mediaPlayer.prepare();
                                    mediaPlayer.start();

                                    // Force the mediaPlayer to stop after 3
                                    // seconds...
                                    if (alarmToneTimer != null)
                                        alarmToneTimer.cancel();
                                    alarmToneTimer = new CountDownTimer(3000, 3000) {
                                        @Override
                                        public void onTick(long millisUntilFinished) {

                                        }

                                        @Override
                                        public void onFinish() {
                                            try {
                                                if (mediaPlayer.isPlaying())
                                                    mediaPlayer.stop();
                                            } catch (Exception e) {

                                            }
                                        }
                                    };
                                    alarmToneTimer.start();
                                } catch (Exception e) {
                                    try {
                                        if (mediaPlayer.isPlaying())
                                            mediaPlayer.stop();
                                    } catch (Exception e2) {

                                    }
                                }
                            }
                            break;
                        default:
                            break;
                        }
                        alarmPreferenceListAdapter.setMathAlarm(getMathAlarm());
                        alarmPreferenceListAdapter.notifyDataSetChanged();
                    }

                });

                alert.show();
                break;
            case MULTIPLE_LIST:
                alert = new AlertDialog.Builder(AlarmPreferencesActivity.this);

                alert.setTitle(alarmPreference.getTitle());
                // alert.setMessage(message);

                CharSequence[] multiListItems = new CharSequence[alarmPreference.getOptions().length];
                for (int i = 0; i < multiListItems.length; i++)
                    multiListItems[i] = alarmPreference.getOptions()[i];

                boolean[] checkedItems = new boolean[multiListItems.length];
                for (Alarm.Day day : getMathAlarm().getDays()) {
                    checkedItems[day.ordinal()] = true;
                }
                alert.setMultiChoiceItems(multiListItems, checkedItems, new OnMultiChoiceClickListener() {

                    @Override
                    public void onClick(final DialogInterface dialog, int which, boolean isChecked) {

                        Alarm.Day thisDay = Alarm.Day.values()[which];

                        if (isChecked) {
                            alarm.addDay(thisDay);
                        } else {
                            // Only remove the day if there are more than 1
                            // selected
                            if (alarm.getDays().length > 1) {
                                alarm.removeDay(thisDay);
                            } else {
                                // If the last day was unchecked, re-check
                                // it
                                ((AlertDialog) dialog).getListView().setItemChecked(which, true);
                            }
                        }

                    }
                });
                alert.setOnCancelListener(new OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        alarmPreferenceListAdapter.setMathAlarm(getMathAlarm());
                        alarmPreferenceListAdapter.notifyDataSetChanged();

                    }
                });
                alert.show();
                break;
            case TIME:
                TimePickerDialog timePickerDialog = new TimePickerDialog(AlarmPreferencesActivity.this,
                        new OnTimeSetListener() {

                            @Override
                            public void onTimeSet(TimePicker timePicker, int hours, int minutes) {
                                Calendar newAlarmTime = Calendar.getInstance();
                                newAlarmTime.set(Calendar.HOUR_OF_DAY, hours);
                                newAlarmTime.set(Calendar.MINUTE, minutes);
                                newAlarmTime.set(Calendar.SECOND, 0);
                                alarm.setAlarmTime(newAlarmTime);
                                alarmPreferenceListAdapter.setMathAlarm(getMathAlarm());
                                alarmPreferenceListAdapter.notifyDataSetChanged();
                            }
                        }, alarm.getAlarmTime().get(Calendar.HOUR_OF_DAY),
                        alarm.getAlarmTime().get(Calendar.MINUTE), true);
                timePickerDialog.setTitle(alarmPreference.getTitle());
                timePickerDialog.show();
            default:
                break;
            }
        }
    });
}

From source file:com.karmick.android.citizenalert.alarm.AlarmAddActivity.java

protected void eventCalls() {
    alarm_add.setOnClickListener(new OnClickListener() {

        @Override/*from  w  w  w.ja v a2  s.c  o  m*/
        public void onClick(View v) {

            validateAndSaveAlarm();
        }
    });

    alarm_contacts_add.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            Intent nint = new Intent(AlarmAddActivity.this, ContactListActivity.class);
            nint.putExtra("for_result", true);
            startActivityForResult(nint, GETCONTACTS);

        }
    });

    alarm_time.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            TimePickerDialog timePickerDialog = new TimePickerDialog(AlarmAddActivity.this,
                    new OnTimeSetListener() {

                        @Override
                        public void onTimeSet(TimePicker timePicker, int hours, int minutes) {
                            newAlarmTime.set(Calendar.HOUR_OF_DAY, hours);
                            newAlarmTime.set(Calendar.MINUTE, minutes);
                            newAlarmTime.set(Calendar.SECOND, 0);

                            newAlarmTime2.set(Calendar.HOUR_OF_DAY, hours);
                            newAlarmTime2.set(Calendar.MINUTE, minutes);
                            newAlarmTime2.set(Calendar.SECOND, 0);

                            newAlarmTime3.set(Calendar.HOUR_OF_DAY, hours);
                            newAlarmTime3.set(Calendar.MINUTE, minutes);
                            newAlarmTime3.set(Calendar.SECOND, 0);

                            alarm_time.setText(getAlarmTimeAsString(newAlarmTime));

                        }
                    }, alarm.getAlarmTime().get(Calendar.HOUR_OF_DAY),
                    alarm.getAlarmTime().get(Calendar.MINUTE), true);
            timePickerDialog.setTitle("SetTime");
            timePickerDialog.show();
        }
    });
}

From source file:foam.jellyfish.StarwispBuilder.java

public void Update(final StarwispActivity ctx, final String ctxname, JSONArray arr) {
    try {//from  w  w  w  .j  a va2  s  .  c om

        String type = arr.getString(0);
        final Integer id = arr.getInt(1);
        String token = arr.getString(2);

        Log.i("starwisp", "Update: " + type + " " + id + " " + token);

        // non widget commands
        if (token.equals("toast")) {
            Toast msg = Toast.makeText(ctx.getBaseContext(), arr.getString(3), Toast.LENGTH_SHORT);
            msg.show();
            return;
        }

        if (type.equals("replace-fragment")) {
            int ID = arr.getInt(1);
            String name = arr.getString(2);
            Fragment fragment = ActivityManager.GetFragment(name);
            FragmentTransaction ft = ctx.getSupportFragmentManager().beginTransaction();

            ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);

            //ft.setCustomAnimations(
            //    R.animator.card_flip_right_in, R.animator.card_flip_right_out,
            //    R.animator.card_flip_left_in, R.animator.card_flip_left_out);
            ft.replace(ID, fragment);
            //ft.addToBackStack(null);
            ft.commit();
            return;
        }

        if (token.equals("dialog-fragment")) {
            FragmentManager fm = ctx.getSupportFragmentManager();
            final int ID = arr.getInt(3);
            final JSONArray lp = arr.getJSONArray(4);
            final String name = arr.getString(5);

            final Dialog dialog = new Dialog(ctx);
            dialog.setTitle("Title...");

            LinearLayout inner = new LinearLayout(ctx);
            inner.setId(ID);
            inner.setLayoutParams(BuildLayoutParams(lp));

            dialog.setContentView(inner);

            //                Fragment fragment = ActivityManager.GetFragment(name);
            //                FragmentTransaction fragmentTransaction = ctx.getSupportFragmentManager().beginTransaction();
            //                fragmentTransaction.add(ID,fragment);
            //                fragmentTransaction.commit();

            dialog.show();

            /*                DialogFragment df = new DialogFragment() {
            @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                     Bundle savedInstanceState) {
                LinearLayout inner = new LinearLayout(ctx);
                inner.setId(ID);
                inner.setLayoutParams(BuildLayoutParams(lp));
                    
                return inner;
            }
                    
            @Override
            public Dialog onCreateDialog(Bundle savedInstanceState) {
                Dialog ret = super.onCreateDialog(savedInstanceState);
                Log.i("starwisp","MAKINGDAMNFRAGMENT");
                    
                Fragment fragment = ActivityManager.GetFragment(name);
                FragmentTransaction fragmentTransaction = ctx.getSupportFragmentManager().beginTransaction();
                fragmentTransaction.add(1,fragment);
                fragmentTransaction.commit();
                return ret;
            }
                            };
                            df.show(ctx.getFragmentManager(), "foo");
            */
        }

        if (token.equals("time-picker-dialog")) {

            final Calendar c = Calendar.getInstance();
            int hour = c.get(Calendar.HOUR_OF_DAY);
            int minute = c.get(Calendar.MINUTE);

            // Create a new instance of TimePickerDialog and return it
            TimePickerDialog d = new TimePickerDialog(ctx, null, hour, minute, true);
            d.show();
            return;
        }
        ;

        if (token.equals("make-directory")) {
            File file = new File(((StarwispActivity) ctx).m_AppDir + arr.getString(3));
            file.mkdirs();
            return;
        }

        if (token.equals("list-files")) {
            final String name = arr.getString(3);
            File file = new File(((StarwispActivity) ctx).m_AppDir + arr.getString(5));
            // todo, should probably call callback with empty list
            if (file != null) {
                File list[] = file.listFiles();

                if (list != null) {
                    String code = "(";
                    for (int i = 0; i < list.length; i++) {
                        code += " \"" + list[i].getName() + "\"";
                    }
                    code += ")";

                    DialogCallback(ctx, ctxname, name, code);
                }
            }
            return;
        }

        if (token.equals("delayed")) {
            final String name = arr.getString(3);
            final int d = arr.getInt(5);
            Runnable timerThread = new Runnable() {
                public void run() {
                    DialogCallback(ctx, ctxname, name, "");
                }
            };
            m_Handler.removeCallbacksAndMessages(null);
            m_Handler.postDelayed(timerThread, d);
            return;
        }

        if (token.equals("network-connect")) {
            if (m_NetworkManager.state == NetworkManager.State.IDLE) {
                final String name = arr.getString(3);
                final String ssid = arr.getString(5);
                m_NetworkManager.Start(ssid, (StarwispActivity) ctx, name, this);
            }
            return;
        }

        if (token.equals("http-request")) {
            if (m_NetworkManager.state == NetworkManager.State.CONNECTED) {
                Log.i("starwisp", "attempting http request");
                final String name = arr.getString(3);
                final String url = arr.getString(5);
                m_NetworkManager.StartRequestThread(url, "normal", name);
            }
            return;
        }

        if (token.equals("http-download")) {
            if (m_NetworkManager.state == NetworkManager.State.CONNECTED) {
                Log.i("starwisp", "attempting http dl request");
                final String filename = arr.getString(4);
                final String url = arr.getString(5);
                m_NetworkManager.StartRequestThread(url, "download", filename);
            }
            return;
        }

        if (token.equals("send-mail")) {
            final String to[] = new String[1];
            to[0] = arr.getString(3);
            final String subject = arr.getString(4);
            final String body = arr.getString(5);

            JSONArray attach = arr.getJSONArray(6);
            ArrayList<String> paths = new ArrayList<String>();
            for (int a = 0; a < attach.length(); a++) {
                Log.i("starwisp", attach.getString(a));
                paths.add(attach.getString(a));
            }

            email(ctx, to[0], "", subject, body, paths);
        }

        if (token.equals("date-picker-dialog")) {
            final Calendar c = Calendar.getInstance();
            int day = c.get(Calendar.DAY_OF_MONTH);
            int month = c.get(Calendar.MONTH);
            int year = c.get(Calendar.YEAR);

            final String name = arr.getString(3);

            // Create a new instance of TimePickerDialog and return it
            DatePickerDialog d = new DatePickerDialog(ctx, new DatePickerDialog.OnDateSetListener() {
                public void onDateSet(DatePicker view, int year, int month, int day) {
                    DialogCallback(ctx, ctxname, name, day + " " + month + " " + year);
                }
            }, year, month, day);
            d.show();
            return;
        }
        ;

        if (token.equals("alert-dialog")) {

            final String name = arr.getString(3);
            final String msg = arr.getString(5);

            DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    int result = 0;
                    if (which == DialogInterface.BUTTON_POSITIVE)
                        result = 1;
                    DialogCallback(ctx, ctxname, name, "" + result);
                }
            };

            AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
            builder.setMessage(msg).setPositiveButton("Yes", dialogClickListener)
                    .setNegativeButton("No", dialogClickListener).show();

            return;
        }

        if (token.equals("start-activity")) {
            ActivityManager.StartActivity(ctx, arr.getString(3), arr.getInt(4), arr.getString(5));
            return;
        }

        if (token.equals("start-activity-goto")) {
            ActivityManager.StartActivityGoto(ctx, arr.getString(3), arr.getString(4));
            return;
        }

        if (token.equals("finish-activity")) {
            ctx.setResult(arr.getInt(3));
            ctx.finish();
            return;
        }

        ///////////////////////////////////////////////////////////

        // now try and find the widget
        View vv = ctx.findViewById(id);
        if (vv == null) {
            Log.i("starwisp", "Can't find widget : " + id);
            return;
        }

        // tokens that work on everything
        if (token.equals("hide")) {
            vv.setVisibility(View.GONE);
            return;
        }

        if (token.equals("show")) {
            vv.setVisibility(View.VISIBLE);
            return;
        }

        // tokens that work on everything
        if (token.equals("set-enabled")) {
            vv.setEnabled(arr.getInt(3) == 1);
            return;
        }

        // special cases
        if (type.equals("linear-layout")) {
            LinearLayout v = (LinearLayout) vv;
            if (token.equals("contents")) {
                v.removeAllViews();
                JSONArray children = arr.getJSONArray(3);
                for (int i = 0; i < children.length(); i++) {
                    Build(ctx, ctxname, new JSONArray(children.getString(i)), v);
                }
            }
        }

        if (type.equals("button-grid")) {
            Log.i("starwisp", "button-grid update");
            LinearLayout horiz = (LinearLayout) vv;
            if (token.equals("grid-buttons")) {
                Log.i("starwisp", "button-grid contents");
                horiz.removeAllViews();

                JSONArray params = arr.getJSONArray(3);
                String buttontype = params.getString(0);
                int height = params.getInt(1);
                int textsize = params.getInt(2);
                LinearLayout.LayoutParams lp = BuildLayoutParams(params.getJSONArray(3));
                final JSONArray buttons = params.getJSONArray(4);
                final 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 = params.getString(5);
                        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 = params.getString(5);
                        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);
                    } else if (buttontype.equals("single")) {
                        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 = params.getString(5);
                        b.setOnClickListener(new View.OnClickListener() {
                            public void onClick(View v) {
                                try {
                                    for (int i = 0; i < count; i++) {
                                        JSONArray button = buttons.getJSONArray(i);
                                        int bid = button.getInt(0);
                                        if (bid != v.getId()) {
                                            ToggleButton tb = (ToggleButton) ctx.findViewById(bid);
                                            tb.setChecked(false);
                                        }
                                    }
                                } catch (JSONException e) {
                                    Log.e("starwisp", "Error parsing data " + e.toString());
                                }

                                CallbackArgs(ctx, ctxname, id, "" + v.getId() + " #t");
                            }
                        });
                        vert.addView(b);
                    }

                }
            }
        }

        /*
                    if (type.equals("grid-layout")) {
        GridLayout v = (GridLayout)vv;
        if (token.equals("contents")) {
            v.removeAllViews();
            JSONArray children = arr.getJSONArray(3);
            for (int i=0; i<children.length(); i++) {
                Build(ctx,ctxname,new JSONArray(children.getString(i)), v);
            }
        }
                    }
        */
        if (type.equals("view-pager")) {
            ViewPager v = (ViewPager) vv;
            if (token.equals("switch")) {
                v.setCurrentItem(arr.getInt(3));
            }
            if (token.equals("pages")) {
                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;
                    }
                });
            }
        }

        if (type.equals("image-view")) {
            ImageView v = (ImageView) vv;
            if (token.equals("image")) {
                int iid = ctx.getResources().getIdentifier(arr.getString(3), "drawable", ctx.getPackageName());
                v.setImageResource(iid);
            }
            if (token.equals("external-image")) {
                Bitmap bitmap = BitmapFactory.decodeFile(arr.getString(3));
                v.setImageBitmap(bitmap);
            }
            return;
        }

        if (type.equals("text-view") || type.equals("debug-text-view")) {
            Log.i("starwisp", "text-view...");
            TextView v = (TextView) vv;
            if (token.equals("text")) {
                if (type.equals("debug-text-view")) {
                    //v.setMovementMethod(new ScrollingMovementMethod());
                }
                v.setText(arr.getString(3));
            }
            return;
        }

        if (type.equals("edit-text")) {
            EditText v = (EditText) vv;
            if (token.equals("text")) {
                v.setText(arr.getString(3));
            }
            return;
        }

        if (type.equals("button")) {
            Button v = (Button) vv;
            if (token.equals("text")) {
                v.setText(arr.getString(3));
            }

            if (token.equals("listener")) {
                final String fn = arr.getString(3);
                v.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        m_Scheme.eval("(" + fn + ")");
                    }
                });
            }
            return;
        }

        if (type.equals("toggle-button")) {
            ToggleButton v = (ToggleButton) vv;
            if (token.equals("text")) {
                v.setText(arr.getString(3));
                return;
            }

            if (token.equals("checked")) {
                if (arr.getInt(3) == 0)
                    v.setChecked(false);
                else
                    v.setChecked(true);
                return;
            }

            if (token.equals("listener")) {
                final String fn = arr.getString(3);
                v.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        m_Scheme.eval("(" + fn + ")");
                    }
                });
            }
            return;
        }

        /*
                    if (type.equals("canvas")) {
        StarwispCanvas v = (StarwispCanvas)vv;
        if (token.equals("drawlist")) {
            v.SetDrawList(arr.getJSONArray(3));
        }
        return;
                    }
                
                    if (type.equals("camera-preview")) {
        final CameraPreview v = (CameraPreview)vv;
                
        if (token.equals("take-picture")) {
            final String path = ((StarwispActivity)ctx).m_AppDir+arr.getString(3);
                
            v.TakePicture(
                new PictureCallback() {
                    public void onPictureTaken(byte[] data, Camera camera) {
                        String datetime = getDateTime();
                        String filename = path+datetime + ".jpg";
                        SaveData(filename,data);
                        v.Shutdown();
                        ctx.finish();
                    }
                });
        }
                
        if (token.equals("shutdown")) {
            v.Shutdown();
        }
                
        return;
                    }
        */
        if (type.equals("seek-bar")) {
            SeekBar v = new SeekBar(ctx);
            if (token.equals("max")) {
                // android seekbar bug workaround
                int p = v.getProgress();
                v.setMax(0);
                v.setProgress(0);
                v.setMax(arr.getInt(3));
                v.setProgress(1000);

                // not working.... :(
            }
        }

        if (type.equals("spinner")) {
            Spinner v = (Spinner) vv;

            if (token.equals("selection")) {
                v.setSelection(arr.getInt(3));
            }

            if (token.equals("array")) {
                final JSONArray items = 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,
                        android.R.layout.simple_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;
                    }
                };

                v.setAdapter(spinnerArrayAdapter);

                final int wid = id;
                // need to update for new values
                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) {
                    }
                });

            }
            return;
        }

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

From source file:foam.mongoose.StarwispBuilder.java

public void Update(final StarwispActivity ctx, final String ctxname, JSONArray arr) {
    try {//  ww w .j a v  a 2  s.  c o  m

        String type = arr.getString(0);
        final Integer id = arr.getInt(1);
        String token = arr.getString(2);

        //Log.i("starwisp", "Update: "+type+" "+id+" "+token);

        // non widget commands
        if (token.equals("toast")) {
            Toast msg = Toast.makeText(ctx.getBaseContext(), arr.getString(3), Toast.LENGTH_SHORT);
            msg.show();
            return;
        }

        if (token.equals("play-sound")) {
            String name = arr.getString(3);

            if (name.equals("ping")) {
                MediaPlayer mp = MediaPlayer.create(ctx, R.raw.ping);
                mp.start();
            }
            if (name.equals("active")) {
                MediaPlayer mp = MediaPlayer.create(ctx, R.raw.active);
                mp.start();
            }
        }

        if (token.equals("vibrate")) {
            Vibrator v = (Vibrator) ctx.getSystemService(Context.VIBRATOR_SERVICE);
            v.vibrate(arr.getInt(3));
        }

        if (type.equals("replace-fragment")) {
            int ID = arr.getInt(1);
            String name = arr.getString(2);
            Fragment fragment = ActivityManager.GetFragment(name);
            FragmentTransaction ft = ctx.getSupportFragmentManager().beginTransaction();

            ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);

            //ft.setCustomAnimations(
            //    R.animator.card_flip_right_in, R.animator.card_flip_right_out,
            //    R.animator.card_flip_left_in, R.animator.card_flip_left_out);
            ft.replace(ID, fragment);
            //ft.addToBackStack(null);
            ft.commit();
            return;
        }

        if (token.equals("dialog-fragment")) {
            FragmentManager fm = ctx.getSupportFragmentManager();
            final int ID = arr.getInt(3);
            final JSONArray lp = arr.getJSONArray(4);
            final String name = arr.getString(5);

            final Dialog dialog = new Dialog(ctx);
            dialog.setTitle("Title...");

            LinearLayout inner = new LinearLayout(ctx);
            inner.setId(ID);
            inner.setLayoutParams(BuildLayoutParams(lp));

            dialog.setContentView(inner);

            //                Fragment fragment = ActivityManager.GetFragment(name);
            //                FragmentTransaction fragmentTransaction = ctx.getSupportFragmentManager().beginTransaction();
            //                fragmentTransaction.add(ID,fragment);
            //                fragmentTransaction.commit();

            dialog.show();

            /*                DialogFragment df = new DialogFragment() {
            @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                     Bundle savedInstanceState) {
                LinearLayout inner = new LinearLayout(ctx);
                inner.setId(ID);
                inner.setLayoutParams(BuildLayoutParams(lp));
                    
                return inner;
            }
                    
            @Override
            public Dialog onCreateDialog(Bundle savedInstanceState) {
                Dialog ret = super.onCreateDialog(savedInstanceState);
                Log.i("starwisp","MAKINGDAMNFRAGMENT");
                    
                Fragment fragment = ActivityManager.GetFragment(name);
                FragmentTransaction fragmentTransaction = ctx.getSupportFragmentManager().beginTransaction();
                fragmentTransaction.add(1,fragment);
                fragmentTransaction.commit();
                return ret;
            }
                            };
                            df.show(ctx.getFragmentManager(), "foo");
            */
        }

        if (token.equals("time-picker-dialog")) {

            final Calendar c = Calendar.getInstance();
            int hour = c.get(Calendar.HOUR_OF_DAY);
            int minute = c.get(Calendar.MINUTE);

            // Create a new instance of TimePickerDialog and return it
            TimePickerDialog d = new TimePickerDialog(ctx, null, hour, minute, true);
            d.show();
            return;
        }
        ;

        if (token.equals("make-directory")) {
            File file = new File(((StarwispActivity) ctx).m_AppDir + arr.getString(3));
            file.mkdirs();
            return;
        }

        if (token.equals("list-files")) {
            final String name = arr.getString(3);
            File file = new File(((StarwispActivity) ctx).m_AppDir + arr.getString(5));
            // todo, should probably call callback with empty list
            if (file != null) {
                File list[] = file.listFiles();

                if (list != null) {
                    String code = "(";
                    for (int i = 0; i < list.length; i++) {
                        code += " \"" + list[i].getName() + "\"";
                    }
                    code += ")";

                    DialogCallback(ctx, ctxname, name, code);
                }
            }
            return;
        }

        if (token.equals("gps-start")) {
            final String name = arr.getString(3);

            if (m_LocationManager == null) {
                m_LocationManager = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);
                m_GPS = new DorisLocationListener(m_LocationManager);
            }

            m_GPS.Start((StarwispActivity) ctx, name, this);
            return;
        }

        if (token.equals("delayed")) {
            final String name = arr.getString(3);
            final int d = arr.getInt(5);
            Runnable timerThread = new Runnable() {
                public void run() {
                    DialogCallback(ctx, ctxname, name, "");
                }
            };
            m_Handler.removeCallbacksAndMessages(null);
            m_Handler.postDelayed(timerThread, d);
            return;
        }

        if (token.equals("network-connect")) {
            final String name = arr.getString(3);
            final String ssid = arr.getString(5);
            m_NetworkManager.Start(ssid, (StarwispActivity) ctx, name, this);
            return;
        }

        if (token.equals("http-request")) {
            if (m_NetworkManager.state == NetworkManager.State.CONNECTED) {
                Log.i("starwisp", "attempting http request");
                final String name = arr.getString(3);
                final String url = arr.getString(5);
                m_NetworkManager.StartRequestThread(url, "normal", name);
            }
            return;
        }

        if (token.equals("http-download")) {
            if (m_NetworkManager.state == NetworkManager.State.CONNECTED) {
                Log.i("starwisp", "attempting http dl request");
                final String filename = arr.getString(4);
                final String url = arr.getString(5);
                m_NetworkManager.StartRequestThread(url, "download", filename);
            }
            return;
        }

        if (token.equals("send-mail")) {
            final String to[] = new String[1];
            to[0] = arr.getString(3);
            final String subject = arr.getString(4);
            final String body = arr.getString(5);

            JSONArray attach = arr.getJSONArray(6);
            ArrayList<String> paths = new ArrayList<String>();
            for (int a = 0; a < attach.length(); a++) {
                Log.i("starwisp", attach.getString(a));
                paths.add(attach.getString(a));
            }

            email(ctx, to[0], "", subject, body, paths);
        }

        if (token.equals("date-picker-dialog")) {
            final Calendar c = Calendar.getInstance();
            int day = c.get(Calendar.DAY_OF_MONTH);
            int month = c.get(Calendar.MONTH);
            int year = c.get(Calendar.YEAR);

            final String name = arr.getString(3);

            // Create a new instance of TimePickerDialog and return it
            DatePickerDialog d = new DatePickerDialog(ctx, new DatePickerDialog.OnDateSetListener() {
                public void onDateSet(DatePicker view, int year, int month, int day) {
                    DialogCallback(ctx, ctxname, name, day + " " + month + " " + year);
                }
            }, year, month, day);
            d.show();
            return;
        }
        ;

        if (token.equals("alert-dialog")) {

            final String name = arr.getString(3);
            final String msg = arr.getString(5);

            DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    int result = 0;
                    if (which == DialogInterface.BUTTON_POSITIVE)
                        result = 1;
                    DialogCallback(ctx, ctxname, name, "" + result);
                }
            };

            AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
            builder.setMessage(msg).setPositiveButton("Yes", dialogClickListener)
                    .setNegativeButton("No", dialogClickListener).show();

            return;
        }

        if (token.equals("start-activity")) {
            ActivityManager.StartActivity(ctx, arr.getString(3), arr.getInt(4), arr.getString(5));
            return;
        }

        if (token.equals("start-activity-goto")) {
            ActivityManager.StartActivityGoto(ctx, arr.getString(3), arr.getString(4));
            return;
        }

        if (token.equals("finish-activity")) {
            ctx.setResult(arr.getInt(3));
            ctx.finish();
            return;
        }

        ///////////////////////////////////////////////////////////

        // problem associating the id number
        if (id == 0)
            return;

        // now try and find the widget
        View vv = ctx.findViewById(id);
        if (vv == null) {
            Log.i("starwisp", "Can't find widget : " + id);
            return;
        }

        // tokens that work on everything
        if (token.equals("hide")) {
            vv.setVisibility(View.GONE);
            return;
        }

        if (token.equals("show")) {
            vv.setVisibility(View.VISIBLE);
            return;
        }

        // tokens that work on everything
        if (token.equals("set-enabled")) {
            vv.setEnabled(arr.getInt(3) == 1);
            return;
        }

        // special cases
        if (type.equals("linear-layout")) {
            LinearLayout v = (LinearLayout) vv;
            if (token.equals("contents")) {
                v.removeAllViews();
                JSONArray children = arr.getJSONArray(3);
                for (int i = 0; i < children.length(); i++) {
                    Build(ctx, ctxname, new JSONArray(children.getString(i)), v);
                }
            }
        }

        if (type.equals("button-grid")) {
            LinearLayout horiz = (LinearLayout) vv;
            if (token.equals("grid-buttons")) {
                horiz.removeAllViews();

                JSONArray params = arr.getJSONArray(3);
                String buttontype = params.getString(0);
                int height = params.getInt(1);
                int textsize = params.getInt(2);
                LinearLayout.LayoutParams lp = BuildLayoutParams(params.getJSONArray(3));
                final JSONArray buttons = params.getJSONArray(4);
                final 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 = params.getString(5);
                        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 = params.getString(5);
                        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);
                    } else if (buttontype.equals("single")) {
                        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 = params.getString(5);
                        b.setOnClickListener(new View.OnClickListener() {
                            public void onClick(View v) {
                                try {
                                    for (int i = 0; i < count; i++) {
                                        JSONArray button = buttons.getJSONArray(i);
                                        int bid = button.getInt(0);
                                        if (bid != v.getId()) {
                                            ToggleButton tb = (ToggleButton) ctx.findViewById(bid);
                                            tb.setChecked(false);
                                        }
                                    }
                                } catch (JSONException e) {
                                    Log.e("starwisp", "Error parsing data " + e.toString());
                                }

                                CallbackArgs(ctx, ctxname, id, "" + v.getId() + " #t");
                            }
                        });
                        vert.addView(b);
                    }

                }
            }
        }

        /*
                    if (type.equals("grid-layout")) {
        GridLayout v = (GridLayout)vv;
        if (token.equals("contents")) {
            v.removeAllViews();
            JSONArray children = arr.getJSONArray(3);
            for (int i=0; i<children.length(); i++) {
                Build(ctx,ctxname,new JSONArray(children.getString(i)), v);
            }
        }
                    }
        */
        if (type.equals("view-pager")) {
            ViewPager v = (ViewPager) vv;
            if (token.equals("switch")) {
                v.setCurrentItem(arr.getInt(3));
            }
            if (token.equals("pages")) {
                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;
                    }
                });
            }
        }

        if (type.equals("image-view")) {
            ImageView v = (ImageView) vv;
            if (token.equals("image")) {
                int iid = ctx.getResources().getIdentifier(arr.getString(3), "drawable", ctx.getPackageName());
                v.setImageResource(iid);
            }
            if (token.equals("external-image")) {
                Bitmap bitmap = BitmapFactory.decodeFile(arr.getString(3));
                v.setImageBitmap(bitmap);
            }
            return;
        }

        if (type.equals("text-view") || type.equals("debug-text-view")) {
            TextView v = (TextView) vv;
            if (token.equals("text")) {
                if (type.equals("debug-text-view")) {
                    //v.setMovementMethod(new ScrollingMovementMethod());
                }
                v.setText(arr.getString(3));
            }
            return;
        }

        if (type.equals("edit-text")) {
            EditText v = (EditText) vv;
            if (token.equals("text")) {
                v.setText(arr.getString(3));
            }
            if (token.equals("request-focus")) {
                v.requestFocus();
                InputMethodManager imm = (InputMethodManager) ctx
                        .getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.showSoftInput(v, InputMethodManager.SHOW_IMPLICIT);
            }
            return;
        }

        if (type.equals("button")) {
            Button v = (Button) vv;
            if (token.equals("text")) {
                v.setText(arr.getString(3));
            }

            if (token.equals("listener")) {
                final String fn = arr.getString(3);
                v.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        m_Scheme.eval("(" + fn + ")");
                    }
                });
            }
            return;
        }

        if (type.equals("toggle-button")) {
            ToggleButton v = (ToggleButton) vv;
            if (token.equals("text")) {
                v.setText(arr.getString(3));
                return;
            }

            if (token.equals("checked")) {
                if (arr.getInt(3) == 0)
                    v.setChecked(false);
                else
                    v.setChecked(true);
                return;
            }

            if (token.equals("listener")) {
                final String fn = arr.getString(3);
                v.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        m_Scheme.eval("(" + fn + ")");
                    }
                });
            }
            return;
        }

        if (type.equals("canvas")) {
            StarwispCanvas v = (StarwispCanvas) vv;
            if (token.equals("drawlist")) {
                v.SetDrawList(arr.getJSONArray(3));
            }
            return;
        }

        if (type.equals("camera-preview")) {
            final CameraPreview v = (CameraPreview) vv;

            if (token.equals("take-picture")) {
                final String path = ((StarwispActivity) ctx).m_AppDir + arr.getString(3);

                v.TakePicture(new PictureCallback() {
                    public void onPictureTaken(byte[] data, Camera camera) {
                        String datetime = getDateTime();
                        String filename = path + datetime + ".jpg";
                        SaveData(filename, data);
                        v.Shutdown();
                        ctx.finish();
                    }
                });
            }

            if (token.equals("shutdown")) {
                v.Shutdown();
            }

            return;
        }

        if (type.equals("seek-bar")) {
            SeekBar v = new SeekBar(ctx);
            if (token.equals("max")) {
                // android seekbar bug workaround
                int p = v.getProgress();
                v.setMax(0);
                v.setProgress(0);
                v.setMax(arr.getInt(3));
                v.setProgress(1000);

                // not working.... :(
            }
        }

        if (type.equals("spinner")) {
            Spinner v = (Spinner) vv;

            if (token.equals("selection")) {
                v.setSelection(arr.getInt(3));
            }

            if (token.equals("array")) {
                final JSONArray items = 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,
                        android.R.layout.simple_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;
                    }
                };

                v.setAdapter(spinnerArrayAdapter);

                final int wid = id;
                // need to update for new values
                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) {
                    }
                });

            }
            return;
        }

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

From source file:foam.opensauces.StarwispBuilder.java

public void Update(final StarwispActivity ctx, final String ctxname, JSONArray arr) {
    try {/*from w  w w . j  a v  a2 s .  c  o  m*/

        String type = arr.getString(0);
        final Integer id = arr.getInt(1);
        String token = arr.getString(2);

        Log.i("starwisp", "Update: " + type + " " + id + " " + token);

        // non widget commands
        if (token.equals("toast")) {
            Toast msg = Toast.makeText(ctx.getBaseContext(), arr.getString(3), Toast.LENGTH_SHORT);
            msg.show();
            return;
        }

        if (token.equals("play-sound")) {
            String name = arr.getString(3);

            if (name.equals("ping")) {
                MediaPlayer mp = MediaPlayer.create(ctx, R.raw.ping);
                mp.start();
            }
            if (name.equals("active")) {
                MediaPlayer mp = MediaPlayer.create(ctx, R.raw.active);
                mp.start();
            }
        }

        if (token.equals("vibrate")) {
            Vibrator v = (Vibrator) ctx.getSystemService(Context.VIBRATOR_SERVICE);
            v.vibrate(arr.getInt(3));
        }

        if (type.equals("replace-fragment")) {
            int ID = arr.getInt(1);
            String name = arr.getString(2);
            Fragment fragment = ActivityManager.GetFragment(name);
            FragmentTransaction ft = ctx.getSupportFragmentManager().beginTransaction();

            ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);

            //ft.setCustomAnimations(
            //    R.animator.card_flip_right_in, R.animator.card_flip_right_out,
            //    R.animator.card_flip_left_in, R.animator.card_flip_left_out);
            ft.replace(ID, fragment);
            //ft.addToBackStack(null);
            ft.commit();
            return;
        }

        if (token.equals("dialog-fragment")) {
            FragmentManager fm = ctx.getSupportFragmentManager();
            final int ID = arr.getInt(3);
            final JSONArray lp = arr.getJSONArray(4);
            final String name = arr.getString(5);

            final Dialog dialog = new Dialog(ctx);
            dialog.setTitle("Title...");

            LinearLayout inner = new LinearLayout(ctx);
            inner.setId(ID);
            inner.setLayoutParams(BuildLayoutParams(lp));

            dialog.setContentView(inner);

            //                Fragment fragment = ActivityManager.GetFragment(name);
            //                FragmentTransaction fragmentTransaction = ctx.getSupportFragmentManager().beginTransaction();
            //                fragmentTransaction.add(ID,fragment);
            //                fragmentTransaction.commit();

            dialog.show();

            /*                DialogFragment df = new DialogFragment() {
            @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                     Bundle savedInstanceState) {
                LinearLayout inner = new LinearLayout(ctx);
                inner.setId(ID);
                inner.setLayoutParams(BuildLayoutParams(lp));
                    
                return inner;
            }
                    
            @Override
            public Dialog onCreateDialog(Bundle savedInstanceState) {
                Dialog ret = super.onCreateDialog(savedInstanceState);
                Log.i("starwisp","MAKINGDAMNFRAGMENT");
                    
                Fragment fragment = ActivityManager.GetFragment(name);
                FragmentTransaction fragmentTransaction = ctx.getSupportFragmentManager().beginTransaction();
                fragmentTransaction.add(1,fragment);
                fragmentTransaction.commit();
                return ret;
            }
                            };
                            df.show(ctx.getFragmentManager(), "foo");
            */
        }

        if (token.equals("time-picker-dialog")) {

            final Calendar c = Calendar.getInstance();
            int hour = c.get(Calendar.HOUR_OF_DAY);
            int minute = c.get(Calendar.MINUTE);

            // Create a new instance of TimePickerDialog and return it
            TimePickerDialog d = new TimePickerDialog(ctx, null, hour, minute, true);
            d.show();
            return;
        }
        ;

        if (token.equals("make-directory")) {
            File file = new File(((StarwispActivity) ctx).m_AppDir + arr.getString(3));
            file.mkdirs();
            return;
        }

        if (token.equals("list-files")) {
            final String name = arr.getString(3);
            File file = new File(((StarwispActivity) ctx).m_AppDir + arr.getString(5));
            // todo, should probably call callback with empty list
            if (file != null) {
                File list[] = file.listFiles();

                if (list != null) {
                    String code = "(";
                    for (int i = 0; i < list.length; i++) {
                        code += " \"" + list[i].getName() + "\"";
                    }
                    code += ")";

                    DialogCallback(ctx, ctxname, name, code);
                }
            }
            return;
        }

        if (token.equals("gps-start")) {
            final String name = arr.getString(3);

            if (m_LocationManager == null) {
                m_LocationManager = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);
                m_GPS = new DorisLocationListener(m_LocationManager);
            }

            m_GPS.Start((StarwispActivity) ctx, name, this);
            return;
        }

        if (token.equals("walk-draggable")) {
            final String name = arr.getString(3);
            int iid = arr.getInt(5);
            DialogCallback(ctx, ctxname, name, WalkDraggable(ctx, name, ctxname, iid));
            return;
        }

        if (token.equals("delayed")) {
            final String name = arr.getString(3);
            final int d = arr.getInt(5);
            Runnable timerThread = new Runnable() {
                public void run() {
                    DialogCallback(ctx, ctxname, name, "");
                }
            };
            m_Handler.removeCallbacksAndMessages(null);
            m_Handler.postDelayed(timerThread, d);
            return;
        }

        if (token.equals("network-connect")) {
            final String name = arr.getString(3);
            final String ssid = arr.getString(5);
            m_NetworkManager.Start(ssid, (StarwispActivity) ctx, name, this);
            return;
        }

        if (token.equals("http-request")) {
            if (m_NetworkManager.state == NetworkManager.State.CONNECTED) {
                Log.i("starwisp", "attempting http request");
                final String name = arr.getString(3);
                final String url = arr.getString(5);
                m_NetworkManager.StartRequestThread(url, "normal", name);
            }
            return;
        }

        if (token.equals("http-download")) {
            if (m_NetworkManager.state == NetworkManager.State.CONNECTED) {
                Log.i("starwisp", "attempting http dl request");
                final String filename = arr.getString(4);
                final String url = arr.getString(5);
                m_NetworkManager.StartRequestThread(url, "download", filename);
            }
            return;
        }

        if (token.equals("send-mail")) {
            final String to[] = new String[1];
            to[0] = arr.getString(3);
            final String subject = arr.getString(4);
            final String body = arr.getString(5);

            JSONArray attach = arr.getJSONArray(6);
            ArrayList<String> paths = new ArrayList<String>();
            for (int a = 0; a < attach.length(); a++) {
                Log.i("starwisp", attach.getString(a));
                paths.add(attach.getString(a));
            }

            email(ctx, to[0], "", subject, body, paths);
        }

        if (token.equals("date-picker-dialog")) {
            final Calendar c = Calendar.getInstance();
            int day = c.get(Calendar.DAY_OF_MONTH);
            int month = c.get(Calendar.MONTH);
            int year = c.get(Calendar.YEAR);

            final String name = arr.getString(3);

            // Create a new instance of TimePickerDialog and return it
            DatePickerDialog d = new DatePickerDialog(ctx, new DatePickerDialog.OnDateSetListener() {
                public void onDateSet(DatePicker view, int year, int month, int day) {
                    DialogCallback(ctx, ctxname, name, day + " " + month + " " + year);
                }
            }, year, month, day);
            d.show();
            return;
        }
        ;

        if (token.equals("alert-dialog")) {

            final String name = arr.getString(3);
            final String msg = arr.getString(5);

            DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    int result = 0;
                    if (which == DialogInterface.BUTTON_POSITIVE)
                        result = 1;
                    DialogCallback(ctx, ctxname, name, "" + result);
                }
            };

            AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
            builder.setMessage(msg).setPositiveButton("Yes", dialogClickListener)
                    .setNegativeButton("No", dialogClickListener).show();

            return;
        }

        if (token.equals("start-activity")) {
            ActivityManager.StartActivity(ctx, arr.getString(3), arr.getInt(4), arr.getString(5));
            return;
        }

        if (token.equals("start-activity-goto")) {
            ActivityManager.StartActivityGoto(ctx, arr.getString(3), arr.getString(4));
            return;
        }

        if (token.equals("finish-activity")) {
            ctx.setResult(arr.getInt(3));
            ctx.finish();
            return;
        }

        ///////////////////////////////////////////////////////////

        // now try and find the widget
        View vv = ctx.findViewById(id);
        if (vv == null) {
            Log.i("starwisp", "Can't find widget : " + id);
            return;
        }

        // tokens that work on everything
        if (token.equals("hide")) {
            vv.setVisibility(View.GONE);
            return;
        }

        if (token.equals("show")) {
            vv.setVisibility(View.VISIBLE);
            return;
        }

        // tokens that work on everything
        if (token.equals("set-enabled")) {
            vv.setEnabled(arr.getInt(3) == 1);
            return;
        }

        // special cases
        if (type.equals("linear-layout")) {
            LinearLayout v = (LinearLayout) vv;
            if (token.equals("contents")) {
                v.removeAllViews();
                JSONArray children = arr.getJSONArray(3);
                for (int i = 0; i < children.length(); i++) {
                    Build(ctx, ctxname, new JSONArray(children.getString(i)), v);
                }
            }
        }

        // special cases
        if (type.equals("draggable")) {
            LinearLayout v = (LinearLayout) vv;
            if (token.equals("contents")) {
                //                    v.removeAllViews();
                JSONArray children = arr.getJSONArray(3);
                for (int i = 0; i < children.length(); i++) {
                    Build(ctx, ctxname, new JSONArray(children.getString(i)), v);
                }
            }
        }

        if (type.equals("button-grid")) {
            LinearLayout horiz = (LinearLayout) vv;
            if (token.equals("grid-buttons")) {
                horiz.removeAllViews();

                JSONArray params = arr.getJSONArray(3);
                String buttontype = params.getString(0);
                int height = params.getInt(1);
                int textsize = params.getInt(2);
                LinearLayout.LayoutParams lp = BuildLayoutParams(params.getJSONArray(3));
                final JSONArray buttons = params.getJSONArray(4);
                final 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 = params.getString(5);
                        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 = params.getString(5);
                        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);
                    } else if (buttontype.equals("single")) {
                        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 = params.getString(5);
                        b.setOnClickListener(new View.OnClickListener() {
                            public void onClick(View v) {
                                try {
                                    for (int i = 0; i < count; i++) {
                                        JSONArray button = buttons.getJSONArray(i);
                                        int bid = button.getInt(0);
                                        if (bid != v.getId()) {
                                            ToggleButton tb = (ToggleButton) ctx.findViewById(bid);
                                            tb.setChecked(false);
                                        }
                                    }
                                } catch (JSONException e) {
                                    Log.e("starwisp", "Error parsing data " + e.toString());
                                }

                                CallbackArgs(ctx, ctxname, id, "" + v.getId() + " #t");
                            }
                        });
                        vert.addView(b);
                    }

                }
            }
        }

        /*
                    if (type.equals("grid-layout")) {
        GridLayout v = (GridLayout)vv;
        if (token.equals("contents")) {
            v.removeAllViews();
            JSONArray children = arr.getJSONArray(3);
            for (int i=0; i<children.length(); i++) {
                Build(ctx,ctxname,new JSONArray(children.getString(i)), v);
            }
        }
                    }
        */
        if (type.equals("view-pager")) {
            ViewPager v = (ViewPager) vv;
            if (token.equals("switch")) {
                v.setCurrentItem(arr.getInt(3));
            }
            if (token.equals("pages")) {
                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;
                    }
                });
            }
        }

        if (type.equals("image-view")) {
            ImageView v = (ImageView) vv;
            if (token.equals("image")) {
                int iid = ctx.getResources().getIdentifier(arr.getString(3), "drawable", ctx.getPackageName());
                v.setImageResource(iid);
            }
            if (token.equals("external-image")) {
                Bitmap bitmap = BitmapFactory.decodeFile(arr.getString(3));
                v.setImageBitmap(bitmap);
            }
            return;
        }

        if (type.equals("text-view") || type.equals("debug-text-view")) {
            TextView v = (TextView) vv;
            if (token.equals("text")) {
                if (type.equals("debug-text-view")) {
                    //v.setMovementMethod(new ScrollingMovementMethod());
                }
                v.setText(arr.getString(3));
            }
            return;
        }

        if (type.equals("edit-text")) {
            EditText v = (EditText) vv;
            if (token.equals("text")) {
                v.setText(arr.getString(3));
            }
            if (token.equals("request-focus")) {
                v.requestFocus();
                InputMethodManager imm = (InputMethodManager) ctx
                        .getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.showSoftInput(v, InputMethodManager.SHOW_IMPLICIT);
            }
            return;
        }

        if (type.equals("button")) {
            Button v = (Button) vv;
            if (token.equals("text")) {
                v.setText(arr.getString(3));
            }

            if (token.equals("listener")) {
                final String fn = arr.getString(3);
                v.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        m_Scheme.eval("(" + fn + ")");
                    }
                });
            }
            return;
        }

        if (type.equals("toggle-button")) {
            ToggleButton v = (ToggleButton) vv;
            if (token.equals("text")) {
                v.setText(arr.getString(3));
                return;
            }

            if (token.equals("checked")) {
                if (arr.getInt(3) == 0)
                    v.setChecked(false);
                else
                    v.setChecked(true);
                return;
            }

            if (token.equals("listener")) {
                final String fn = arr.getString(3);
                v.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        m_Scheme.eval("(" + fn + ")");
                    }
                });
            }
            return;
        }

        if (type.equals("canvas")) {
            StarwispCanvas v = (StarwispCanvas) vv;
            if (token.equals("drawlist")) {
                v.SetDrawList(arr.getJSONArray(3));
            }
            return;
        }

        if (type.equals("camera-preview")) {
            final CameraPreview v = (CameraPreview) vv;

            if (token.equals("take-picture")) {
                final String path = ((StarwispActivity) ctx).m_AppDir + arr.getString(3);

                v.TakePicture(new PictureCallback() {
                    public void onPictureTaken(byte[] data, Camera camera) {
                        String datetime = getDateTime();
                        String filename = path + datetime + ".jpg";
                        SaveData(filename, data);
                        v.Shutdown();
                        ctx.finish();
                    }
                });
            }

            if (token.equals("shutdown")) {
                v.Shutdown();
            }

            return;
        }

        if (type.equals("seek-bar")) {
            SeekBar v = new SeekBar(ctx);
            if (token.equals("max")) {
                // android seekbar bug workaround
                int p = v.getProgress();
                v.setMax(0);
                v.setProgress(0);
                v.setMax(arr.getInt(3));
                v.setProgress(1000);

                // not working.... :(
            }
        }

        if (type.equals("spinner")) {
            Spinner v = (Spinner) vv;

            if (token.equals("selection")) {
                v.setSelection(arr.getInt(3));
            }

            if (token.equals("array")) {
                final JSONArray items = 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,
                        android.R.layout.simple_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;
                    }
                };

                v.setAdapter(spinnerArrayAdapter);

                final int wid = id;
                // need to update for new values
                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) {
                    }
                });

            }
            return;
        }

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

From source file:com.bigpigs.fragments.SearchFragment.java

@Override
public void onClick(View v) {
    int id = v.getId();
    switch (id) {
    case R.id.bt_clear: {
        for (Polyline line : polylines) {
            line.remove();/*  w  ww.  j av  a  2 s .c  o m*/
        }
        polylines.clear();
        map.clear();

        Log.d("size", polylines.size() + "");

        reDrawMarker();
        bt_clear.setVisibility(View.GONE);
    }
    case R.id.bt_currentLocation: {
        double lat = Double.parseDouble(
                getContext().getSharedPreferences("data", Context.MODE_PRIVATE).getString("lat", "0.0"));
        double lng = Double.parseDouble(
                getContext().getSharedPreferences("data", Context.MODE_PRIVATE).getString("lng", "0.0"));
        Log.d("latlng", lat + ":" + lng);
        currentLatLng = new LatLng(lat, lng);
        if (lat != 0.0 && lng != 0.0) {
            Utils.moveCamera(new LatLng(lat, lng), "Bn ang  y", 13, map);
        }
        break;
    }
    case R.id.tv_time: {
        mHour = 0;
        mMinute = 0;
        TimePickerDialog dialog = new TimePickerDialog(getContext(), new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                mHour = hourOfDay;
                mMinute = minute;
                sHour = mHour + "";
                sMinute = mMinute + "";
                if (mHour < 10 && mMinute < 10) {
                    tv_time.setText("0" + mHour + ":" + "0" + mMinute);
                }
                if (mHour < 10 && mMinute > 10) {
                    tv_time.setText("0" + mHour + ":" + "" + mMinute);
                }
                if (mHour > 10 && mMinute < 10) {
                    tv_time.setText("" + mHour + ":" + "0" + mMinute);
                }
                currentTime = tv_time.getText().toString();
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("day",
                        Calendar.getInstance().get(Calendar.YEAR) + "-"
                                + (Calendar.getInstance().get(Calendar.MONTH) + 1) + "-"
                                + Calendar.getInstance().get(Calendar.DAY_OF_MONTH));
                map.put("time_start", currentTime);
                map.put("textlocation", search_box.getSelectedItem().toString());

                new SearchSystemPitch(map).execute();
            }
        }, 7, 00, true);
        dialog.setTitle("Ch?n gi? bt u bn mun");
        dialog.show();
        break;
    }
    //            case R.id.bt_search :
    //            {
    //                map.clear();
    //                map.addMarker(new MarkerOptions().position(currentLatLng).title("Bn  y"));
    //                dateofweek = Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
    //                HashMap<String,String> body = new HashMap<>();
    //                body.put("time_start",tv_time.getText().toString()+":00");
    //                body.put("day", "2017-01-01");
    //                body.put("textlocation",search_box.getSelectedItem().toString());
    //                new SearchSystemPitch(body);
    //                break;
    //
    //
    //            }
    }
}

From source file:github.popeen.dsub.fragments.NowPlayingFragment.java

protected void startCustomTimerDialog() {
    // Retrieve previous custom time
    final SharedPreferences prefs = Util.getPreferences(context);
    String lengthString = prefs.getString(Constants.PREFERENCES_KEY_SLEEP_TIMER_DURATION, "5");
    int length = Integer.parseInt(lengthString);

    // Create TimePicker dialog
    TimePickerDialog timePicker = new TimePickerDialog(context, new TimePickerDialog.OnTimeSetListener() {
        @Override//from w  w w.  j  a  v  a  2  s  .  c  om
        public void onTimeSet(TimePicker timePicker, int i, int i1) {
            // Parse length from dialog
            int length = (timePicker.getCurrentHour() * 60) + timePicker.getCurrentMinute();

            // Store custom length preference
            SharedPreferences.Editor editor = prefs.edit();
            editor.putString(Constants.PREFERENCES_KEY_SLEEP_TIMER_DURATION, Integer.toString(length));
            editor.commit();

            // Start timer
            // length is in milliseconds so multiply (minutes * 60 seconds * 1000 milliseconds)
            startTimer(length * 60000);
        }
    }, 0, 5, true);

    timePicker.setTitle(R.string.menu_set_timer);
    timePicker.updateTime((length / 60), (length % 60));
    timePicker.show();
}

From source file:mobisocial.bento.ebento.ui.EditFragment.java

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

    if (savedInstanceState != null) {
        mbImageChanged = savedInstanceState.getBoolean(INSTANCE_STATE_IMAGE_CHANGED);
    }/*  w  w  w  .  j a  v  a 2  s  .  c  o  m*/

    mTargetWidth = (UIUtils.isTablet(getActivity()) ? MAX_IMG_WIDTH_TABLET : MAX_IMG_WIDTH_PHONE);
    mTargetHeight = (UIUtils.isTablet(getActivity()) ? MAX_IMG_HEIGHT_TABLET : MAX_IMG_HEIGHT_PHONE);

    // Check if this activity launched from internal activity or not
    if (getActivity().getIntent().hasExtra(EditActivity.EXTRA_EDIT)) {
        mbNewEventMode = false;
    }

    // Event
    Event event = new Event();
    if (!mbNewEventMode) {
        event = mManager.getEvent();
    }

    // View
    mRootView = (ViewGroup) inflater.inflate(R.layout.fragment_edit, container);

    // EditText
    View.OnFocusChangeListener unfocusListener = new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean flag) {
            if (flag == false) {
                InputMethodManager imm = (InputMethodManager) getActivity()
                        .getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
            }
        }
    };
    mTitle = (EditText) mRootView.findViewById(R.id.title);
    mTitle.setOnFocusChangeListener(unfocusListener);
    if (!mbNewEventMode)
        mTitle.setText(event.title);
    mPlace = (EditText) mRootView.findViewById(R.id.place);
    mPlace.setOnFocusChangeListener(unfocusListener);
    if (!mbNewEventMode)
        mPlace.setText(event.place);
    mDetails = (EditText) mRootView.findViewById(R.id.details);
    mDetails.setOnFocusChangeListener(unfocusListener);
    if (!mbNewEventMode)
        mDetails.setText(event.details);

    // Date & Time Picker
    // TODO : All day option
    if (mbNewEventMode) {
        // start
        mStartDateTime = DateTimeUtils.getRoundedCurrentDateTime();
        // end
        mEndDateTime = DateTimeUtils.getOneHourAheadEndTimeFromStartTime(mStartDateTime);
    } else {
        // start
        mStartDateTime.year = event.startDate.year;
        mStartDateTime.month = event.startDate.month;
        mStartDateTime.day = event.startDate.day;
        mStartDateTime.hour = event.startTime.hour;
        mStartDateTime.minute = event.startTime.minute;
        // end
        mEndDateTime.year = event.endDate.year;
        mEndDateTime.month = event.endDate.month;
        mEndDateTime.day = event.endDate.day;
        mEndDateTime.hour = event.endTime.hour;
        mEndDateTime.minute = event.endTime.minute;
    }
    mStartDateButton = (Button) mRootView.findViewById(R.id.start_date_button);
    mEndDateButton = (Button) mRootView.findViewById(R.id.end_date_button);
    mStartTimeButton = (Button) mRootView.findViewById(R.id.start_time_button);
    mEndTimeButton = (Button) mRootView.findViewById(R.id.end_time_button);
    setDateTimeButtonText();

    // Date
    mStartDateButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            final DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(),
                    new DatePickerDialog.OnDateSetListener() {
                        @Override
                        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                            DateTime candidateStart = new DateTime();
                            candidateStart.year = year;
                            candidateStart.month = (monthOfYear + 1);
                            candidateStart.day = dayOfMonth;
                            candidateStart.hour = mStartDateTime.hour;
                            candidateStart.minute = mStartDateTime.minute;
                            if (DateTimeUtils.isPastDateTime(candidateStart)) {
                                Toast.makeText(getActivity(), R.string.toast_edit_past_time, Toast.LENGTH_SHORT)
                                        .show();
                            } else {
                                mStartDateTime.year = year;
                                mStartDateTime.month = (monthOfYear + 1);
                                mStartDateTime.day = dayOfMonth;

                                mEndDateTime = DateTimeUtils.getEndTimeFromStartTime(mStartDateTime,
                                        mEndDateTime);
                                setDateTimeButtonText();
                            }
                        }
                    }, mStartDateTime.year, (mStartDateTime.month - 1), mStartDateTime.day);
            datePickerDialog.show();
        }
    });

    mEndDateButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            final DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(),
                    new DatePickerDialog.OnDateSetListener() {
                        @Override
                        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                            DateTime candidateEnd = new DateTime();
                            candidateEnd.year = year;
                            candidateEnd.month = (monthOfYear + 1);
                            candidateEnd.day = dayOfMonth;
                            candidateEnd.hour = mEndDateTime.hour;
                            candidateEnd.minute = mEndDateTime.minute;

                            DateTime candidateStart = new DateTime();
                            candidateStart.year = mStartDateTime.year;
                            candidateStart.month = mStartDateTime.month;
                            candidateStart.day = mStartDateTime.day;
                            candidateStart.hour = mStartDateTime.hour;
                            candidateStart.minute = mStartDateTime.minute;
                            candidateStart = DateTimeUtils.getStartTimeFromEndTime(candidateStart,
                                    candidateEnd);

                            if (DateTimeUtils.isPastDateTime(candidateStart)
                                    || DateTimeUtils.isPastDateTime(candidateEnd)) {
                                Toast.makeText(getActivity(), R.string.toast_edit_past_time, Toast.LENGTH_SHORT)
                                        .show();
                            } else {
                                mEndDateTime.year = year;
                                mEndDateTime.month = (monthOfYear + 1);
                                mEndDateTime.day = dayOfMonth;

                                mStartDateTime = DateTimeUtils.getStartTimeFromEndTime(mStartDateTime,
                                        mEndDateTime);
                                setDateTimeButtonText();
                            }
                        }
                    }, mEndDateTime.year, (mEndDateTime.month - 1), mEndDateTime.day);
            datePickerDialog.show();
        }
    });

    // Time
    mStartTimeButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            final TimePickerDialog timePickerDialog = new FiveMinutesIntervalTimePickerDialog(getActivity(),
                    new TimePickerDialog.OnTimeSetListener() {
                        @Override
                        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                            DateTime candidateStart = new DateTime();
                            candidateStart.year = mStartDateTime.year;
                            candidateStart.month = mStartDateTime.month;
                            candidateStart.day = mStartDateTime.day;
                            candidateStart.hour = hourOfDay;
                            candidateStart.minute = minute;
                            if (DateTimeUtils.isPastDateTime(candidateStart)) {
                                Toast.makeText(getActivity(), R.string.toast_edit_past_time, Toast.LENGTH_SHORT)
                                        .show();
                            } else {
                                mStartDateTime.hour = hourOfDay;
                                mStartDateTime.minute = minute;

                                mEndDateTime = DateTimeUtils.getEndTimeFromStartTime(mStartDateTime,
                                        mEndDateTime);
                                setDateTimeButtonText();
                            }
                        }
                    }, mStartDateTime.hour, mStartDateTime.minute, false);
            timePickerDialog.show();
        }
    });

    mEndTimeButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            final TimePickerDialog timePickerDialog = new FiveMinutesIntervalTimePickerDialog(getActivity(),
                    new TimePickerDialog.OnTimeSetListener() {
                        @Override
                        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                            DateTime candidateEnd = new DateTime();
                            candidateEnd.year = mEndDateTime.year;
                            candidateEnd.month = mEndDateTime.month;
                            candidateEnd.day = mEndDateTime.day;
                            candidateEnd.hour = hourOfDay;
                            candidateEnd.minute = minute;

                            DateTime candidateStart = new DateTime();
                            candidateStart.year = mStartDateTime.year;
                            candidateStart.month = mStartDateTime.month;
                            candidateStart.day = mStartDateTime.day;
                            candidateStart.hour = mStartDateTime.hour;
                            candidateStart.minute = mStartDateTime.minute;
                            candidateStart = DateTimeUtils.getStartTimeFromEndTime(candidateStart,
                                    candidateEnd);

                            if (DateTimeUtils.isPastDateTime(candidateStart)
                                    || DateTimeUtils.isPastDateTime(candidateEnd)) {
                                Toast.makeText(getActivity(), R.string.toast_edit_past_time, Toast.LENGTH_SHORT)
                                        .show();
                            } else {
                                mEndDateTime.hour = hourOfDay;
                                mEndDateTime.minute = minute;

                                mStartDateTime = DateTimeUtils.getStartTimeFromEndTime(mStartDateTime,
                                        mEndDateTime);
                                setDateTimeButtonText();
                            }
                        }
                    }, mEndDateTime.hour, mEndDateTime.minute, false);
            timePickerDialog.show();
        }
    });

    // Image
    mImageButton = (Button) mRootView.findViewById(R.id.image_button);
    mImageButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            goPicture(v);
        }
    });

    mImageView = (ImageView) mRootView.findViewById(R.id.image);
    if (mbNewEventMode) {
        if (!mbImageChanged) {
            sImageOrg = null;
        }
    } else {
        if (!mbImageChanged) {
            sImageOrg = event.image;
        }
    }

    if (sImageOrg != null) {
        mImageView.setImageBitmap(BitmapHelper.getResizedBitmap(sImageOrg, mTargetWidth, mTargetHeight, 0));
        mImageView.setVisibility(View.VISIBLE);
    } else {
        mImageView.setVisibility(View.GONE);
    }

    // Quick Action
    ActionItem cameraItem = new ActionItem(REQUEST_IMAGE_CAPTURE,
            getResources().getString(R.string.label_camera),
            getResources().getDrawable(R.drawable.ic_menu_camera));
    ActionItem galleryItem = new ActionItem(REQUEST_GALLERY, getResources().getString(R.string.label_gallery),
            getResources().getDrawable(R.drawable.ic_menu_gallery));
    ActionItem removeItem = new ActionItem(REQUEST_REMOVE,
            getResources().getString(R.string.label_remove_picture),
            getResources().getDrawable(R.drawable.ic_menu_remove_picture));

    mQuickAction = new QuickAction(getActivity());
    mQuickAction.addActionItem(cameraItem);
    mQuickAction.addActionItem(galleryItem);
    mQuickAction.addActionItem(removeItem);
    mQuickAction.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
        @Override
        public void onItemClick(QuickAction quickAction, int pos, int actionId) {
            if (actionId == REQUEST_IMAGE_CAPTURE) {
                goCamera();
            } else if (actionId == REQUEST_GALLERY) {
                goGallery();
            } else {
                goRemovePicture();
            }
        }
    });
    mQuickAction.setOnDismissListener(new QuickAction.OnDismissListener() {
        @Override
        public void onDismiss() {
        }
    });

    // Add Cal
    mAddCalCheckBox = (CheckBox) mRootView.findViewById(R.id.add_cal_checkbox);
    mAddCalText = (TextView) mRootView.findViewById(R.id.add_cal_text);
    mAddCalLayout = (LinearLayout) mRootView.findViewById(R.id.add_cal_layout);
    mAddCalSub = (TextView) mRootView.findViewById(R.id.add_cal_sub);

    if (!mbNewEventMode) {
        mAddCalText.setVisibility(View.GONE);
        mAddCalLayout.setVisibility(View.GONE);
    } else {
        // not ICS
        if (!UIUtils.isIceCreamSandwich()) {
            mAddCalSub.setVisibility(View.GONE);
        }
    }

    // Save/Cancel Buttons
    mSaveButton = (Button) mRootView.findViewById(R.id.save_button);
    mSaveButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            goSave();
        }
    });
    mCancelButton = (Button) mRootView.findViewById(R.id.cancel_button);
    mCancelButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            getActivity().finish();
        }
    });

    return mRootView;
}