Example usage for android.widget LinearLayout getChildAt

List of usage examples for android.widget LinearLayout getChildAt

Introduction

In this page you can find the example usage for android.widget LinearLayout getChildAt.

Prototype

public View getChildAt(int index) 

Source Link

Document

Returns the view at the specified position in the group.

Usage

From source file:com.httrack.android.HTTrackActivity.java

private void setProgressLinesInternal(final String[] lines) {
    // Get line divider position of the bottom coordinate
    final View lineDivider = findViewById(R.id.buttonStop);
    if (lineDivider == null) {
        return;// w w w.  j av a2s . c om
    }
    final int[] textPosition = new int[2];
    final int[] linePosition = new int[2];
    lineDivider.getLocationInWindow(linePosition);
    final int lineYTopPosition = linePosition[1];

    // Explode lines
    final LinearLayout layout = LinearLayout.class.cast(findViewById(R.id.layout));

    // Remove any additional lines
    removeLinesFromLayout(layout, lines.length);

    // Add lines while we can
    final int currSize = layout.getChildCount();
    for (int i = 0; i < lines.length; i++) {
        // Fetch or create next layout line.
        final TextView text = i < currSize ? TextView.class.cast(layout.getChildAt(i))
                : addEmptyLineToLayout(layout);

        // Stop adding lines if overlapping to the end of the screen
        text.getLocationInWindow(textPosition);
        final int height = text.getHeight();
        final int textYBottomPosition = textPosition[1] + height;
        if (textYBottomPosition >= lineYTopPosition) {
            // Then cut everything remaining
            removeLinesFromLayout(layout, i);

            // Stop here
            break;
        }

        // Set text (html-formatted) for this line
        final String line = lines[i].trim();
        if (line.length() != 0) {
            text.setText(Html.fromHtml(line));
        } else {
            // Otherwise Android 3.0 does not insert any blank line
            text.setText(Html.fromHtml("&nbsp;"));
        }
    }
}

From source file:foam.starwisp.StarwispBuilder.java

public void Update(final StarwispActivity ctx, final String ctxname, JSONArray arr) {

    String type = "";
    Integer tid = 0;//from w w w.  j  av  a 2s . c  om
    String token = "";

    try {

        type = arr.getString(0);
        tid = arr.getInt(1);
        token = arr.getString(2);

    } catch (JSONException e) {
        Log.e("starwisp",
                "Error parsing update arguments for " + ctxname + " " + arr.toString() + e.toString());
    }

    final Integer id = tid;

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

    try {

        // non widget commands
        if (token.equals("toast")) {
            Toast msg = Toast.makeText(ctx.getBaseContext(), arr.getString(3), Toast.LENGTH_SHORT);
            LinearLayout linearLayout = (LinearLayout) msg.getView();
            View child = linearLayout.getChildAt(0);
            TextView messageTextView = (TextView) child;
            messageTextView.setTextSize(arr.getInt(4));
            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("soundfile-start-recording")) {
            String filename = arr.getString(3);
            m_SoundManager.StartRecording(filename);
        }
        if (token.equals("soundfile-stop-recording")) {
            m_SoundManager.StopRecording();
        }
        if (token.equals("soundfile-start-playback")) {
            String filename = arr.getString(3);
            m_SoundManager.StartPlaying(filename);
        }
        if (token.equals("soundfile-stop-playback")) {
            m_SoundManager.StopPlaying();
        }

        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.fragment_slide_left_enter,
            //             R.animator.fragment_slide_right_exit);

            //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("view")) {
            //ctx.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse()));

            File f = new File(arr.getString(3));
            Uri fileUri = Uri.fromFile(f);

            Intent myIntent = new Intent(android.content.Intent.ACTION_VIEW);
            String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(arr.getString(3));
            String mimetype = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
            myIntent.setDataAndType(fileUri, mimetype);
            ctx.startActivity(myIntent);
            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, arr.getInt(5), arr.getInt(6));
            return;
        }

        if (token.equals("sensors-get")) {
            final String name = arr.getString(3);
            if (m_SensorHandler == null) {
                m_SensorHandler = new SensorHandler((StarwispActivity) ctx, this);
            }
            m_SensorHandler.GetSensors((StarwispActivity) ctx, name, this);
            return;
        }

        if (token.equals("sensors-start")) {
            final String name = arr.getString(3);
            final JSONArray requested_json = arr.getJSONArray(5);
            ArrayList<Integer> requested = new ArrayList<Integer>();

            try {
                for (int i = 0; i < requested_json.length(); i++) {
                    requested.add(requested_json.getInt(i));
                }
            } catch (JSONException e) {
                Log.e("starwisp", "Error parsing data in sensors start " + e.toString());
            }

            // start it up...
            if (m_SensorHandler == null) {
                m_SensorHandler = new SensorHandler((StarwispActivity) ctx, this);
            }
            m_SensorHandler.StartSensors((StarwispActivity) ctx, name, this, requested);
            return;
        }

        if (token.equals("sensors-stop")) {
            if (m_SensorHandler != null) {
                m_SensorHandler.StopSensors();
            }
            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).replace("\\", ""));
            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")) {
            Log.i("starwisp", "http-request called");
            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-post")) {
            Log.i("starwisp", "http-post called");
            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);
                final String data = arr.getString(6);
                m_NetworkManager.StartRequestThread(url, "post", data, name);
            }
            return;
        }

        if (token.equals("http-upload")) {
            if (m_NetworkManager.state == NetworkManager.State.CONNECTED) {
                Log.i("starwisp", "attempting http ul request");
                final String filename = arr.getString(4);
                final String url = arr.getString(5);
                m_NetworkManager.StartRequestThread(url, "upload", "", filename);
            }
            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("take-photo")) {
            photo(ctx, arr.getString(3), arr.getInt(4));
        }

        if (token.equals("bluetooth")) {
            final String name = arr.getString(3);
            m_Bluetooth.Start((StarwispActivity) ctx, name, this);
            return;
        }

        if (token.equals("bluetooth-send")) {
            m_Bluetooth.Write(arr.getString(3));
        }

        if (token.equals("process-image-in-place")) {
            BitmapCache.ProcessInPlace(arr.getString(3));
        }

        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("ok-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("Ok", 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;
        }

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

        if (id == 0) {
            Log.i("starwisp", "Zero ID, aborting...");
            return;
        }

        // now try and find the widget
        final 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;
        }

        // only tested on spinners
        if (token.equals("disabled")) {
            vv.setAlpha(0.3f);
            //vv.getSelectedView().setEnabled(false);
            vv.setEnabled(false);
            return;
        }

        if (token.equals("enabled")) {
            vv.setAlpha(1.0f);
            //vv.getSelectedView().setEnabled(true);
            vv.setEnabled(true);
            return;
        }

        if (token.equals("animate")) {
            JSONArray trans = arr.getJSONArray(3);

            final TranslateAnimation animation = new TranslateAnimation(getPixelsFromDp(ctx, trans.getInt(0)),
                    getPixelsFromDp(ctx, trans.getInt(1)), getPixelsFromDp(ctx, trans.getInt(2)),
                    getPixelsFromDp(ctx, trans.getInt(3)));
            animation.setDuration(1000);
            animation.setFillAfter(false);
            animation.setInterpolator(new AnticipateOvershootInterpolator(1.0f));
            animation.setAnimationListener(new AnimationListener() {
                @Override
                public void onAnimationEnd(Animation animation) {
                    vv.clearAnimation();
                    Log.i("starwisp", "animation end");
                    ((ViewManager) vv.getParent()).removeView(vv);

                    //LayoutParams lp = new LayoutParams(imageView.getWidth(), imageView.getHeight());
                    //lp.setMargins(50, 100, 0, 0);
                    //imageView.setLayoutParams(lp);
                }

                @Override
                public void onAnimationRepeat(Animation animation) {
                }

                @Override
                public void onAnimationStart(Animation animation) {
                    Log.i("starwisp", "animation start");
                }

            });

            vv.startAnimation(animation);
            return;
        }

        // tokens that work on everything
        if (token.equals("set-enabled")) {
            Log.i("starwisp", "set-enabled called...");
            vv.setEnabled(arr.getInt(3) == 1);
            vv.setClickable(arr.getInt(3) == 1);
            if (vv.getBackground() != null) {
                if (arr.getInt(3) == 0) {
                    //vv.setBackgroundColor(0x00000000);
                    vv.getBackground().setColorFilter(0x20000000, PorterDuff.Mode.MULTIPLY);
                } else {
                    vv.getBackground().setColorFilter(null);
                }
            }
            return;
        }

        if (token.equals("background-colour")) {
            JSONArray col = arr.getJSONArray(3);

            if (type.equals("linear-layout")) {
                vv.setBackgroundColor(Color.argb(col.getInt(3), col.getInt(0), col.getInt(1), col.getInt(2)));
            } else {
                //vv.setBackgroundColor();
                vv.getBackground().setColorFilter(
                        Color.argb(col.getInt(3), col.getInt(0), col.getInt(1), col.getInt(2)),
                        PorterDuff.Mode.MULTIPLY);
            }
            vv.invalidate();
            return;
        }

        // special cases

        if (type.equals("linear-layout")) {
            //Log.i("starwisp","linear-layout update id: "+id);
            StarwispLinearLayout.Update(this, (LinearLayout) vv, token, ctx, ctxname, arr);
            return;
        }

        if (type.equals("relative-layout")) {
            StarwispRelativeLayout.Update(this, (RelativeLayout) vv, token, ctx, ctxname, arr);
            return;
        }

        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 (token.equals("contents-add")) {
                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);
                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 on click 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 pages 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")) {
                v.setImageBitmap(BitmapCache.Load(arr.getString(3)));
            }
            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(Html.fromHtml(arr.getString(3)), BufferType.SPANNABLE);
                //                    v.invalidate();
            }
            if (token.equals("file")) {
                v.setText(LoadData(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[] input, Camera camera) {
                        Bitmap original = BitmapFactory.decodeByteArray(input, 0, input.length);
                        Bitmap resized = Bitmap.createScaledBitmap(original, PHOTO_WIDTH, PHOTO_HEIGHT, true);
                        ByteArrayOutputStream blob = new ByteArrayOutputStream();
                        resized.compress(Bitmap.CompressFormat.JPEG, 100, blob);

                        String datetime = getDateTime();
                        String filename = path + datetime + ".jpg";
                        SaveData(filename, blob.toByteArray());
                        v.Shutdown();
                        ctx.finish();
                    }
                });
            }

            // don't shut the activity down and use provided path
            if (token.equals("take-picture-cont")) {
                final String path = ((StarwispActivity) ctx).m_AppDir + arr.getString(3);

                Log.i("starwisp", "take-picture-cont fired");

                v.TakePicture(new PictureCallback() {
                    public void onPictureTaken(byte[] input, Camera camera) {
                        Log.i("starwisp", "on picture taken...");

                        // the version used by the uav app

                        Bitmap original = BitmapFactory.decodeByteArray(input, 0, input.length);
                        //Bitmap resized = Bitmap.createScaledBitmap(original, PHOTO_WIDTH, PHOTO_HEIGHT, true);
                        ByteArrayOutputStream blob = new ByteArrayOutputStream();
                        original.compress(Bitmap.CompressFormat.JPEG, 95, blob);
                        original.recycle();
                        String filename = path;
                        Log.i("starwisp", path);
                        SaveData(filename, blob.toByteArray());

                        // burn gps into exif data
                        if (m_GPS.currentLocation != null) {
                            double latitude = m_GPS.currentLocation.getLatitude();
                            double longitude = m_GPS.currentLocation.getLongitude();

                            try {
                                ExifInterface exif = new ExifInterface(filename);
                                exif.setAttribute(ExifInterface.TAG_GPS_LATITUDE, GPS.convert(latitude));
                                exif.setAttribute(ExifInterface.TAG_GPS_LATITUDE_REF,
                                        GPS.latitudeRef(latitude));
                                exif.setAttribute(ExifInterface.TAG_GPS_LONGITUDE, GPS.convert(longitude));
                                exif.setAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF,
                                        GPS.longitudeRef(longitude));
                                exif.saveAttributes();
                            } catch (IOException e) {
                                Log.i("starwisp",
                                        "Couldn't open " + filename + " to add exif data: ioexception caught.");
                            }

                        }

                        v.TakenPicture();
                    }
                });
            }

            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, R.layout.spinner_item,
                        spinnerArray) {
                    public View getView(int position, View convertView, ViewGroup parent) {
                        View v = super.getView(position, convertView, parent);
                        ((TextView) v).setTypeface(((StarwispActivity) ctx).m_Typeface);
                        return v;
                    }
                };

                spinnerArrayAdapter.setDropDownViewResource(R.layout.spinner_layout);
                v.setAdapter(spinnerArrayAdapter);

                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) {
                        CallbackArgs(ctx, ctxname, wid, "" + pos);
                    }

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

            }
            return;
        }

        if (type.equals("draw-map")) {
            DrawableMap v = m_DMaps.get(id);
            if (v != null) {
                if (token.equals("polygons")) {
                    v.UpdateFromJSON(arr.getJSONArray(3));
                }
                if (token.equals("centre")) {
                    JSONArray tokens = arr.getJSONArray(3);
                    v.Centre(tokens.getDouble(0), tokens.getDouble(1), tokens.getInt(2));
                }
                if (token.equals("layout")) {
                    v.m_parent.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));
                }
            } else {
                Log.e("starwisp", "Asked to update a drawmap which doesn't exist");
            }
        }

    } catch (JSONException e) {
        Log.e("starwisp", "Error parsing builder data " + e.toString());
        Log.e("starwisp", "type:" + type + " id:" + id + " token:" + token);
    }
}

From source file:com.mdlive.sav.MDLiveProviderDetails.java

private void clickForVideoOrPhoneTapReqFutureAction() {
    findViewById(R.id.dateTxtLayout).setVisibility(View.VISIBLE);
    tapSeetheDoctorTxtLayout.setVisibility(View.GONE);
    reqfutureapptBtnLayout.setVisibility(View.GONE);
    videophoneparentLl.setVisibility(View.VISIBLE);
    horizontalscrollview.setVisibility(View.GONE);
    //This condition is only for PHS Users

    final UserBasicInfo userBasicInfo = UserBasicInfo.readFromSharedPreference(getBaseContext());
    //PHS user/* www.  ja  v  a2s . co  m*/
    if (userBasicInfo.getPersonalInfo().getConsultMethod().equalsIgnoreCase("video")) {
        byphoneBtnLayout.setVisibility(View.INVISIBLE);
        byphoneBtnLayout.setBackgroundResource(R.drawable.disable_round_rect_grey_border);
        byphoneBtn.setTextColor(getResources().getColor(R.color.disableBtn));
        ((ImageView) findViewById(R.id.phoneicon)).setImageResource(R.drawable.phone_icon_gray);
        byphoneBtnLayout.setClickable(false);

        saveAppmtType("video");
        byvideoBtnLayout.setBackgroundResource(R.drawable.searchpvr_white_rounded_corner);
        byvideoBtn.setTextColor(Color.GRAY);
        byvideoBtn.setTextColor(Color.GRAY);
        byvideoBtnLayout.setVisibility(View.VISIBLE);
        byvideoBtnLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    horizontalscrollview.smoothScrollTo(layout.getChildAt(0).getLeft(), 0);
                    byvideoBtnLayout.setBackgroundResource(R.drawable.searchpvr_blue_rounded_corner);
                    byvideoBtn.setTextColor(Color.WHITE);
                    ((ImageView) findViewById(R.id.videoicon)).setImageResource(R.drawable.video_icon_white);
                    ((ImageView) findViewById(R.id.phoneicon)).setImageResource(R.drawable.phone_icon_gray);
                    byphoneBtnLayout.setBackgroundResource(R.drawable.disable_round_rect_grey_border);
                    byphoneBtn.setTextColor(getResources().getColor(R.color.disableBtn));
                    byphoneBtnLayout.setVisibility(View.INVISIBLE);
                    byphoneBtnLayout.setClickable(false);

                    horizontalscrollview.setVisibility(View.VISIBLE);
                    final LinearLayout layout = (LinearLayout) findViewById(R.id.panelMessageFiles);
                    if (layout.getChildCount() > 0) {
                        layout.removeAllViews();
                    }

                    for (TextView tv : videoList) {
                        layout.addView(tv);
                    }
                    saveConsultationType("Video", MDLiveProviderDetails.this);
                    //Enable Request Appointment Button
                    enableReqAppmtBtn();
                    ((ImageView) findViewById(R.id.videoicon)).setImageResource(R.drawable.video_icon_white);
                    //horizontalscrollview.smoothScrollTo(0,0);

                    horizontalscrollview.smoothScrollTo(layout.getChildAt(0).getLeft(), 0);
                    horizontalscrollview.postDelayed(new Runnable() {
                        public void run() {
                            horizontalscrollview.fullScroll(HorizontalScrollView.FOCUS_LEFT);
                        }
                    }, 100L);
                    //horizontalscrollview.fullScroll(HorizontalScrollView.FOCUS_LEFT);
                    selectedTimeslot = false;
                    enableReqAppmtBtn();
                    clearTimeSlotViews();
                    horizontalscrollview.startAnimation(AnimationUtils.loadAnimation(MDLiveProviderDetails.this,
                            R.anim.mdlive_trans_left_in));

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

    } else if (userBasicInfo.getPersonalInfo().getConsultMethod().equalsIgnoreCase("phone")) {
        phsOnlyForPhone();
    }
    //Only For idaho
    else if (longLocation.equalsIgnoreCase("idaho")) {
        onlyForIdaho();
    }
    //Only For Texas
    else if (longLocation.equalsIgnoreCase("texas")) {
        phsOnlyForPhone();
    }
    //Vido or Phone Button on Click listener for Blue color
    else {
        //Disabling the Video or Phone Based on the Phone list and video list
        //if the phone list is empty we should not shown the Phone Layout
        //if the video list is empty then we should not show the Video Layout.
        byvideoBtnLayout.setBackgroundResource(R.drawable.searchpvr_white_rounded_corner);
        ((ImageView) findViewById(R.id.videoicon)).setImageResource(R.drawable.video_icon);
        ((ImageView) findViewById(R.id.phoneicon)).setImageResource(R.drawable.phone_icon);
        byvideoBtn.setTextColor(Color.GRAY);
        byphoneBtnLayout.setBackgroundResource(R.drawable.searchpvr_white_rounded_corner);
        byphoneBtn.setTextColor(Color.GRAY);

        if (videoList.size() == 0) {
            saveAppmtType("phone");
            byvideoBtnLayout.setVisibility(View.VISIBLE);
            byvideoBtnLayout.setBackgroundResource(R.drawable.disable_round_rect_grey_border);
            byvideoBtn.setTextColor(getResources().getColor(R.color.disableBtn));
            ((ImageView) findViewById(R.id.videoicon)).setImageResource(R.drawable.video_icon_gray);
            byvideoBtnLayout.setClickable(false);
        } else {
            byvideoBtnLayout.setVisibility(View.VISIBLE);
            byvideoBtnLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    try {
                        horizontalscrollview.smoothScrollTo(layout.getChildAt(0).getLeft(), 0);
                        byvideoBtnLayout.setBackgroundResource(R.drawable.searchpvr_blue_rounded_corner);
                        byvideoBtn.setTextColor(Color.WHITE);
                        ((ImageView) findViewById(R.id.videoicon))
                                .setImageResource(R.drawable.video_icon_white);
                        byphoneBtnLayout.setVisibility(View.VISIBLE);
                        byphoneBtnLayout.setBackgroundResource(R.drawable.searchpvr_white_rounded_corner);
                        byphoneBtn.setTextColor(Color.GRAY);
                        ((ImageView) findViewById(R.id.phoneicon)).setImageResource(R.drawable.phone_icon);

                        horizontalscrollview.setVisibility(View.VISIBLE);
                        LinearLayout layout = (LinearLayout) findViewById(R.id.panelMessageFiles);
                        if (layout.getChildCount() > 0) {
                            layout.removeAllViews();
                        }

                        for (TextView tv : videoList) {
                            layout.addView(tv);
                        }
                        saveConsultationType("Video", MDLiveProviderDetails.this);
                        //Enable Request Appointment Button

                        horizontalscrollview.smoothScrollTo(layout.getChildAt(0).getLeft(), 0);
                        ((ImageView) findViewById(R.id.videoicon))
                                .setImageResource(R.drawable.video_icon_white);
                        ((ImageView) findViewById(R.id.phoneicon)).setImageResource(R.drawable.phone_icon);
                        selectedTimeslot = false;
                        enableReqAppmtBtn();
                        clearTimeSlotViews();
                        horizontalscrollview.startAnimation(AnimationUtils
                                .loadAnimation(MDLiveProviderDetails.this, R.anim.mdlive_trans_left_in));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        if (phoneList.size() == 0) {
            saveAppmtType("video");
            byphoneBtnLayout.setVisibility(View.VISIBLE);
            byphoneBtnLayout.setBackgroundResource(R.drawable.disable_round_rect_grey_border);
            byphoneBtn.setTextColor(getResources().getColor(R.color.disableBtn));
            ((ImageView) findViewById(R.id.phoneicon)).setImageResource(R.drawable.phone_icon_gray);
            byphoneBtnLayout.setClickable(false);
        } else {
            byphoneBtnLayout.setVisibility(View.VISIBLE);
            byphoneBtnLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    try {
                        horizontalscrollview.smoothScrollTo(layout.getChildAt(0).getLeft(), 0);
                        byphoneBtnLayout.setBackgroundResource(R.drawable.searchpvr_blue_rounded_corner);
                        byphoneBtn.setTextColor(Color.WHITE);
                        ((ImageView) findViewById(R.id.phoneicon))
                                .setImageResource(R.drawable.phone_icon_white);

                        byvideoBtnLayout.setVisibility(View.VISIBLE);
                        byvideoBtnLayout.setBackgroundResource(R.drawable.searchpvr_white_rounded_corner);
                        byvideoBtn.setTextColor(Color.GRAY);
                        ((ImageView) findViewById(R.id.videoicon)).setImageResource(R.drawable.video_icon_gray);
                        horizontalscrollview.setVisibility(View.VISIBLE);
                        LinearLayout layout = (LinearLayout) findViewById(R.id.panelMessageFiles);
                        if (layout.getChildCount() > 0) {
                            layout.removeAllViews();
                        }
                        for (TextView tv : phoneList) {
                            layout.addView(tv);
                        }
                        saveConsultationType("Phone", MDLiveProviderDetails.this);
                        //Enable Request Appointment Button

                        horizontalscrollview.smoothScrollTo(layout.getChildAt(0).getLeft(), 0);
                        ((ImageView) findViewById(R.id.phoneicon))
                                .setImageResource(R.drawable.phone_icon_white);
                        ((ImageView) findViewById(R.id.videoicon)).setImageResource(R.drawable.video_icon);
                        selectedTimeslot = false;
                        enableReqAppmtBtn();
                        clearTimeSlotViews();
                        horizontalscrollview.startAnimation(AnimationUtils
                                .loadAnimation(MDLiveProviderDetails.this, R.anim.mdlive_trans_left_in));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }

    }

}

From source file:com.juick.android.MainActivity.java

@TargetApi(VERSION_CODES.ICE_CREAM_SANDWICH)
private void selectSourcesForCombined(final String prefix, final String[] codes) {
    final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
    ScrollView v = new ScrollView(this);
    v.setLayoutParams(new ScrollView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT));
    final LinearLayout ll = new LinearLayout(this);
    ll.setLayoutParams(new ScrollView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT));
    ll.setOrientation(LinearLayout.VERTICAL);
    v.addView(ll);//from  w  w w . j  ava2  s. co  m
    for (int i = 0; i < codes.length; i++) {
        final CompoundButton sw = VERSION.SDK_INT >= 14 ? new Switch(this) : new CheckBox(this);
        sw.setPadding(10, 10, 10, 10);
        sw.setLayoutParams(new ScrollView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));
        sw.setText(codes[i]);
        sw.setChecked(sp.getBoolean(prefix + codes[i], true));
        ll.addView(sw);
    }

    new AlertDialog.Builder(MainActivity.this).setView(v).setCancelable(true)
            .setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialogInterface) {
                    SharedPreferences.Editor e = sp.edit();
                    for (int i = 0; i < ll.getChildCount(); i++) {
                        CompoundButton cb = (CompoundButton) ll.getChildAt(i);
                        assert cb != null;
                        e.putBoolean(prefix + codes[i], cb.isChecked());
                    }
                    e.commit();
                }
            }).create().show();

}

From source file:im.vector.fragments.VectorSettingsPreferencesFragment.java

private void displayTextSizeSelection(final Activity activity) {
    AlertDialog.Builder builder = new AlertDialog.Builder(activity);
    LayoutInflater inflater = activity.getLayoutInflater();

    View layout = inflater.inflate(R.layout.text_size_selection, null);
    builder.setTitle(R.string.font_size);
    builder.setView(layout);/*  ww  w  . j av  a2s  .  c  om*/

    builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
        }
    });

    builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
        }
    });

    final AlertDialog dialog = builder.create();
    dialog.show();

    LinearLayout linearLayout = layout.findViewById(R.id.text_selection_group_view);

    int childCount = linearLayout.getChildCount();

    String scaleText = VectorApp.getFontScale();

    for (int i = 0; i < childCount; i++) {
        View v = linearLayout.getChildAt(i);

        if (v instanceof CheckedTextView) {
            final CheckedTextView checkedTextView = (CheckedTextView) v;
            checkedTextView.setChecked(TextUtils.equals(checkedTextView.getText(), scaleText));

            checkedTextView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                    VectorApp.updateFontScale(checkedTextView.getText().toString());
                    activity.startActivity(activity.getIntent());
                    activity.finish();
                }
            });
        }
    }
}

From source file:usbong.android.likha_collection_1.UsbongDecisionTreeEngineActivity.java

public void processNextButtonPressed() {
    wasNextButtonPressed = true;/*from w  ww  . j a v a2s . c  om*/
    hasUpdatedDecisionTrackerContainer = false;

    //edited by Mike, 20160417
    if ((mTts != null) && (mTts.isSpeaking())) {
        mTts.stop();
    }
    //edited by Mike, 20160417
    if ((myMediaPlayer != null) && (myMediaPlayer.isPlaying())) {
        myMediaPlayer.stop();
    }

    if (currAudioRecorder != null) {
        try {
            //if stop button is pressable
            if (stopButton.isEnabled()) {
                currAudioRecorder.stop();
            }
            if (currAudioRecorder.isPlaying()) {
                currAudioRecorder.stopPlayback();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        String path = currAudioRecorder.getPath();
        //               System.out.println(">>>>>>>>>>>>>>>>>>>currAudioRecorder: "+currAudioRecorder);
        if (!attachmentFilePaths.contains(path)) {
            attachmentFilePaths.add(path);
            //                  System.out.println(">>>>>>>>>>>>>>>>adding path: "+path);
        }
    }

    //END_STATE_SCREEN = last screen
    if (currScreen == UsbongConstants.END_STATE_SCREEN) {
        int usbongAnswerContainerSize = usbongAnswerContainer.size();
        StringBuffer outputStringBuffer = new StringBuffer();
        for (int i = 0; i < usbongAnswerContainerSize; i++) {
            outputStringBuffer.append(usbongAnswerContainer.elementAt(i));
        }

        myOutputDirectory = UsbongUtils.getDateTimeStamp() + "/";
        if (UsbongUtils.STORE_OUTPUT) {
            try {
                UsbongUtils.createNewOutputFolderStructure();
            } catch (Exception e) {
                e.printStackTrace();
            }
            UsbongUtils.storeOutputInSDCard(
                    UsbongUtils.BASE_FILE_PATH + myOutputDirectory + UsbongUtils.getDateTimeStamp() + ".csv",
                    outputStringBuffer.toString());
        } else {
            UsbongUtils.deleteRecursive(new File(UsbongUtils.BASE_FILE_PATH + myOutputDirectory));
        }

        //wasNextButtonPressed=false; //no need to make this true, because this is the last node
        hasUpdatedDecisionTrackerContainer = true;

        /*
        //send to server
        UsbongUtils.performFileUpload(UsbongUtils.BASE_FILE_PATH + myOutputDirectory + UsbongUtils.getTimeStamp() + ".csv");
                 
        //send to email
        Intent emailIntent = UsbongUtils.performEmailProcess(UsbongUtils.BASE_FILE_PATH + myOutputDirectory + UsbongUtils.getTimeStamp() + ".csv", attachmentFilePaths);
        emailIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        //                emailIntent.addFlags(RESULT_OK);
        startActivityForResult(Intent.createChooser(emailIntent, "Email:"),EMAIL_SENDING_SUCCESS);
        */

        //added by Mike, Sept. 10, 2014
        UsbongUtils.clearTempFolder();

        //added by Mike, 20160415
        if (UsbongUtils.IS_IN_AUTO_LOOP_MODE) {
            //added by Mike, 20161118
            AppRater.showRateDialog(this);

            isAutoLoopedTree = true;
            initParser(myTree);
            return;
        } else {
            //return to main activity
            finish();
            //added by Mike, 20161118
            Intent toUsbongMainActivityIntent = new Intent(UsbongDecisionTreeEngineActivity.this,
                    UsbongMainActivity.class);
            toUsbongMainActivityIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            toUsbongMainActivityIntent.putExtra("completed_tree", "true");
            startActivity(toUsbongMainActivityIntent);
        }
    } else {
        if (currScreen == UsbongConstants.YES_NO_DECISION_SCREEN) {
            RadioButton myYesRadioButton = (RadioButton) findViewById(R.id.yes_radiobutton);
            RadioButton myNoRadioButton = (RadioButton) findViewById(R.id.no_radiobutton);

            if (myYesRadioButton.isChecked()) {
                currUsbongNode = nextUsbongNodeIfYes;

                UsbongUtils.addElementToContainer(usbongAnswerContainer, "Y;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
            } else if (myNoRadioButton.isChecked()) {
                currUsbongNode = nextUsbongNodeIfNo;
                //                     usbongAnswerContainer.addElement("N;");                                             
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "N;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
            } else { //if no radio button was checked                       
                if (!UsbongUtils.IS_IN_DEBUG_MODE) {
                    if (!isAnOptionalNode) {
                        showRequiredFieldAlert(PLEASE_CHOOSE_AN_ANSWER_ALERT_TYPE);
                        wasNextButtonPressed = false;
                        hasUpdatedDecisionTrackerContainer = true;
                        return;
                    }
                }
                currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any"
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "A;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
            }
        } else if (currScreen == UsbongConstants.SEND_TO_WEBSERVER_SCREEN) {
            RadioButton myYesRadioButton = (RadioButton) findViewById(R.id.yes_radiobutton);
            RadioButton myNoRadioButton = (RadioButton) findViewById(R.id.no_radiobutton);

            if (myYesRadioButton.isChecked()) {
                currUsbongNode = nextUsbongNodeIfYes;
                //                     usbongAnswerContainer.addElement("Y;");         
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "Y;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                decisionTrackerContainer.addElement(usbongAnswerContainer.lastElement());
                //                     wasNextButtonPressed=false; //no need to make this true, because "Y;" has already been added to decisionTrackerContainer
                hasUpdatedDecisionTrackerContainer = true;

                //edited by Mike, March 4, 2013
                //"save" the output into the SDCard as "output.txt"
                //                      int usbongAnswerContainerSize = usbongAnswerContainer.size();
                int usbongAnswerContainerSize = usbongAnswerContainerCounter;

                StringBuffer outputStringBuffer = new StringBuffer();
                for (int i = 0; i < usbongAnswerContainerSize; i++) {
                    outputStringBuffer.append(usbongAnswerContainer.elementAt(i));
                }

                myOutputDirectory = UsbongUtils.getDateTimeStamp() + "/";
                try {
                    UsbongUtils.createNewOutputFolderStructure();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                UsbongUtils.storeOutputInSDCard(UsbongUtils.BASE_FILE_PATH + myOutputDirectory
                        + UsbongUtils.getDateTimeStamp() + ".csv", outputStringBuffer.toString());

                //send to server
                UsbongUtils.performFileUpload(UsbongUtils.BASE_FILE_PATH + myOutputDirectory
                        + UsbongUtils.getDateTimeStamp() + ".csv");
            } else if (myNoRadioButton.isChecked()) {
                currUsbongNode = nextUsbongNodeIfNo;
                //                     usbongAnswerContainer.addElement("N;");                                             
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "N;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;
            } else { //if no radio button was checked                       
                if (!UsbongUtils.IS_IN_DEBUG_MODE) {
                    if (!isAnOptionalNode) {
                        showRequiredFieldAlert(PLEASE_CHOOSE_AN_ANSWER_ALERT_TYPE);
                        wasNextButtonPressed = false;
                        hasUpdatedDecisionTrackerContainer = true;
                        return;
                    }
                }
                //                       else {
                currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any"
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "A;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;
                //                      initParser();            
            }
            initParser();
        } else if (currScreen == UsbongConstants.SEND_TO_CLOUD_BASED_SERVICE_SCREEN) {
            RadioButton myYesRadioButton = (RadioButton) findViewById(R.id.yes_radiobutton);
            RadioButton myNoRadioButton = (RadioButton) findViewById(R.id.no_radiobutton);

            if (myYesRadioButton.isChecked()) {
                currUsbongNode = nextUsbongNodeIfYes;
                //                     usbongAnswerContainer.addElement("Y;");                                             
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "Y;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                decisionTrackerContainer.addElement(usbongAnswerContainer.lastElement());
                //                     wasNextButtonPressed=false; //no need to make this true, because "Y;" has already been added to decisionTrackerContainer
                hasUpdatedDecisionTrackerContainer = true;

                StringBuffer sb = new StringBuffer();
                for (int i = 0; i < decisionTrackerContainer.size(); i++) {
                    sb.append(decisionTrackerContainer.elementAt(i));
                }
                Log.d(">>>>>>>>>>>>>decisionTrackerContainer", sb.toString());

                //edited by Mike, March 4, 2013
                //"save" the output into the SDCard as "output.txt"
                //                      int usbongAnswerContainerSize = usbongAnswerContainer.size();
                int usbongAnswerContainerSize = usbongAnswerContainerCounter;

                StringBuffer outputStringBuffer = new StringBuffer();
                for (int i = 0; i < usbongAnswerContainerSize; i++) {
                    outputStringBuffer.append(usbongAnswerContainer.elementAt(i));
                }

                myOutputDirectory = UsbongUtils.getDateTimeStamp() + "/";
                try {
                    UsbongUtils.createNewOutputFolderStructure();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                UsbongUtils.storeOutputInSDCard(UsbongUtils.BASE_FILE_PATH + myOutputDirectory
                        + UsbongUtils.getDateTimeStamp() + ".csv", outputStringBuffer.toString());

                //send to cloud-based service
                Intent sendToCloudBasedServiceIntent = UsbongUtils
                        .performSendToCloudBasedServiceProcess(UsbongUtils.BASE_FILE_PATH + myOutputDirectory
                                + UsbongUtils.getDateTimeStamp() + ".csv", attachmentFilePaths);
                /*emailIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                */
                //                      emailIntent.addFlags(RESULT_OK);
                //                      startActivityForResult(Intent.createChooser(emailIntent, "Email:"),EMAIL_SENDING_SUCCESS);
                //answer from Llango J, stackoverflow
                //Reference: http://stackoverflow.com/questions/7479883/problem-with-sending-email-goes-back-to-previous-activity;
                //last accessed: 22 Oct. 2012
                startActivity(
                        Intent.createChooser(sendToCloudBasedServiceIntent, "Send to Cloud-based Service:"));
            } else if (myNoRadioButton.isChecked()) {
                currUsbongNode = nextUsbongNodeIfNo;
                //                     usbongAnswerContainer.addElement("N;");                                             
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "N;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;
            } else { //if no radio button was checked                       
                if (!UsbongUtils.IS_IN_DEBUG_MODE) {
                    if (!isAnOptionalNode) {
                        showRequiredFieldAlert(PLEASE_CHOOSE_AN_ANSWER_ALERT_TYPE);
                        wasNextButtonPressed = false;
                        hasUpdatedDecisionTrackerContainer = true;
                        return;
                    }
                }
                //                       else {
                currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any"
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "A;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;
                //                      initParser();            

                /*
                                       if (!isAnOptionalNode) {
                  showRequiredFieldAlert(PLEASE_CHOOSE_AN_ANSWER_ALERT_TYPE);
                 wasNextButtonPressed=false;
                 hasUpdatedDecisionTrackerContainer=true;
                         
                 return;
                                       }
                                       else {
                 currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any"
                //                        usbongAnswerContainer.addElement("A;");                                             
                 UsbongUtils.addElementToContainer(usbongAnswerContainer, "A;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;
                        
                initParser();            
                                       }
                */
            }
            /*                    
                              currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any"
                              usbongAnswerContainer.addElement("Any;");                                             
            */
            initParser();
        } else if (currScreen == UsbongConstants.MULTIPLE_CHECKBOXES_SCREEN) {
            //                   requiredTotalCheckedBoxes   
            LinearLayout myMultipleCheckboxesLinearLayout = (LinearLayout) findViewById(
                    R.id.multiple_checkboxes_linearlayout);
            StringBuffer sb = new StringBuffer();
            int totalCheckedBoxes = 0;
            int totalCheckBoxChildren = myMultipleCheckboxesLinearLayout.getChildCount();
            //begin with i=1, because i=0 is for checkboxes_textview
            for (int i = 1; i < totalCheckBoxChildren; i++) {
                if (((CheckBox) myMultipleCheckboxesLinearLayout.getChildAt(i)).isChecked()) {
                    totalCheckedBoxes++;
                    sb.append("," + (i - 1)); //do a (i-1) so that i starts with 0 for the checkboxes (excluding checkboxes_textview) to maintain consistency with the other components
                }
            }

            if (totalCheckedBoxes >= requiredTotalCheckedBoxes) {
                currUsbongNode = nextUsbongNodeIfYes;
                sb.insert(0, "Y"); //insert in front of stringBuffer
                sb.append(";");
            } else {
                currUsbongNode = nextUsbongNodeIfNo;
                sb.delete(0, sb.length());
                sb.append("N,;"); //make sure to add the comma
            }
            //                   usbongAnswerContainer.addElement(sb.toString());
            UsbongUtils.addElementToContainer(usbongAnswerContainer, sb.toString(),
                    usbongAnswerContainerCounter);
            usbongAnswerContainerCounter++;

            initParser();
        } else if (currScreen == UsbongConstants.MULTIPLE_RADIO_BUTTONS_SCREEN) {
            currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any"
            RadioGroup myRadioGroup = (RadioGroup) findViewById(R.id.multiple_radio_buttons_radiogroup);

            //                   if (UsbongUtils.IS_IN_DEBUG_MODE==false) {
            if (myRadioGroup.getCheckedRadioButtonId() == -1) { //no radio button checked
                if (!UsbongUtils.IS_IN_DEBUG_MODE) {
                    if (!isAnOptionalNode) {
                        showRequiredFieldAlert(PLEASE_CHOOSE_AN_ANSWER_ALERT_TYPE);
                        wasNextButtonPressed = false;
                        hasUpdatedDecisionTrackerContainer = true;
                        return;
                    }
                }
                //                          else {
                currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any"
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "A;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
                //                          }
            } else {
                //                         usbongAnswerContainer.addElement(myRadioGroup.getCheckedRadioButtonId()+";");
                UsbongUtils.addElementToContainer(usbongAnswerContainer,
                        myRadioGroup.getCheckedRadioButtonId() + ";", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
            }
            //                   }
            /*                   
                               else {
            //                      usbongAnswerContainer.addElement(myRadioGroup.getCheckedRadioButtonId()+";");
              UsbongUtils.addElementToContainer(usbongAnswerContainer, myRadioGroup.getCheckedRadioButtonId()+";", usbongAnswerContainerCounter);
             usbongAnswerContainerCounter++;
                      
              initParser();                      
                               }
            */
        } else if (currScreen == UsbongConstants.MULTIPLE_RADIO_BUTTONS_WITH_ANSWER_SCREEN) {
            currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any"
            RadioGroup myRadioGroup = (RadioGroup) findViewById(R.id.multiple_radio_buttons_radiogroup);

            /*                   if (UsbongUtils.IS_IN_DEBUG_MODE==false) {
             */
            if (myRadioGroup.getCheckedRadioButtonId() == -1) { //no radio button checked                                                  
                if (!UsbongUtils.IS_IN_DEBUG_MODE) {
                    if (!isAnOptionalNode) {
                        showRequiredFieldAlert(PLEASE_CHOOSE_AN_ANSWER_ALERT_TYPE);
                        wasNextButtonPressed = false;
                        hasUpdatedDecisionTrackerContainer = true;
                        return;
                    }
                }
                //                          else {
                currUsbongNode = nextUsbongNodeIfYes; //choose Yes if "Any"
                UsbongUtils.addElementToContainer(usbongAnswerContainer,
                        "A," + myRadioGroup.getCheckedRadioButtonId() + ";", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
                //                          }
            } else {
                if (myMultipleRadioButtonsWithAnswerScreenAnswer
                        .equals("" + myRadioGroup.getCheckedRadioButtonId())) {
                    currUsbongNode = nextUsbongNodeIfYes;
                    UsbongUtils.addElementToContainer(usbongAnswerContainer,
                            "Y," + myRadioGroup.getCheckedRadioButtonId() + ";", usbongAnswerContainerCounter);
                } else {
                    currUsbongNode = nextUsbongNodeIfNo;
                    UsbongUtils.addElementToContainer(usbongAnswerContainer,
                            "N," + myRadioGroup.getCheckedRadioButtonId() + ";", usbongAnswerContainerCounter);
                }

                usbongAnswerContainerCounter++;
                initParser();
            }
        } else if (currScreen == UsbongConstants.LINK_SCREEN) {
            RadioGroup myRadioGroup = (RadioGroup) findViewById(R.id.multiple_radio_buttons_radiogroup);

            try {
                currUsbongNode = UsbongUtils.getLinkFromRadioButton(
                        radioButtonsContainer.elementAt(myRadioGroup.getCheckedRadioButtonId()));
            } catch (Exception e) {
                //if the user hasn't ticked any radio button yet
                //put the currUsbongNode to default
                //                currUsbongNode = UsbongUtils.getLinkFromRadioButton(nextUsbongNodeIfYes); //nextUsbongNodeIfNo will also do, since this is "Any"
                //of course, showPleaseAnswerAlert() will be called                        
                //edited by Mike, 20160613
                //don't change the currUsbongNode anymore if no radio button has been ticked                
            }

            //                   Log.d(">>>>>>>>>>currUsbongNode",currUsbongNode);
            if (myRadioGroup.getCheckedRadioButtonId() == -1) { //no radio button checked
                //                         if (!UsbongUtils.IS_IN_DEBUG_MODE) {
                if (!isAnOptionalNode) {
                    showRequiredFieldAlert(PLEASE_CHOOSE_AN_ANSWER_ALERT_TYPE);
                    wasNextButtonPressed = false;
                    hasUpdatedDecisionTrackerContainer = true;

                    return;
                }
                //                         }
                //                          else {
                currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any"
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "A;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
                //                          }
            } else {
                //                         usbongAnswerContainer.addElement(myRadioGroup.getCheckedRadioButtonId()+";");
                UsbongUtils.addElementToContainer(usbongAnswerContainer,
                        myRadioGroup.getCheckedRadioButtonId() + ";", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
            }
            /*                   }
                               else {
              usbongAnswerContainer.addElement(myRadioGroup.getCheckedRadioButtonId()+";");
               initParser();                      
                               }
            */
        } else if ((currScreen == UsbongConstants.TEXTFIELD_SCREEN)
                || (currScreen == UsbongConstants.TEXTFIELD_WITH_UNIT_SCREEN)
                || (currScreen == UsbongConstants.TEXTFIELD_NUMERICAL_SCREEN)) {
            currUsbongNode = nextUsbongNodeIfYes; //= nextIMCIQuestionIfNo will also do
            EditText myTextFieldScreenEditText = (EditText) findViewById(R.id.textfield_edittext);

            //                    if (UsbongUtils.IS_IN_DEBUG_MODE==false) {
            //if it's blank
            if (myTextFieldScreenEditText.getText().toString().trim().equals("")) {
                if (!UsbongUtils.IS_IN_DEBUG_MODE) {
                    if (!isAnOptionalNode) {
                        showRequiredFieldAlert(PLEASE_ANSWER_FIELD_ALERT_TYPE);
                        wasNextButtonPressed = false;
                        hasUpdatedDecisionTrackerContainer = true;
                        return;
                    }
                }
                //                          else {
                currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any"
                //                           usbongAnswerContainer.addElement("A;");                                             
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "A,;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
                //                          }
            } else {
                //                        usbongAnswerContainer.addElement("A,"+myTextFieldScreenEditText.getText()+";");                     
                UsbongUtils.addElementToContainer(usbongAnswerContainer,
                        "A," + myTextFieldScreenEditText.getText() + ";", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
            }
        } else if (currScreen == UsbongConstants.TEXTFIELD_WITH_ANSWER_SCREEN) {
            currUsbongNode = nextUsbongNodeIfYes;
            EditText myTextFieldScreenEditText = (EditText) findViewById(R.id.textfield_edittext);
            //if it's blank
            if (myTextFieldScreenEditText.getText().toString().trim().equals("")) {
                if (!UsbongUtils.IS_IN_DEBUG_MODE) {
                    if (!isAnOptionalNode) {
                        showRequiredFieldAlert(PLEASE_ANSWER_FIELD_ALERT_TYPE);
                        wasNextButtonPressed = false;
                        hasUpdatedDecisionTrackerContainer = true;
                        return;
                    }
                }
                currUsbongNode = nextUsbongNodeIfYes; //choose Yes if "Any"
                UsbongUtils.addElementToContainer(usbongAnswerContainer,
                        "A," + myTextFieldScreenEditText.getText().toString().trim() + ";",
                        usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
            } else {
                //added by Mike, Jan. 27, 2014
                Vector<String> myPossibleAnswers = new Vector<String>();
                StringTokenizer myPossibleAnswersStringTokenizer = new StringTokenizer(
                        myTextFieldWithAnswerScreenAnswer, "||");
                if (myPossibleAnswersStringTokenizer != null) {
                    while (myPossibleAnswersStringTokenizer.hasMoreTokens()) { //get last element (i.e. Mike in "textFieldWithAnswer~Who is the founder of Usbong (nickname)?Answer=Mike")
                        myPossibleAnswers.add(myPossibleAnswersStringTokenizer.nextToken());
                    }
                }
                int size = myPossibleAnswers.size();
                for (int i = 0; i < size; i++) {
                    if (myPossibleAnswers.elementAt(i)
                            .equals(myTextFieldScreenEditText.getText().toString().trim())) {
                        currUsbongNode = nextUsbongNodeIfYes;
                        UsbongUtils.addElementToContainer(usbongAnswerContainer,
                                "Y," + myTextFieldScreenEditText.getText().toString().trim() + ";",
                                usbongAnswerContainerCounter);
                        break;
                    }

                    if (i == size - 1) { //if this is the last element in the vector
                        currUsbongNode = nextUsbongNodeIfNo;
                        UsbongUtils.addElementToContainer(usbongAnswerContainer,
                                "N," + myTextFieldScreenEditText.getText().toString().trim() + ";",
                                usbongAnswerContainerCounter);
                    }
                }
                /*                        
                  if (myTextFieldWithAnswerScreenAnswer.equals(myTextFieldScreenEditText.getText().toString().trim())) {
                   currUsbongNode = nextUsbongNodeIfYes;    
                    UsbongUtils.addElementToContainer(usbongAnswerContainer, "Y,"+myTextFieldScreenEditText.getText().toString().trim()+";", usbongAnswerContainerCounter);
                  }
                  else {
                   currUsbongNode = nextUsbongNodeIfNo;                                               
                    UsbongUtils.addElementToContainer(usbongAnswerContainer, "N,"+myTextFieldScreenEditText.getText().toString().trim()+";", usbongAnswerContainerCounter);
                  }                    
                */
                usbongAnswerContainerCounter++;
                initParser();
            }
        } else if ((currScreen == UsbongConstants.TEXTAREA_SCREEN)) {
            currUsbongNode = nextUsbongNodeIfYes; //= nextIMCIQuestionIfNo will also do
            EditText myTextAreaScreenEditText = (EditText) findViewById(R.id.textarea_edittext);

            //                    if (UsbongUtils.IS_IN_DEBUG_MODE==false) {
            //if it's blank
            if (myTextAreaScreenEditText.getText().toString().trim().equals("")) {
                if (!UsbongUtils.IS_IN_DEBUG_MODE) {
                    if (!isAnOptionalNode) {
                        showRequiredFieldAlert(PLEASE_ANSWER_FIELD_ALERT_TYPE);
                        wasNextButtonPressed = false;
                        hasUpdatedDecisionTrackerContainer = true;
                        return;
                    }
                }
                //                          else {
                currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any"
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "A,;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
                //                          }
            } else {
                //                        usbongAnswerContainer.addElement("A,"+myTextAreaScreenEditText.getText()+";");                     
                UsbongUtils.addElementToContainer(usbongAnswerContainer,
                        "A," + myTextAreaScreenEditText.getText() + ";", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
            }
        } else if (currScreen == UsbongConstants.TEXTAREA_WITH_ANSWER_SCREEN) {
            currUsbongNode = nextUsbongNodeIfYes;
            EditText myTextAreaScreenEditText = (EditText) findViewById(R.id.textarea_edittext);
            //if it's blank
            if (myTextAreaScreenEditText.getText().toString().trim().equals("")) {
                if (!UsbongUtils.IS_IN_DEBUG_MODE) {
                    if (!isAnOptionalNode) {
                        showRequiredFieldAlert(PLEASE_ANSWER_FIELD_ALERT_TYPE);
                        wasNextButtonPressed = false;
                        hasUpdatedDecisionTrackerContainer = true;
                        return;
                    }
                }
                currUsbongNode = nextUsbongNodeIfYes; //choose Yes if "Any"
                UsbongUtils.addElementToContainer(usbongAnswerContainer,
                        "A," + myTextAreaScreenEditText.getText().toString().trim() + ";",
                        usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
            } else {
                /*                        
                  if (myTextAreaWithAnswerScreenAnswer.equals(myTextAreaScreenEditText.getText().toString().trim())) {
                   currUsbongNode = nextUsbongNodeIfYes;    
                    UsbongUtils.addElementToContainer(usbongAnswerContainer, "Y,"+myTextAreaScreenEditText.getText().toString().trim()+";", usbongAnswerContainerCounter);
                  }
                  else {
                   currUsbongNode = nextUsbongNodeIfNo;                                               
                    UsbongUtils.addElementToContainer(usbongAnswerContainer, "N,"+myTextAreaScreenEditText.getText().toString().trim()+";", usbongAnswerContainerCounter);
                  }                    
                */
                //added by Mike, Jan. 27, 2014
                Vector<String> myPossibleAnswers = new Vector<String>();
                StringTokenizer myPossibleAnswersStringTokenizer = new StringTokenizer(
                        myTextAreaWithAnswerScreenAnswer, "||");
                if (myPossibleAnswersStringTokenizer != null) {
                    while (myPossibleAnswersStringTokenizer.hasMoreTokens()) { //get last element (i.e. Mike in "textAreaWithAnswer~Who is the founder of Usbong (nickname)?Answer=Mike||mike")
                        myPossibleAnswers.add(myPossibleAnswersStringTokenizer.nextToken());
                    }
                }
                int size = myPossibleAnswers.size();
                for (int i = 0; i < size; i++) {
                    //                           Log.d(">>>>>>myPossibleAnswers: ",myPossibleAnswers.elementAt(i));
                    if (myPossibleAnswers.elementAt(i)
                            .equals(myTextAreaScreenEditText.getText().toString().trim())) {
                        currUsbongNode = nextUsbongNodeIfYes;
                        UsbongUtils.addElementToContainer(usbongAnswerContainer,
                                "Y," + myTextAreaScreenEditText.getText().toString().trim() + ";",
                                usbongAnswerContainerCounter);
                        break;
                    }

                    if (i == size - 1) { //if this is the last element in the vector
                        currUsbongNode = nextUsbongNodeIfNo;
                        UsbongUtils.addElementToContainer(usbongAnswerContainer,
                                "N," + myTextAreaScreenEditText.getText().toString().trim() + ";",
                                usbongAnswerContainerCounter);
                    }
                }
                usbongAnswerContainerCounter++;
                initParser();
            }
        } else if (currScreen == UsbongConstants.GPS_LOCATION_SCREEN) {
            currUsbongNode = nextUsbongNodeIfYes; //= nextIMCIQuestionIfNo will also do
            TextView myLongitudeTextView = (TextView) findViewById(R.id.longitude_textview);
            TextView myLatitudeTextView = (TextView) findViewById(R.id.latitude_textview);

            //                  usbongAnswerContainer.addElement(myLongitudeTextView.getText()+","+myLatitudeTextView.getText()+";");                     
            UsbongUtils.addElementToContainer(usbongAnswerContainer,
                    "A," + myLongitudeTextView.getText() + "," + myLatitudeTextView.getText() + ";",
                    usbongAnswerContainerCounter);
            usbongAnswerContainerCounter++;

            initParser();

        } else if (currScreen == UsbongConstants.SIMPLE_ENCRYPT_SCREEN) {
            EditText myPinEditText = (EditText) findViewById(R.id.pin_edittext);

            if (myPinEditText.getText().toString().length() != 4) {
                String message = "";
                if (currLanguageBeingUsed == UsbongUtils.LANGUAGE_FILIPINO) {
                    message = (String) getResources().getText(R.string.Usbong4DigitsPinAlertMessageFILIPINO);
                } else if (currLanguageBeingUsed == UsbongUtils.LANGUAGE_JAPANESE) {
                    message = (String) getResources().getText(R.string.Usbong4DigitsPinAlertMessageJAPANESE);
                } else { //if (udtea.currLanguageBeingUsed==UsbongUtils.LANGUAGE_ENGLISH) {
                    message = (String) getResources().getText(R.string.Usbong4DigitsPinAlertMessageENGLISH);
                }

                new AlertDialog.Builder(UsbongDecisionTreeEngineActivity.this).setTitle("Hey!")
                        .setMessage(message).setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        }).show();
            } else {
                int yourKey = Integer.parseInt(myPinEditText.getText().toString());
                currUsbongNode = nextUsbongNodeIfYes; //= nextIMCIQuestionIfNo will also do

                UsbongUtils.addElementToContainer(usbongAnswerContainer, "A;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                //                  Log.d(">>>>>>>start encode","encode");
                for (int i = 0; i < usbongAnswerContainerCounter; i++) {
                    try {
                        usbongAnswerContainer.set(i, UsbongUtils.performSimpleFileEncrypt(yourKey,
                                usbongAnswerContainer.elementAt(i)));
                        //                        Log.d(">>>>>>"+i,""+usbongAnswerContainer.get(i));
                        //                        Log.d(">>>decoded"+i,""+UsbongUtils.performSimpleFileDecode(yourKey, usbongAnswerContainer.get(i)));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                initParser();
            }
        } else if (currScreen == UsbongConstants.DATE_SCREEN) {
            currUsbongNode = nextUsbongNodeIfYes;
            //added by Mike, 13 Oct. 2015
            DatePicker myDatePicker = (DatePicker) findViewById(R.id.date_picker);
            UsbongUtils.addElementToContainer(usbongAnswerContainer, "A," + myDatePicker.getMonth()
                    + myDatePicker.getDayOfMonth() + "," + myDatePicker.getYear() + ";",
                    usbongAnswerContainerCounter);

            /*                   
                         Spinner dateMonthSpinner = (Spinner) findViewById(R.id.date_month_spinner);
                          Spinner dateDaySpinner = (Spinner) findViewById(R.id.date_day_spinner);
                          EditText myDateYearEditText = (EditText)findViewById(R.id.date_edittext);
            //             usbongAnswerContainer.addElement("A,"+monthAdapter.getItem(dateMonthSpinner.getSelectedItemPosition()).toString() +
            //                                      dayAdapter.getItem(dateDaySpinner.getSelectedItemPosition()).toString() + "," +
            //                                      myDateYearEditText.getText().toString()+";");                         
                         UsbongUtils.addElementToContainer(usbongAnswerContainer, "A,"+monthAdapter.getItem(dateMonthSpinner.getSelectedItemPosition()).toString() +
                              dayAdapter.getItem(dateDaySpinner.getSelectedItemPosition()).toString() + "," +
                              myDateYearEditText.getText().toString()+";", usbongAnswerContainerCounter);
            */
            usbongAnswerContainerCounter++;

            //             System.out.println(">>>>>>>>>>>>>Date screen: "+usbongAnswerContainer.lastElement());
            initParser();
        } else if (currScreen == UsbongConstants.TIMESTAMP_DISPLAY_SCREEN) {
            currUsbongNode = nextUsbongNodeIfYes;
            UsbongUtils.addElementToContainer(usbongAnswerContainer, timestampString + ";",
                    usbongAnswerContainerCounter);
            usbongAnswerContainerCounter++;

            initParser();
        } else if (currScreen == UsbongConstants.QR_CODE_READER_SCREEN) {
            currUsbongNode = nextUsbongNodeIfYes; //= nextIMCIQuestionIfNo will also do

            if (!myQRCodeContent.equals("")) {
                //                      usbongAnswerContainer.addElement("Y,"+myQRCodeContent+";");                     
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "Y," + myQRCodeContent + ";",
                        usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;
            } else {
                //                      usbongAnswerContainer.addElement("N;");                                           
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "N;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;
            }
            initParser();
        } else if ((currScreen == UsbongConstants.DCAT_SUMMARY_SCREEN)) {
            currUsbongNode = nextUsbongNodeIfYes; //= nextIMCIQuestionIfNo will also do
            /*
            LinearLayout myDCATSummaryLinearLayout = (LinearLayout)findViewById(R.id.dcat_summary_linearlayout);
            int total = myDCATSummaryLinearLayout.getChildCount();
                    
                              StringBuffer dcatSummary= new StringBuffer();
            for (int i=0; i<total; i++) {
               dcatSummary.append(((TextView) myDCATSummaryLinearLayout.getChildAt(i)).getText().toString());
            }
            */
            //                   UsbongUtils.addElementToContainer(usbongAnswerContainer, "dcat_end;", usbongAnswerContainerCounter);
            UsbongUtils.addElementToContainer(usbongAnswerContainer,
                    "dcat_end," + myDcatSummaryStringBuffer.toString() + ";", usbongAnswerContainerCounter);
            usbongAnswerContainerCounter++;

            initParser();
        }

        else { //TODO: do this for now                
            currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any"
            //                  usbongAnswerContainer.addElement("A;");                                             
            UsbongUtils.addElementToContainer(usbongAnswerContainer, "A;", usbongAnswerContainerCounter);
            usbongAnswerContainerCounter++;

            initParser();
        }
    }
}

From source file:fiskinfoo.no.sintef.fiskinfoo.Implementation.UtilityOnClickListeners.java

@Override
public OnClickListener getSubscriptionCheckBoxOnClickListener(final PropertyDescription subscription,
        final Subscription activeSubscription, final User user) {
    return new OnClickListener() {
        @Override//  w  w w  .ja  va  2s . co  m
        public void onClick(final View v) {
            UtilityRowsInterface utilityRowsInterface = new UtilityRows();
            final FiskInfoUtility fiskInfoUtility = new FiskInfoUtility();

            final Dialog dialog;

            int iconId = fiskInfoUtility.subscriptionApiNameToIconId(subscription.ApiName);

            if (iconId != -1) {
                dialog = new UtilityDialogs().getDialogWithTitleIcon(v.getContext(),
                        R.layout.dialog_manage_subscription, subscription.Name, iconId);
            } else {
                dialog = new UtilityDialogs().getDialog(v.getContext(), R.layout.dialog_manage_subscription,
                        subscription.Name);
            }

            final Switch subscribedSwitch = (Switch) dialog.findViewById(R.id.manage_subscription_switch);
            final LinearLayout formatsContainer = (LinearLayout) dialog
                    .findViewById(R.id.manage_subscription_formats_container);
            final LinearLayout intervalsContainer = (LinearLayout) dialog
                    .findViewById(R.id.manage_subscription_intervals_container);
            final EditText subscriptionEmailEditText = (EditText) dialog
                    .findViewById(R.id.manage_subscription_email_edit_text);

            final Button subscribeButton = (Button) dialog.findViewById(R.id.manage_subscription_update_button);
            Button cancelButton = (Button) dialog.findViewById(R.id.manage_subscription_cancel_button);

            final boolean isSubscribed = activeSubscription != null;
            final Map<String, String> subscriptionFrequencies = new HashMap<>();

            dialog.setTitle(subscription.Name);

            if (isSubscribed) {
                subscriptionEmailEditText.setText(activeSubscription.SubscriptionEmail);

                subscribedSwitch.setVisibility(View.VISIBLE);
                subscribedSwitch.setChecked(true);
                subscribedSwitch
                        .setText(v.getResources().getString(R.string.manage_subscription_subscription_active));

                subscribedSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        System.out.println("This is checked:" + isChecked);
                        String switchText = isChecked
                                ? v.getResources().getString(R.string.manage_subscription_subscription_active)
                                : v.getResources()
                                        .getString(R.string.manage_subscription_subscription_cancellation);
                        subscribedSwitch.setText(switchText);
                    }
                });
            } else {
                subscriptionEmailEditText.setText(user.getUsername());
            }

            for (String format : subscription.Formats) {
                final RadioButtonRow row = utilityRowsInterface.getRadioButtonRow(v.getContext(), format);
                if (isSubscribed && activeSubscription.FileFormatType.equals(format)) {
                    row.setSelected(true);
                }

                formatsContainer.addView(row.getView());
            }

            for (String interval : subscription.SubscriptionInterval) {
                final RadioButtonRow row = utilityRowsInterface.getRadioButtonRow(v.getContext(),
                        SubscriptionInterval.getType(interval).toString());

                if (activeSubscription != null) {
                    row.setSelected(activeSubscription.SubscriptionIntervalName.equals(interval));
                }

                subscriptionFrequencies.put(SubscriptionInterval.getType(interval).toString(), interval);
                intervalsContainer.addView(row.getView());
            }

            if (intervalsContainer.getChildCount() == 1) {
                ((RadioButton) intervalsContainer.getChildAt(0)
                        .findViewById(R.id.radio_button_row_radio_button)).setChecked(true);
            }

            subscribeButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View subscribeButton) {
                    String subscriptionFormat = null;
                    String subscriptionInterval = null;
                    String subscriptionEmail;

                    BarentswatchApi barentswatchApi = new BarentswatchApi();
                    barentswatchApi.setAccesToken(user.getToken());
                    final IBarentswatchApi api = barentswatchApi.getApi();

                    for (int i = 0; i < formatsContainer.getChildCount(); i++) {
                        if (((RadioButton) formatsContainer.getChildAt(i)
                                .findViewById(R.id.radio_button_row_radio_button)).isChecked()) {
                            subscriptionFormat = ((TextView) formatsContainer.getChildAt(i)
                                    .findViewById(R.id.radio_button_row_text_view)).getText().toString();
                            break;
                        }
                    }

                    if (subscriptionFormat == null) {
                        Toast.makeText(v.getContext(),
                                v.getContext().getString(R.string.choose_subscription_format),
                                Toast.LENGTH_LONG).show();
                        return;
                    }

                    for (int i = 0; i < intervalsContainer.getChildCount(); i++) {
                        if (((RadioButton) intervalsContainer.getChildAt(i)
                                .findViewById(R.id.radio_button_row_radio_button)).isChecked()) {
                            subscriptionInterval = ((TextView) intervalsContainer.getChildAt(i)
                                    .findViewById(R.id.radio_button_row_text_view)).getText().toString();
                            break;
                        }
                    }

                    if (subscriptionInterval == null) {
                        Toast.makeText(v.getContext(),
                                v.getContext().getString(R.string.choose_subscription_interval),
                                Toast.LENGTH_LONG).show();
                        return;
                    }

                    subscriptionEmail = subscriptionEmailEditText.getText().toString();

                    if (!(new FiskInfoUtility().isEmailValid(subscriptionEmail))) {
                        Toast.makeText(v.getContext(), v.getContext().getString(R.string.error_invalid_email),
                                Toast.LENGTH_LONG).show();
                        return;
                    }

                    if (isSubscribed) {
                        if (subscribedSwitch.isChecked()) {
                            if (!(subscriptionFormat.equals(activeSubscription.FileFormatType)
                                    && activeSubscription.SubscriptionIntervalName
                                            .equals(subscriptionFrequencies.get(subscriptionInterval))
                                    && user.getUsername().equals(subscriptionEmail))) {
                                SubscriptionSubmitObject updatedSubscription = new SubscriptionSubmitObject(
                                        subscription.ApiName, subscriptionFormat, user.getUsername(),
                                        user.getUsername(), subscriptionFrequencies.get(subscriptionInterval));
                                Subscription newSubscriptionObject = api.updateSubscription(
                                        String.valueOf(activeSubscription.Id), updatedSubscription);

                                if (newSubscriptionObject != null) {
                                    ((CheckBox) v).setChecked(true);
                                }
                            }
                        } else {
                            Response response = api.deleteSubscription(String.valueOf(activeSubscription.Id));

                            if (response.getStatus() == 204) {
                                ((CheckBox) v).setChecked(false);
                                Toast.makeText(v.getContext(), R.string.subscription_update_successful,
                                        Toast.LENGTH_LONG).show();
                            } else {
                                Toast.makeText(v.getContext(), R.string.subscription_update_failed,
                                        Toast.LENGTH_LONG).show();
                            }
                        }
                    } else {
                        SubscriptionSubmitObject newSubscription = new SubscriptionSubmitObject(
                                subscription.ApiName, subscriptionFormat, user.getUsername(),
                                user.getUsername(), subscriptionFrequencies.get(subscriptionInterval));

                        Subscription response = api.setSubscription(newSubscription);

                        if (response != null) {
                            ((CheckBox) v).setChecked(true);
                            // TODO: add to "Mine abonnementer"
                            Toast.makeText(v.getContext(), R.string.subscription_update_successful,
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(v.getContext(), R.string.subscription_update_failed,
                                    Toast.LENGTH_LONG).show();
                        }
                    }

                    dialog.dismiss();
                }
            });

            cancelButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View cancelButton) {
                    ((CheckBox) v).setChecked(isSubscribed);

                    dialog.dismiss();
                }
            });

            dialog.show();

        }
    };
}

From source file:usbong.android.retrocc.UsbongDecisionTreeEngineActivity.java

public void processNextButtonPressed() {
    wasNextButtonPressed = true;//from   w ww .  j a  va  2  s . c  o m
    hasUpdatedDecisionTrackerContainer = false;

    //edited by Mike, 20160417
    if ((mTts != null) && (mTts.isSpeaking())) {
        mTts.stop();
    }
    //edited by Mike, 20160417
    if ((myMediaPlayer != null) && (myMediaPlayer.isPlaying())) {
        myMediaPlayer.stop();
    }

    if (currAudioRecorder != null) {
        try {
            //if stop button is pressable
            if (stopButton.isEnabled()) {
                currAudioRecorder.stop();
            }
            if (currAudioRecorder.isPlaying()) {
                currAudioRecorder.stopPlayback();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        String path = currAudioRecorder.getPath();
        //               System.out.println(">>>>>>>>>>>>>>>>>>>currAudioRecorder: "+currAudioRecorder);
        if (!attachmentFilePaths.contains(path)) {
            attachmentFilePaths.add(path);
            //                  System.out.println(">>>>>>>>>>>>>>>>adding path: "+path);
        }
    }

    //END_STATE_SCREEN = last screen
    if (currScreen == UsbongConstants.END_STATE_SCREEN) {
        int usbongAnswerContainerSize = usbongAnswerContainer.size();
        StringBuffer outputStringBuffer = new StringBuffer();
        for (int i = 0; i < usbongAnswerContainerSize; i++) {
            outputStringBuffer.append(usbongAnswerContainer.elementAt(i));
        }

        myOutputDirectory = UsbongUtils.getDateTimeStamp() + "/";
        if (UsbongUtils.STORE_OUTPUT) {
            try {
                UsbongUtils.createNewOutputFolderStructure();
            } catch (Exception e) {
                e.printStackTrace();
            }
            UsbongUtils.storeOutputInSDCard(
                    UsbongUtils.BASE_FILE_PATH + myOutputDirectory + UsbongUtils.getDateTimeStamp() + ".csv",
                    outputStringBuffer.toString());
        } else {
            UsbongUtils.deleteRecursive(new File(UsbongUtils.BASE_FILE_PATH + myOutputDirectory));
        }

        //wasNextButtonPressed=false; //no need to make this true, because this is the last node
        hasUpdatedDecisionTrackerContainer = true;

        /*
        //send to server
        UsbongUtils.performFileUpload(UsbongUtils.BASE_FILE_PATH + myOutputDirectory + UsbongUtils.getTimeStamp() + ".csv");
                 
        //send to email
        Intent emailIntent = UsbongUtils.performEmailProcess(UsbongUtils.BASE_FILE_PATH + myOutputDirectory + UsbongUtils.getTimeStamp() + ".csv", attachmentFilePaths);
        emailIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        //                emailIntent.addFlags(RESULT_OK);
        startActivityForResult(Intent.createChooser(emailIntent, "Email:"),EMAIL_SENDING_SUCCESS);
        */

        //added by Mike, Sept. 10, 2014
        UsbongUtils.clearTempFolder();

        //added by Mike, 20160415
        if (UsbongUtils.IS_IN_AUTO_LOOP_MODE) {
            //added by Mike, 20161117
            AppRater.showRateDialog(this);

            isAutoLoopedTree = true;
            initParser(myTree);
            return;
        } else {
            //return to main activity
            finish();
            //added by Mike, 20161117
            Intent toUsbongMainActivityIntent = new Intent(UsbongDecisionTreeEngineActivity.this,
                    UsbongMainActivity.class);
            toUsbongMainActivityIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            toUsbongMainActivityIntent.putExtra("completed_tree", "true");
            startActivity(toUsbongMainActivityIntent);
        }
    } else {
        if (currScreen == UsbongConstants.YES_NO_DECISION_SCREEN) {
            RadioButton myYesRadioButton = (RadioButton) findViewById(R.id.yes_radiobutton);
            RadioButton myNoRadioButton = (RadioButton) findViewById(R.id.no_radiobutton);

            if (myYesRadioButton.isChecked()) {
                currUsbongNode = nextUsbongNodeIfYes;

                UsbongUtils.addElementToContainer(usbongAnswerContainer, "Y;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
            } else if (myNoRadioButton.isChecked()) {
                currUsbongNode = nextUsbongNodeIfNo;
                //                     usbongAnswerContainer.addElement("N;");                                             
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "N;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
            } else { //if no radio button was checked                       
                if (!UsbongUtils.IS_IN_DEBUG_MODE) {
                    if (!isAnOptionalNode) {
                        showRequiredFieldAlert(PLEASE_CHOOSE_AN_ANSWER_ALERT_TYPE);
                        wasNextButtonPressed = false;
                        hasUpdatedDecisionTrackerContainer = true;
                        return;
                    }
                }
                currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any"
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "A;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
            }
        } else if (currScreen == UsbongConstants.SEND_TO_WEBSERVER_SCREEN) {
            RadioButton myYesRadioButton = (RadioButton) findViewById(R.id.yes_radiobutton);
            RadioButton myNoRadioButton = (RadioButton) findViewById(R.id.no_radiobutton);

            if (myYesRadioButton.isChecked()) {
                currUsbongNode = nextUsbongNodeIfYes;
                //                     usbongAnswerContainer.addElement("Y;");         
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "Y;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                decisionTrackerContainer.addElement(usbongAnswerContainer.lastElement());
                //                     wasNextButtonPressed=false; //no need to make this true, because "Y;" has already been added to decisionTrackerContainer
                hasUpdatedDecisionTrackerContainer = true;

                //edited by Mike, March 4, 2013
                //"save" the output into the SDCard as "output.txt"
                //                      int usbongAnswerContainerSize = usbongAnswerContainer.size();
                int usbongAnswerContainerSize = usbongAnswerContainerCounter;

                StringBuffer outputStringBuffer = new StringBuffer();
                for (int i = 0; i < usbongAnswerContainerSize; i++) {
                    outputStringBuffer.append(usbongAnswerContainer.elementAt(i));
                }

                myOutputDirectory = UsbongUtils.getDateTimeStamp() + "/";
                try {
                    UsbongUtils.createNewOutputFolderStructure();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                UsbongUtils.storeOutputInSDCard(UsbongUtils.BASE_FILE_PATH + myOutputDirectory
                        + UsbongUtils.getDateTimeStamp() + ".csv", outputStringBuffer.toString());

                //send to server
                UsbongUtils.performFileUpload(UsbongUtils.BASE_FILE_PATH + myOutputDirectory
                        + UsbongUtils.getDateTimeStamp() + ".csv");
            } else if (myNoRadioButton.isChecked()) {
                currUsbongNode = nextUsbongNodeIfNo;
                //                     usbongAnswerContainer.addElement("N;");                                             
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "N;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;
            } else { //if no radio button was checked                       
                if (!UsbongUtils.IS_IN_DEBUG_MODE) {
                    if (!isAnOptionalNode) {
                        showRequiredFieldAlert(PLEASE_CHOOSE_AN_ANSWER_ALERT_TYPE);
                        wasNextButtonPressed = false;
                        hasUpdatedDecisionTrackerContainer = true;
                        return;
                    }
                }
                //                       else {
                currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any"
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "A;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;
                //                      initParser();            
            }
            initParser();
        } else if (currScreen == UsbongConstants.SEND_TO_CLOUD_BASED_SERVICE_SCREEN) {
            RadioButton myYesRadioButton = (RadioButton) findViewById(R.id.yes_radiobutton);
            RadioButton myNoRadioButton = (RadioButton) findViewById(R.id.no_radiobutton);

            if (myYesRadioButton.isChecked()) {
                currUsbongNode = nextUsbongNodeIfYes;
                //                     usbongAnswerContainer.addElement("Y;");                                             
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "Y;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                decisionTrackerContainer.addElement(usbongAnswerContainer.lastElement());
                //                     wasNextButtonPressed=false; //no need to make this true, because "Y;" has already been added to decisionTrackerContainer
                hasUpdatedDecisionTrackerContainer = true;

                StringBuffer sb = new StringBuffer();
                for (int i = 0; i < decisionTrackerContainer.size(); i++) {
                    sb.append(decisionTrackerContainer.elementAt(i));
                }
                Log.d(">>>>>>>>>>>>>decisionTrackerContainer", sb.toString());

                //edited by Mike, March 4, 2013
                //"save" the output into the SDCard as "output.txt"
                //                      int usbongAnswerContainerSize = usbongAnswerContainer.size();
                int usbongAnswerContainerSize = usbongAnswerContainerCounter;

                StringBuffer outputStringBuffer = new StringBuffer();
                for (int i = 0; i < usbongAnswerContainerSize; i++) {
                    outputStringBuffer.append(usbongAnswerContainer.elementAt(i));
                }

                myOutputDirectory = UsbongUtils.getDateTimeStamp() + "/";
                try {
                    UsbongUtils.createNewOutputFolderStructure();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                UsbongUtils.storeOutputInSDCard(UsbongUtils.BASE_FILE_PATH + myOutputDirectory
                        + UsbongUtils.getDateTimeStamp() + ".csv", outputStringBuffer.toString());

                //send to cloud-based service
                Intent sendToCloudBasedServiceIntent = UsbongUtils
                        .performSendToCloudBasedServiceProcess(UsbongUtils.BASE_FILE_PATH + myOutputDirectory
                                + UsbongUtils.getDateTimeStamp() + ".csv", attachmentFilePaths);
                /*emailIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                */
                //                      emailIntent.addFlags(RESULT_OK);
                //                      startActivityForResult(Intent.createChooser(emailIntent, "Email:"),EMAIL_SENDING_SUCCESS);
                //answer from Llango J, stackoverflow
                //Reference: http://stackoverflow.com/questions/7479883/problem-with-sending-email-goes-back-to-previous-activity;
                //last accessed: 22 Oct. 2012
                startActivity(Intent.createChooser(sendToCloudBasedServiceIntent, "Email Book Request:"));
            } else if (myNoRadioButton.isChecked()) {
                currUsbongNode = nextUsbongNodeIfNo;
                //                     usbongAnswerContainer.addElement("N;");                                             
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "N;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;
            } else { //if no radio button was checked                       
                if (!UsbongUtils.IS_IN_DEBUG_MODE) {
                    if (!isAnOptionalNode) {
                        showRequiredFieldAlert(PLEASE_CHOOSE_AN_ANSWER_ALERT_TYPE);
                        wasNextButtonPressed = false;
                        hasUpdatedDecisionTrackerContainer = true;
                        return;
                    }
                }
                //                       else {
                currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any"
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "A;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;
                //                      initParser();            

                /*
                                       if (!isAnOptionalNode) {
                  showRequiredFieldAlert(PLEASE_CHOOSE_AN_ANSWER_ALERT_TYPE);
                 wasNextButtonPressed=false;
                 hasUpdatedDecisionTrackerContainer=true;
                         
                 return;
                                       }
                                       else {
                 currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any"
                //                        usbongAnswerContainer.addElement("A;");                                             
                 UsbongUtils.addElementToContainer(usbongAnswerContainer, "A;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;
                        
                initParser();            
                                       }
                */
            }
            /*                    
                              currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any"
                              usbongAnswerContainer.addElement("Any;");                                             
            */
            initParser();
        } else if (currScreen == UsbongConstants.MULTIPLE_CHECKBOXES_SCREEN) {
            //                   requiredTotalCheckedBoxes   
            LinearLayout myMultipleCheckboxesLinearLayout = (LinearLayout) findViewById(
                    R.id.multiple_checkboxes_linearlayout);
            StringBuffer sb = new StringBuffer();
            int totalCheckedBoxes = 0;
            int totalCheckBoxChildren = myMultipleCheckboxesLinearLayout.getChildCount();
            //begin with i=1, because i=0 is for checkboxes_textview
            for (int i = 1; i < totalCheckBoxChildren; i++) {
                if (((CheckBox) myMultipleCheckboxesLinearLayout.getChildAt(i)).isChecked()) {
                    totalCheckedBoxes++;
                    sb.append("," + (i - 1)); //do a (i-1) so that i starts with 0 for the checkboxes (excluding checkboxes_textview) to maintain consistency with the other components
                }
            }

            if (totalCheckedBoxes >= requiredTotalCheckedBoxes) {
                currUsbongNode = nextUsbongNodeIfYes;
                sb.insert(0, "Y"); //insert in front of stringBuffer
                sb.append(";");
            } else {
                currUsbongNode = nextUsbongNodeIfNo;
                sb.delete(0, sb.length());
                sb.append("N,;"); //make sure to add the comma
            }
            //                   usbongAnswerContainer.addElement(sb.toString());
            UsbongUtils.addElementToContainer(usbongAnswerContainer, sb.toString(),
                    usbongAnswerContainerCounter);
            usbongAnswerContainerCounter++;

            initParser();
        } else if (currScreen == UsbongConstants.MULTIPLE_RADIO_BUTTONS_SCREEN) {
            currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any"
            RadioGroup myRadioGroup = (RadioGroup) findViewById(R.id.multiple_radio_buttons_radiogroup);

            //                   if (UsbongUtils.IS_IN_DEBUG_MODE==false) {
            if (myRadioGroup.getCheckedRadioButtonId() == -1) { //no radio button checked
                if (!UsbongUtils.IS_IN_DEBUG_MODE) {
                    if (!isAnOptionalNode) {
                        showRequiredFieldAlert(PLEASE_CHOOSE_AN_ANSWER_ALERT_TYPE);
                        wasNextButtonPressed = false;
                        hasUpdatedDecisionTrackerContainer = true;
                        return;
                    }
                }
                //                          else {
                currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any"
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "A;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
                //                          }
            } else {
                //                         usbongAnswerContainer.addElement(myRadioGroup.getCheckedRadioButtonId()+";");
                UsbongUtils.addElementToContainer(usbongAnswerContainer,
                        myRadioGroup.getCheckedRadioButtonId() + ";", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
            }
            //                   }
            /*                   
                               else {
            //                      usbongAnswerContainer.addElement(myRadioGroup.getCheckedRadioButtonId()+";");
              UsbongUtils.addElementToContainer(usbongAnswerContainer, myRadioGroup.getCheckedRadioButtonId()+";", usbongAnswerContainerCounter);
             usbongAnswerContainerCounter++;
                      
              initParser();                      
                               }
            */
        } else if (currScreen == UsbongConstants.MULTIPLE_RADIO_BUTTONS_WITH_ANSWER_SCREEN) {
            currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any"
            RadioGroup myRadioGroup = (RadioGroup) findViewById(R.id.multiple_radio_buttons_radiogroup);

            /*                   if (UsbongUtils.IS_IN_DEBUG_MODE==false) {
             */
            if (myRadioGroup.getCheckedRadioButtonId() == -1) { //no radio button checked                                                  
                if (!UsbongUtils.IS_IN_DEBUG_MODE) {
                    if (!isAnOptionalNode) {
                        showRequiredFieldAlert(PLEASE_CHOOSE_AN_ANSWER_ALERT_TYPE);
                        wasNextButtonPressed = false;
                        hasUpdatedDecisionTrackerContainer = true;
                        return;
                    }
                }
                //                          else {
                currUsbongNode = nextUsbongNodeIfYes; //choose Yes if "Any"
                UsbongUtils.addElementToContainer(usbongAnswerContainer,
                        "A," + myRadioGroup.getCheckedRadioButtonId() + ";", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
                //                          }
            } else {
                if (myMultipleRadioButtonsWithAnswerScreenAnswer
                        .equals("" + myRadioGroup.getCheckedRadioButtonId())) {
                    currUsbongNode = nextUsbongNodeIfYes;
                    UsbongUtils.addElementToContainer(usbongAnswerContainer,
                            "Y," + myRadioGroup.getCheckedRadioButtonId() + ";", usbongAnswerContainerCounter);
                } else {
                    currUsbongNode = nextUsbongNodeIfNo;
                    UsbongUtils.addElementToContainer(usbongAnswerContainer,
                            "N," + myRadioGroup.getCheckedRadioButtonId() + ";", usbongAnswerContainerCounter);
                }

                usbongAnswerContainerCounter++;
                initParser();
            }
        } else if (currScreen == UsbongConstants.LINK_SCREEN) {
            RadioGroup myRadioGroup = (RadioGroup) findViewById(R.id.multiple_radio_buttons_radiogroup);

            try {
                currUsbongNode = UsbongUtils.getLinkFromRadioButton(
                        radioButtonsContainer.elementAt(myRadioGroup.getCheckedRadioButtonId()));
            } catch (Exception e) {
                //if the user hasn't ticked any radio button yet
                //put the currUsbongNode to default
                currUsbongNode = UsbongUtils.getLinkFromRadioButton(nextUsbongNodeIfYes); //nextUsbongNodeIfNo will also do, since this is "Any"
                //of course, showPleaseAnswerAlert() will be called                        
            }

            //                   Log.d(">>>>>>>>>>currUsbongNode",currUsbongNode);
            if (myRadioGroup.getCheckedRadioButtonId() == -1) { //no radio button checked
                //                         if (!UsbongUtils.IS_IN_DEBUG_MODE) {
                if (!isAnOptionalNode) {
                    showRequiredFieldAlert(PLEASE_CHOOSE_AN_ANSWER_ALERT_TYPE);
                    wasNextButtonPressed = false;
                    hasUpdatedDecisionTrackerContainer = true;

                    return;
                }
                //                         }
                //                          else {
                currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any"
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "A;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
                //                          }
            } else {
                //                         usbongAnswerContainer.addElement(myRadioGroup.getCheckedRadioButtonId()+";");
                UsbongUtils.addElementToContainer(usbongAnswerContainer,
                        myRadioGroup.getCheckedRadioButtonId() + ";", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
            }
            /*                   }
                               else {
              usbongAnswerContainer.addElement(myRadioGroup.getCheckedRadioButtonId()+";");
               initParser();                      
                               }
            */
        } else if ((currScreen == UsbongConstants.TEXTFIELD_SCREEN)
                || (currScreen == UsbongConstants.TEXTFIELD_WITH_UNIT_SCREEN)
                || (currScreen == UsbongConstants.TEXTFIELD_NUMERICAL_SCREEN)) {
            currUsbongNode = nextUsbongNodeIfYes; //= nextIMCIQuestionIfNo will also do
            EditText myTextFieldScreenEditText = (EditText) findViewById(R.id.textfield_edittext);

            //                    if (UsbongUtils.IS_IN_DEBUG_MODE==false) {
            //if it's blank
            if (myTextFieldScreenEditText.getText().toString().trim().equals("")) {
                if (!UsbongUtils.IS_IN_DEBUG_MODE) {
                    if (!isAnOptionalNode) {
                        showRequiredFieldAlert(PLEASE_ANSWER_FIELD_ALERT_TYPE);
                        wasNextButtonPressed = false;
                        hasUpdatedDecisionTrackerContainer = true;
                        return;
                    }
                }
                //                          else {
                currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any"
                //                           usbongAnswerContainer.addElement("A;");                                             
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "A,;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
                //                          }
            } else {
                //added by Mike, 20170207
                TextView myTextFieldScreenTextView = (TextView) this.findViewById(R.id.textfield_textview);

                //Reference: http://stackoverflow.com/questions/23024831/android-shared-preferences-example
                //; last accessed: 20150609
                //answer by Elenasys
                //added by Mike, 20170207
                SharedPreferences.Editor editor = getSharedPreferences(UsbongConstants.MY_ACCOUNT_DETAILS,
                        MODE_PRIVATE).edit();
                if (myTextFieldScreenTextView.getText().toString().contains("First Name")) {
                    editor.putString("firstName", myTextFieldScreenEditText.getText().toString());
                } else if (myTextFieldScreenTextView.getText().toString().contains("Surname")) {
                    editor.putString("surname", myTextFieldScreenEditText.getText().toString());
                } else if (myTextFieldScreenTextView.getText().toString().contains("Contact Number")) {
                    editor.putString("contactNumber", myTextFieldScreenEditText.getText().toString());
                } else if (myTextFieldScreenTextView.getText().toString().contains("Shipping Address")) {
                    editor.putString("shippingAddress", myTextFieldScreenEditText.getText().toString());
                }
                editor.commit();

                //                        usbongAnswerContainer.addElement("A,"+myTextFieldScreenEditText.getText()+";");                     
                UsbongUtils.addElementToContainer(usbongAnswerContainer,
                        "A," + myTextFieldScreenEditText.getText() + ";", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
            }
        } else if (currScreen == UsbongConstants.TEXTFIELD_WITH_ANSWER_SCREEN) {
            currUsbongNode = nextUsbongNodeIfYes;
            EditText myTextFieldScreenEditText = (EditText) findViewById(R.id.textfield_edittext);
            //if it's blank
            if (myTextFieldScreenEditText.getText().toString().trim().equals("")) {
                if (!UsbongUtils.IS_IN_DEBUG_MODE) {
                    if (!isAnOptionalNode) {
                        showRequiredFieldAlert(PLEASE_ANSWER_FIELD_ALERT_TYPE);
                        wasNextButtonPressed = false;
                        hasUpdatedDecisionTrackerContainer = true;
                        return;
                    }
                }
                currUsbongNode = nextUsbongNodeIfYes; //choose Yes if "Any"
                UsbongUtils.addElementToContainer(usbongAnswerContainer,
                        "A," + myTextFieldScreenEditText.getText().toString().trim() + ";",
                        usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
            } else {
                //added by Mike, Jan. 27, 2014
                Vector<String> myPossibleAnswers = new Vector<String>();
                StringTokenizer myPossibleAnswersStringTokenizer = new StringTokenizer(
                        myTextFieldWithAnswerScreenAnswer, "||");
                if (myPossibleAnswersStringTokenizer != null) {
                    while (myPossibleAnswersStringTokenizer.hasMoreTokens()) { //get last element (i.e. Mike in "textFieldWithAnswer~Who is the founder of Usbong (nickname)?Answer=Mike")
                        myPossibleAnswers.add(myPossibleAnswersStringTokenizer.nextToken());
                    }
                }
                int size = myPossibleAnswers.size();
                for (int i = 0; i < size; i++) {
                    if (myPossibleAnswers.elementAt(i)
                            .equals(myTextFieldScreenEditText.getText().toString().trim())) {
                        currUsbongNode = nextUsbongNodeIfYes;
                        UsbongUtils.addElementToContainer(usbongAnswerContainer,
                                "Y," + myTextFieldScreenEditText.getText().toString().trim() + ";",
                                usbongAnswerContainerCounter);
                        break;
                    }

                    if (i == size - 1) { //if this is the last element in the vector
                        currUsbongNode = nextUsbongNodeIfNo;
                        UsbongUtils.addElementToContainer(usbongAnswerContainer,
                                "N," + myTextFieldScreenEditText.getText().toString().trim() + ";",
                                usbongAnswerContainerCounter);
                    }
                }
                /*                        
                  if (myTextFieldWithAnswerScreenAnswer.equals(myTextFieldScreenEditText.getText().toString().trim())) {
                   currUsbongNode = nextUsbongNodeIfYes;    
                    UsbongUtils.addElementToContainer(usbongAnswerContainer, "Y,"+myTextFieldScreenEditText.getText().toString().trim()+";", usbongAnswerContainerCounter);
                  }
                  else {
                   currUsbongNode = nextUsbongNodeIfNo;                                               
                    UsbongUtils.addElementToContainer(usbongAnswerContainer, "N,"+myTextFieldScreenEditText.getText().toString().trim()+";", usbongAnswerContainerCounter);
                  }                    
                */
                usbongAnswerContainerCounter++;
                initParser();
            }
        } else if ((currScreen == UsbongConstants.TEXTAREA_SCREEN)) {
            currUsbongNode = nextUsbongNodeIfYes; //= nextIMCIQuestionIfNo will also do
            EditText myTextAreaScreenEditText = (EditText) findViewById(R.id.textarea_edittext);

            //                    if (UsbongUtils.IS_IN_DEBUG_MODE==false) {
            //if it's blank
            if (myTextAreaScreenEditText.getText().toString().trim().equals("")) {
                if (!UsbongUtils.IS_IN_DEBUG_MODE) {
                    if (!isAnOptionalNode) {
                        showRequiredFieldAlert(PLEASE_ANSWER_FIELD_ALERT_TYPE);
                        wasNextButtonPressed = false;
                        hasUpdatedDecisionTrackerContainer = true;
                        return;
                    }
                }
                //                          else {
                currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any"
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "A,;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
                //                          }
            } else {
                //                        usbongAnswerContainer.addElement("A,"+myTextAreaScreenEditText.getText()+";");                     
                UsbongUtils.addElementToContainer(usbongAnswerContainer,
                        "A," + myTextAreaScreenEditText.getText() + ";", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
            }
        } else if (currScreen == UsbongConstants.TEXTAREA_WITH_ANSWER_SCREEN) {
            currUsbongNode = nextUsbongNodeIfYes;
            EditText myTextAreaScreenEditText = (EditText) findViewById(R.id.textarea_edittext);
            //if it's blank
            if (myTextAreaScreenEditText.getText().toString().trim().equals("")) {
                if (!UsbongUtils.IS_IN_DEBUG_MODE) {
                    if (!isAnOptionalNode) {
                        showRequiredFieldAlert(PLEASE_ANSWER_FIELD_ALERT_TYPE);
                        wasNextButtonPressed = false;
                        hasUpdatedDecisionTrackerContainer = true;
                        return;
                    }
                }
                currUsbongNode = nextUsbongNodeIfYes; //choose Yes if "Any"
                UsbongUtils.addElementToContainer(usbongAnswerContainer,
                        "A," + myTextAreaScreenEditText.getText().toString().trim() + ";",
                        usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                initParser();
            } else {
                /*                        
                  if (myTextAreaWithAnswerScreenAnswer.equals(myTextAreaScreenEditText.getText().toString().trim())) {
                   currUsbongNode = nextUsbongNodeIfYes;    
                    UsbongUtils.addElementToContainer(usbongAnswerContainer, "Y,"+myTextAreaScreenEditText.getText().toString().trim()+";", usbongAnswerContainerCounter);
                  }
                  else {
                   currUsbongNode = nextUsbongNodeIfNo;                                               
                    UsbongUtils.addElementToContainer(usbongAnswerContainer, "N,"+myTextAreaScreenEditText.getText().toString().trim()+";", usbongAnswerContainerCounter);
                  }                    
                */
                //added by Mike, Jan. 27, 2014
                Vector<String> myPossibleAnswers = new Vector<String>();
                StringTokenizer myPossibleAnswersStringTokenizer = new StringTokenizer(
                        myTextAreaWithAnswerScreenAnswer, "||");
                if (myPossibleAnswersStringTokenizer != null) {
                    while (myPossibleAnswersStringTokenizer.hasMoreTokens()) { //get last element (i.e. Mike in "textAreaWithAnswer~Who is the founder of Usbong (nickname)?Answer=Mike||mike")
                        myPossibleAnswers.add(myPossibleAnswersStringTokenizer.nextToken());
                    }
                }
                int size = myPossibleAnswers.size();
                for (int i = 0; i < size; i++) {
                    //                           Log.d(">>>>>>myPossibleAnswers: ",myPossibleAnswers.elementAt(i));
                    if (myPossibleAnswers.elementAt(i)
                            .equals(myTextAreaScreenEditText.getText().toString().trim())) {
                        currUsbongNode = nextUsbongNodeIfYes;
                        UsbongUtils.addElementToContainer(usbongAnswerContainer,
                                "Y," + myTextAreaScreenEditText.getText().toString().trim() + ";",
                                usbongAnswerContainerCounter);
                        break;
                    }

                    if (i == size - 1) { //if this is the last element in the vector
                        currUsbongNode = nextUsbongNodeIfNo;
                        UsbongUtils.addElementToContainer(usbongAnswerContainer,
                                "N," + myTextAreaScreenEditText.getText().toString().trim() + ";",
                                usbongAnswerContainerCounter);
                    }
                }
                usbongAnswerContainerCounter++;
                initParser();
            }
        } else if (currScreen == UsbongConstants.GPS_LOCATION_SCREEN) {
            currUsbongNode = nextUsbongNodeIfYes; //= nextIMCIQuestionIfNo will also do
            TextView myLongitudeTextView = (TextView) findViewById(R.id.longitude_textview);
            TextView myLatitudeTextView = (TextView) findViewById(R.id.latitude_textview);

            //                  usbongAnswerContainer.addElement(myLongitudeTextView.getText()+","+myLatitudeTextView.getText()+";");                     
            UsbongUtils.addElementToContainer(usbongAnswerContainer,
                    "A," + myLongitudeTextView.getText() + "," + myLatitudeTextView.getText() + ";",
                    usbongAnswerContainerCounter);
            usbongAnswerContainerCounter++;

            initParser();

        } else if (currScreen == UsbongConstants.SIMPLE_ENCRYPT_SCREEN) {
            EditText myPinEditText = (EditText) findViewById(R.id.pin_edittext);

            if (myPinEditText.getText().toString().length() != 4) {
                String message = "";
                if (currLanguageBeingUsed == UsbongUtils.LANGUAGE_FILIPINO) {
                    message = (String) getResources().getText(R.string.Usbong4DigitsPinAlertMessageFILIPINO);
                } else if (currLanguageBeingUsed == UsbongUtils.LANGUAGE_JAPANESE) {
                    message = (String) getResources().getText(R.string.Usbong4DigitsPinAlertMessageJAPANESE);
                } else { //if (udtea.currLanguageBeingUsed==UsbongUtils.LANGUAGE_ENGLISH) {
                    message = (String) getResources().getText(R.string.Usbong4DigitsPinAlertMessageENGLISH);
                }

                new AlertDialog.Builder(UsbongDecisionTreeEngineActivity.this).setTitle("Hey!")
                        .setMessage(message).setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        }).show();
            } else {
                int yourKey = Integer.parseInt(myPinEditText.getText().toString());
                currUsbongNode = nextUsbongNodeIfYes; //= nextIMCIQuestionIfNo will also do

                UsbongUtils.addElementToContainer(usbongAnswerContainer, "A;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;

                //                  Log.d(">>>>>>>start encode","encode");
                for (int i = 0; i < usbongAnswerContainerCounter; i++) {
                    try {
                        usbongAnswerContainer.set(i, UsbongUtils.performSimpleFileEncrypt(yourKey,
                                usbongAnswerContainer.elementAt(i)));
                        //                        Log.d(">>>>>>"+i,""+usbongAnswerContainer.get(i));
                        //                        Log.d(">>>decoded"+i,""+UsbongUtils.performSimpleFileDecode(yourKey, usbongAnswerContainer.get(i)));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                initParser();
            }
        } else if (currScreen == UsbongConstants.DATE_SCREEN) {
            currUsbongNode = nextUsbongNodeIfYes;
            Spinner dateMonthSpinner = (Spinner) findViewById(R.id.date_month_spinner);
            Spinner dateDaySpinner = (Spinner) findViewById(R.id.date_day_spinner);
            EditText myDateYearEditText = (EditText) findViewById(R.id.date_edittext);
            /*                   usbongAnswerContainer.addElement("A,"+monthAdapter.getItem(dateMonthSpinner.getSelectedItemPosition()).toString() +
                                    dayAdapter.getItem(dateDaySpinner.getSelectedItemPosition()).toString() + "," +
                                    myDateYearEditText.getText().toString()+";");                         
            */
            UsbongUtils.addElementToContainer(usbongAnswerContainer,
                    "A," + monthAdapter.getItem(dateMonthSpinner.getSelectedItemPosition()).toString()
                            + dayAdapter.getItem(dateDaySpinner.getSelectedItemPosition()).toString() + ","
                            + myDateYearEditText.getText().toString() + ";",
                    usbongAnswerContainerCounter);
            usbongAnswerContainerCounter++;

            //                   System.out.println(">>>>>>>>>>>>>Date screen: "+usbongAnswerContainer.lastElement());
            initParser();
        } else if (currScreen == UsbongConstants.TIMESTAMP_DISPLAY_SCREEN) {
            currUsbongNode = nextUsbongNodeIfYes;
            UsbongUtils.addElementToContainer(usbongAnswerContainer, timestampString + ";",
                    usbongAnswerContainerCounter);
            usbongAnswerContainerCounter++;

            initParser();
        } else if (currScreen == UsbongConstants.QR_CODE_READER_SCREEN) {
            currUsbongNode = nextUsbongNodeIfYes; //= nextIMCIQuestionIfNo will also do

            if (!myQRCodeContent.equals("")) {
                //                      usbongAnswerContainer.addElement("Y,"+myQRCodeContent+";");                     
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "Y," + myQRCodeContent + ";",
                        usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;
            } else {
                //                      usbongAnswerContainer.addElement("N;");                                           
                UsbongUtils.addElementToContainer(usbongAnswerContainer, "N;", usbongAnswerContainerCounter);
                usbongAnswerContainerCounter++;
            }
            initParser();
        } else if ((currScreen == UsbongConstants.DCAT_SUMMARY_SCREEN)) {
            currUsbongNode = nextUsbongNodeIfYes; //= nextIMCIQuestionIfNo will also do
            /*
            LinearLayout myDCATSummaryLinearLayout = (LinearLayout)findViewById(R.id.dcat_summary_linearlayout);
            int total = myDCATSummaryLinearLayout.getChildCount();
                    
                              StringBuffer dcatSummary= new StringBuffer();
            for (int i=0; i<total; i++) {
               dcatSummary.append(((TextView) myDCATSummaryLinearLayout.getChildAt(i)).getText().toString());
            }
            */
            //                   UsbongUtils.addElementToContainer(usbongAnswerContainer, "dcat_end;", usbongAnswerContainerCounter);
            UsbongUtils.addElementToContainer(usbongAnswerContainer,
                    "dcat_end," + myDcatSummaryStringBuffer.toString() + ";", usbongAnswerContainerCounter);
            usbongAnswerContainerCounter++;

            initParser();
        }

        else { //TODO: do this for now                
            currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any"
            //                  usbongAnswerContainer.addElement("A;");                                             
            UsbongUtils.addElementToContainer(usbongAnswerContainer, "A;", usbongAnswerContainerCounter);
            usbongAnswerContainerCounter++;

            initParser();
        }
    }
}

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

private void updateToolList(Set<Map.Entry<String, ArrayList<ToolEntry>>> tools,
        final LinearLayout toolContainer) {
    if (fiskInfoUtility.isNetworkAvailable(getActivity())) {
        List<ToolEntry> localTools = new ArrayList<>();
        final List<ToolEntry> unconfirmedRemovedTools = new ArrayList<>();
        final List<ToolEntry> synchedTools = new ArrayList<>();

        for (final Map.Entry<String, ArrayList<ToolEntry>> dateEntry : tools) {
            for (final ToolEntry toolEntry : dateEntry.getValue()) {
                if (toolEntry.getToolStatus() == ToolEntryStatus.STATUS_REMOVED) {
                    continue;
                } else if (toolEntry.getToolStatus() == ToolEntryStatus.STATUS_RECEIVED) {
                    synchedTools.add(toolEntry);
                } else if (!(toolEntry.getToolStatus() == ToolEntryStatus.STATUS_REMOVED_UNCONFIRMED)) {
                    localTools.add(toolEntry);
                } else {
                    unconfirmedRemovedTools.add(toolEntry);
                }//w  w  w .jav  a2  s.  com
            }
        }

        barentswatchApi.setAccesToken(user.getToken());

        Response response = barentswatchApi.getApi().geoDataDownload("fishingfacility", "JSON");

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

        byte[] toolData;
        try {
            toolData = FiskInfoUtility.toByteArray(response.getBody().in());
            JSONObject featureCollection = new JSONObject(new String(toolData));
            JSONArray jsonTools = featureCollection.getJSONArray("features");
            JSONArray matchedTools = new JSONArray();
            UserSettings settings = user.getSettings();

            for (int i = 0; i < jsonTools.length(); i++) {
                JSONObject tool = jsonTools.getJSONObject(i);
                boolean hasCopy = false;

                for (int j = 0; j < localTools.size(); j++) {
                    if (localTools.get(j).getToolId()
                            .equals(tool.getJSONObject("properties").getString("toolid"))) {
                        SimpleDateFormat sdfMilliSeconds = new SimpleDateFormat(
                                getString(R.string.datetime_format_yyyy_mm_dd_t_hh_mm_ss_sss),
                                Locale.getDefault());
                        SimpleDateFormat sdfMilliSecondsRemote = new SimpleDateFormat(
                                getString(R.string.datetime_format_yyyy_mm_dd_t_hh_mm_ss_sss),
                                Locale.getDefault());
                        SimpleDateFormat sdfRemote = new SimpleDateFormat(
                                getString(R.string.datetime_format_yyyy_mm_dd_t_hh_mm_ss), Locale.getDefault());

                        sdfMilliSeconds.setTimeZone(TimeZone.getTimeZone("UTC"));
                        /* Timestamps from BW seem to be one hour earlier than UTC/GMT?  */
                        sdfMilliSecondsRemote.setTimeZone(TimeZone.getTimeZone("GMT-1"));
                        sdfRemote.setTimeZone(TimeZone.getTimeZone("GMT-1"));
                        Date localLastUpdatedDateTime;
                        Date localUpdatedBySourceDateTime;
                        Date serverUpdatedDateTime;
                        Date serverUpdatedBySourceDateTime = null;
                        try {
                            localLastUpdatedDateTime = sdfMilliSeconds
                                    .parse(localTools.get(j).getLastChangedDateTime());
                            localUpdatedBySourceDateTime = sdfMilliSeconds
                                    .parse(localTools.get(j).getLastChangedBySource());

                            serverUpdatedDateTime = tool.getJSONObject("properties")
                                    .getString("lastchangeddatetime").length() == getResources()
                                            .getInteger(R.integer.datetime_without_milliseconds_length)
                                                    ? sdfRemote.parse(tool.getJSONObject("properties")
                                                            .getString("lastchangeddatetime"))
                                                    : sdfMilliSecondsRemote
                                                            .parse(tool.getJSONObject("properties")
                                                                    .getString("lastchangeddatetime"));

                            if (tool.getJSONObject("properties").has("lastchangedbysource")) {
                                serverUpdatedBySourceDateTime = tool.getJSONObject("properties")
                                        .getString("lastchangedbysource").length() == getResources()
                                                .getInteger(R.integer.datetime_without_milliseconds_length)
                                                        ? sdfRemote.parse(tool.getJSONObject("properties")
                                                                .getString("lastchangedbysource"))
                                                        : sdfMilliSecondsRemote
                                                                .parse(tool.getJSONObject("properties")
                                                                        .getString("lastchangedbysource"));
                            }

                            if ((localLastUpdatedDateTime.equals(serverUpdatedDateTime)
                                    || localLastUpdatedDateTime.before(serverUpdatedDateTime))
                                    && serverUpdatedBySourceDateTime != null
                                    && (localUpdatedBySourceDateTime.equals(serverUpdatedBySourceDateTime)
                                            || localUpdatedBySourceDateTime
                                                    .before(serverUpdatedBySourceDateTime))) {
                                localTools.get(j).updateFromGeoJson(tool, getActivity());

                                localTools.get(j).setToolStatus(ToolEntryStatus.STATUS_RECEIVED);
                            } else if (serverUpdatedBySourceDateTime != null
                                    && localUpdatedBySourceDateTime.after(serverUpdatedBySourceDateTime)) {
                                // TODO: Do nothing, local changes should be reported.

                            } else {
                                // TODO: what gives?
                            }

                        } catch (ParseException e) {
                            e.printStackTrace();
                        }

                        localTools.remove(j);
                        j--;

                        hasCopy = true;
                        break;
                    }
                }

                for (int j = 0; j < unconfirmedRemovedTools.size(); j++) {
                    if (unconfirmedRemovedTools.get(j).getToolId()
                            .equals(tool.getJSONObject("properties").getString("toolid"))) {
                        hasCopy = true;
                        unconfirmedRemovedTools.remove(j);
                        j--;
                    }
                }

                for (int j = 0; j < synchedTools.size(); j++) {
                    if (synchedTools.get(j).getToolId()
                            .equals(tool.getJSONObject("properties").getString("toolid"))) {
                        hasCopy = true;
                        synchedTools.remove(j);
                        j--;
                    }
                }

                if (!hasCopy && settings != null) {
                    if ((!settings.getVesselName().isEmpty()
                            && (FiskInfoUtility.ReplaceRegionalCharacters(settings.getVesselName())
                                    .equalsIgnoreCase(tool.getJSONObject("properties").getString("vesselname"))
                                    || settings.getVesselName().equalsIgnoreCase(
                                            tool.getJSONObject("properties").getString("vesselname"))))
                            && ((!settings.getIrcs().isEmpty() && settings.getIrcs().toUpperCase()
                                    .equals(tool.getJSONObject("properties").getString("ircs")))
                                    || (!settings.getMmsi().isEmpty() && settings.getMmsi()
                                            .equals(tool.getJSONObject("properties").getString("mmsi")))
                                    || (!settings.getImo().isEmpty() && settings.getImo()
                                            .equals(tool.getJSONObject("properties").getString("imo"))))) {
                        matchedTools.put(tool);
                    }
                }
            }

            if (matchedTools.length() > 0) {
                final Dialog dialog = dialogInterface.getDialog(getActivity(),
                        R.layout.dialog_confirm_tools_from_api, R.string.tool_confirmation);
                Button cancelButton = (Button) dialog.findViewById(R.id.dialog_bottom_cancel_button);
                Button addToolsButton = (Button) dialog.findViewById(R.id.dialog_bottom_add_button);
                final LinearLayout linearLayoutToolContainer = (LinearLayout) dialog
                        .findViewById(R.id.dialog_confirm_tool_main_container_linear_layout);
                final List<ToolConfirmationRow> matchedToolsList = new ArrayList<>();

                for (int i = 0; i < matchedTools.length(); i++) {
                    ToolConfirmationRow confirmationRow = new ToolConfirmationRow(getActivity(),
                            matchedTools.getJSONObject(i));
                    linearLayoutToolContainer.addView(confirmationRow.getView());
                    matchedToolsList.add(confirmationRow);
                }

                addToolsButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        for (ToolConfirmationRow row : matchedToolsList) {
                            if (row.isChecked()) {
                                ToolEntry newTool = row.getToolEntry();
                                user.getToolLog().addTool(newTool, newTool.getSetupDateTime().substring(0, 10));
                                ToolLogRow newRow = new ToolLogRow(v.getContext(), newTool,
                                        utilityOnClickListeners.getToolEntryEditDialogOnClickListener(
                                                getActivity(), getFragmentManager(), mGpsLocationTracker,
                                                newTool, user));
                                row.getView().setTag(newTool.getToolId());
                                toolContainer.addView(newRow.getView());
                            }
                        }

                        user.writeToSharedPref(v.getContext());
                        dialog.dismiss();
                    }
                });

                cancelButton.setOnClickListener(utilityOnClickListeners.getDismissDialogListener(dialog));
                dialog.show();
            }

            if (unconfirmedRemovedTools.size() > 0) {
                final Dialog dialog = dialogInterface.getDialog(getActivity(),
                        R.layout.dialog_confirm_tools_from_api, R.string.tool_confirmation);
                TextView infoTextView = (TextView) dialog.findViewById(R.id.dialog_description_text_view);
                Button cancelButton = (Button) dialog.findViewById(R.id.dialog_bottom_cancel_button);
                Button archiveToolsButton = (Button) dialog.findViewById(R.id.dialog_bottom_add_button);
                final LinearLayout linearLayoutToolContainer = (LinearLayout) dialog
                        .findViewById(R.id.dialog_confirm_tool_main_container_linear_layout);

                infoTextView.setText(R.string.removed_tools_information_text);
                archiveToolsButton.setText(R.string.ok);
                cancelButton.setVisibility(View.GONE);

                for (ToolEntry removedEntry : unconfirmedRemovedTools) {
                    ToolLogRow removedToolRow = new ToolLogRow(getActivity(), removedEntry, null);
                    removedToolRow.setToolNotificationImageViewVisibility(false);
                    removedToolRow.setEditToolImageViewVisibility(false);
                    linearLayoutToolContainer.addView(removedToolRow.getView());
                }

                archiveToolsButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        for (ToolEntry removedEntry : unconfirmedRemovedTools) {
                            removedEntry.setToolStatus(ToolEntryStatus.STATUS_REMOVED);

                            for (int i = 0; i < toolContainer.getChildCount(); i++) {
                                if (removedEntry.getToolId()
                                        .equals(toolContainer.getChildAt(i).getTag().toString())) {
                                    toolContainer.removeViewAt(i);
                                    break;
                                }
                            }
                        }

                        user.writeToSharedPref(v.getContext());
                        dialog.dismiss();
                    }
                });

                dialog.show();
            }

            if (synchedTools.size() > 0) {
                final Dialog dialog = dialogInterface.getDialog(getActivity(),
                        R.layout.dialog_confirm_tools_from_api, R.string.tool_confirmation);
                TextView infoTextView = (TextView) dialog.findViewById(R.id.dialog_description_text_view);
                Button cancelButton = (Button) dialog.findViewById(R.id.dialog_bottom_cancel_button);
                Button archiveToolsButton = (Button) dialog.findViewById(R.id.dialog_bottom_add_button);
                final LinearLayout linearLayoutToolContainer = (LinearLayout) dialog
                        .findViewById(R.id.dialog_confirm_tool_main_container_linear_layout);

                infoTextView.setText(R.string.unexpected_tool_removal_info_text);
                archiveToolsButton.setText(R.string.archive);

                for (ToolEntry removedEntry : synchedTools) {
                    ToolLogRow removedToolRow = new ToolLogRow(getActivity(), removedEntry, null);
                    removedToolRow.setToolNotificationImageViewVisibility(false);
                    removedToolRow.setEditToolImageViewVisibility(false);
                    linearLayoutToolContainer.addView(removedToolRow.getView());
                }

                archiveToolsButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        for (ToolEntry removedEntry : synchedTools) {
                            removedEntry.setToolStatus(ToolEntryStatus.STATUS_REMOVED);

                            for (int i = 0; i < toolContainer.getChildCount(); i++) {
                                if (removedEntry.getToolId()
                                        .equals(toolContainer.getChildAt(i).getTag().toString())) {
                                    toolContainer.removeViewAt(i);
                                    break;
                                }
                            }
                        }

                        user.writeToSharedPref(v.getContext());
                        dialog.dismiss();
                    }
                });

                cancelButton.setOnClickListener(utilityOnClickListeners.getDismissDialogListener(dialog));
                dialog.show();
            }

            if (unconfirmedRemovedTools.size() > 0) {
                // TODO: If not found server side, tool is assumed to be removed. Inform user.

                final Dialog dialog = dialogInterface.getDialog(getActivity(),
                        R.layout.dialog_confirm_tools_from_api, R.string.reported_tools_removed_title);
                TextView informationTextView = (TextView) dialog
                        .findViewById(R.id.dialog_description_text_view);
                Button cancelButton = (Button) dialog.findViewById(R.id.dialog_bottom_cancel_button);
                Button archiveToolsButton = (Button) dialog.findViewById(R.id.dialog_bottom_add_button);
                final LinearLayout linearLayoutToolContainer = (LinearLayout) dialog
                        .findViewById(R.id.dialog_confirm_tool_main_container_linear_layout);

                informationTextView.setText(getString(R.string.removed_tools_information_text));
                cancelButton.setVisibility(View.GONE);
                archiveToolsButton.setText(getString(R.string.ok));

                for (ToolEntry toolEntry : unconfirmedRemovedTools) {
                    ToolConfirmationRow confirmationRow = new ToolConfirmationRow(getActivity(), toolEntry);
                    linearLayoutToolContainer.addView(confirmationRow.getView());
                }

                archiveToolsButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        for (ToolEntry toolEntry : unconfirmedRemovedTools) {
                            toolEntry.setToolStatus(ToolEntryStatus.STATUS_REMOVED);
                        }

                        user.writeToSharedPref(v.getContext());
                        dialog.dismiss();
                    }
                });

                dialog.show();
            }

            if (synchedTools.size() > 0) {
                //                    // TODO: Prompt user: Tool was confirmed, now is no longer at BW, remove or archive?

                final Dialog dialog = dialogInterface.getDialog(getActivity(),
                        R.layout.dialog_confirm_tools_from_api, R.string.tool_confirmation);
                TextView informationTextView = (TextView) dialog
                        .findViewById(R.id.dialog_description_text_view);
                Button cancelButton = (Button) dialog.findViewById(R.id.dialog_bottom_cancel_button);
                Button archiveToolsButton = (Button) dialog.findViewById(R.id.dialog_bottom_add_button);
                final LinearLayout linearLayoutToolContainer = (LinearLayout) dialog
                        .findViewById(R.id.dialog_confirm_tool_main_container_linear_layout);

                informationTextView.setText(getString(R.string.unexpected_tool_removal_info_text));
                archiveToolsButton.setText(getString(R.string.ok));

                for (ToolEntry toolEntry : synchedTools) {
                    ToolConfirmationRow confirmationRow = new ToolConfirmationRow(getActivity(), toolEntry);
                    linearLayoutToolContainer.addView(confirmationRow.getView());
                }

                archiveToolsButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        for (ToolEntry toolEntry : synchedTools) {
                            toolEntry.setToolStatus(ToolEntryStatus.STATUS_REMOVED);
                        }

                        user.writeToSharedPref(v.getContext());
                        dialog.dismiss();
                    }
                });

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

                dialog.show();
            }

            user.writeToSharedPref(getActivity());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}