Example usage for android.widget LinearLayout removeAllViews

List of usage examples for android.widget LinearLayout removeAllViews

Introduction

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

Prototype

public void removeAllViews() 

Source Link

Document

Call this method to remove all child views from the ViewGroup.

Usage

From source file:com.thinkthinkdo.pff_appsettings.PermissionDetailFragment.java

private void displayApps(LinearLayout permListView, String permName) {
    List<PackageInfo> packs = mPm.getInstalledPackages(0);
    SortedMap<String, MyPermissionInfo> usedPerms = new TreeMap<String, MyPermissionInfo>();
    for (int i = 0; i < packs.size(); i++) {
        PackageInfo p = packs.get(i);//from  ww w .ja  v  a2 s  .  c o  m
        PackageInfo pkgInfo;
        try {
            pkgInfo = mPm.getPackageInfo(p.packageName, PackageManager.GET_PERMISSIONS);
        } catch (NameNotFoundException e) {
            Log.w(TAG, "Couldn't retrieve permissions for package:" + p.packageName);
            continue;
        }
        // Extract all user permissions
        Set<MyPermissionInfo> permSet = new HashSet<MyPermissionInfo>();
        if ((pkgInfo.applicationInfo != null) && (pkgInfo.applicationInfo.uid != -1)) {
            if (localLOGV)
                Log.w(TAG, "getAllUsedPermissions package:" + p.packageName);
            getAllUsedPermissions(pkgInfo.applicationInfo.uid, permSet);
        }
        for (MyPermissionInfo tmpInfo : permSet) {
            if (localLOGV)
                Log.i(TAG, "tmpInfo package:" + p.packageName + ", tmpInfo.name=" + tmpInfo.name);
            if (tmpInfo.name.equalsIgnoreCase(permName)) {
                if (localLOGV)
                    Log.w(TAG, "Adding package:" + p.packageName);
                tmpInfo.packageName = p.packageName;
                usedPerms.put(tmpInfo.packageName, tmpInfo);
            }
        }
    }
    mUsedPerms = usedPerms;
    permListView.removeAllViews();
    /* add the All Entry                        */
    int spacing = (int) (8 * mContext.getResources().getDisplayMetrics().density);
    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT);
    int j = 0;
    for (Map.Entry<String, MyPermissionInfo> entry : usedPerms.entrySet()) {
        MyPermissionInfo tmpPerm = entry.getValue();
        if (tmpPerm.packageName.compareToIgnoreCase("com.thinkthinkdo.pff_appsettings") != 0) {
            if (localLOGV)
                Log.w(TAG, "usedPacks containd package:" + tmpPerm.packageName);
            View view = getAppItemView(mContext, mInflater, tmpPerm);
            lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            if (j == 0) {
                lp.topMargin = spacing;
            }
            if (permListView.getChildCount() == 0) {
                lp.topMargin *= 2;
            }
            permListView.addView(view, lp);
            j++;
        }
    }
}

From source file:foam.opensauces.StarwispBuilder.java

public void Update(final StarwispActivity ctx, final String ctxname, JSONArray arr) {
    try {/*from w w  w.jav  a2 s  . c  om*/

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

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

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

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

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

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

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

            ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);

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

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

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

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

            dialog.setContentView(inner);

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

            dialog.show();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            final String name = arr.getString(3);

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

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

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

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

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

            return;
        }

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

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

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

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

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

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

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

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

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

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

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

                JSONArray params = arr.getJSONArray(3);
                String buttontype = params.getString(0);
                int height = params.getInt(1);
                int textsize = params.getInt(2);
                LinearLayout.LayoutParams lp = BuildLayoutParams(params.getJSONArray(3));
                final JSONArray buttons = params.getJSONArray(4);
                final int count = buttons.length();
                int vertcount = 0;
                LinearLayout vert = null;

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

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

                    if (buttontype.equals("button")) {
                        Button b = new Button(ctx);
                        b.setId(button.getInt(0));
                        b.setText(button.getString(1));
                        b.setTextSize(textsize);
                        b.setLayoutParams(lp);
                        b.setTypeface(((StarwispActivity) ctx).m_Typeface);
                        final String fn = params.getString(5);
                        b.setOnClickListener(new View.OnClickListener() {
                            public void onClick(View v) {
                                CallbackArgs(ctx, ctxname, id, "" + v.getId() + " #t");
                            }
                        });
                        vert.addView(b);
                    } else if (buttontype.equals("toggle")) {
                        ToggleButton b = new ToggleButton(ctx);
                        b.setId(button.getInt(0));
                        b.setText(button.getString(1));
                        b.setTextSize(textsize);
                        b.setLayoutParams(lp);
                        b.setTypeface(((StarwispActivity) ctx).m_Typeface);
                        final String fn = params.getString(5);
                        b.setOnClickListener(new View.OnClickListener() {
                            public void onClick(View v) {
                                String arg = "#f";
                                if (((ToggleButton) v).isChecked())
                                    arg = "#t";
                                CallbackArgs(ctx, ctxname, id, "" + v.getId() + " " + arg);
                            }
                        });
                        vert.addView(b);
                    } else if (buttontype.equals("single")) {
                        ToggleButton b = new ToggleButton(ctx);
                        b.setId(button.getInt(0));
                        b.setText(button.getString(1));
                        b.setTextSize(textsize);
                        b.setLayoutParams(lp);
                        b.setTypeface(((StarwispActivity) ctx).m_Typeface);
                        final String fn = params.getString(5);
                        b.setOnClickListener(new View.OnClickListener() {
                            public void onClick(View v) {
                                try {
                                    for (int i = 0; i < count; i++) {
                                        JSONArray button = buttons.getJSONArray(i);
                                        int bid = button.getInt(0);
                                        if (bid != v.getId()) {
                                            ToggleButton tb = (ToggleButton) ctx.findViewById(bid);
                                            tb.setChecked(false);
                                        }
                                    }
                                } catch (JSONException e) {
                                    Log.e("starwisp", "Error parsing data " + e.toString());
                                }

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

                }
            }
        }

        /*
                    if (type.equals("grid-layout")) {
        GridLayout v = (GridLayout)vv;
        if (token.equals("contents")) {
            v.removeAllViews();
            JSONArray children = arr.getJSONArray(3);
            for (int i=0; i<children.length(); i++) {
                Build(ctx,ctxname,new JSONArray(children.getString(i)), v);
            }
        }
                    }
        */
        if (type.equals("view-pager")) {
            ViewPager v = (ViewPager) vv;
            if (token.equals("switch")) {
                v.setCurrentItem(arr.getInt(3));
            }
            if (token.equals("pages")) {
                final JSONArray items = arr.getJSONArray(3);
                v.setAdapter(new FragmentPagerAdapter(ctx.getSupportFragmentManager()) {
                    @Override
                    public int getCount() {
                        return items.length();
                    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            return;
        }

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

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

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

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

            if (token.equals("array")) {
                final JSONArray items = arr.getJSONArray(3);
                ArrayList<String> spinnerArray = new ArrayList<String>();

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

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

                v.setAdapter(spinnerArrayAdapter);

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

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

            }
            return;
        }

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

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

public void handleDateResponse(JSONObject response) {
    horizontalscrollview.setVisibility(View.GONE);
    //Fetch Data From the Services
    JsonParser parser = new JsonParser();
    JsonObject responObj = (JsonObject) parser.parse(response.toString());
    JsonObject profileobj = responObj.get("doctor_profile").getAsJsonObject();

    JsonObject appointment_slot = profileobj.get("appointment_slot").getAsJsonObject();
    JsonArray available_hour = appointment_slot.get("available_hour").getAsJsonArray();

    LinearLayout layout = (LinearLayout) findViewById(R.id.panelMessageFiles);
    String str_timeslot = "", str_phys_avail_id = "";
    if (layout.getChildCount() > 0) {
        layout.removeAllViews();
    }/*from   ww w. j  a v a  2 s.  c  o  m*/
    timeSlotListMap.clear();

    for (int i = 0; i < available_hour.size(); i++) {
        JsonObject availabilityStatus = available_hour.get(i).getAsJsonObject();
        String str_availabilityStatus = "";

        if (MdliveUtils.checkJSONResponseHasString(availabilityStatus, "status")) {
            str_availabilityStatus = availabilityStatus.get("status").getAsString();
            if (str_availabilityStatus.equals("Available")) {
                //This visibility is for future timeslots response for the corresponding date selection.
                //if  the future date has timeslots then make an appointment req layout nd textview visibility will be gone

                findViewById(R.id.noappmtsTxtLayout).setVisibility(View.GONE);
                reqfutureapptBtnLayout.setVisibility(View.GONE);
                JsonArray timeSlotArray = availabilityStatus.get("time_slot").getAsJsonArray();

                for (int j = 0; j < timeSlotArray.size(); j++) {
                    JsonObject timeSlotObj = timeSlotArray.get(j).getAsJsonObject();

                    if (MdliveUtils.checkJSONResponseHasString(timeSlotObj, "appointment_type")
                            && MdliveUtils.checkJSONResponseHasString(timeSlotObj, "timeslot")) {
                        str_appointmenttype = timeSlotObj.get("appointment_type").getAsString();
                        str_timeslot = timeSlotObj.get("timeslot").getAsString();
                        selectedTimestamp = timeSlotObj.get("timeslot").getAsString();

                        if (MdliveUtils.checkJSONResponseHasString(timeSlotObj, "phys_availability_id")) {
                            str_phys_avail_id = timeSlotObj.get("phys_availability_id").getAsString();
                        } else {
                            str_phys_avail_id = null;
                        }

                        HashMap<String, String> datemap = new HashMap<String, String>();
                        datemap.put("timeslot", str_timeslot);
                        datemap.put("phys_id", str_phys_avail_id);
                        datemap.put("appointment_type", str_appointmenttype);
                        videophoneparentLl.setVisibility(View.VISIBLE);
                        timeSlotListMap.add(datemap);

                        final Button myText = new Button(MDLiveProviderDetails.this);

                        if (str_timeslot.equals("0")) {
                            final int density = (int) getBaseContext().getResources()
                                    .getDisplayMetrics().density;

                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                                myText.setElevation(0f);
                            }
                            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                                    LinearLayout.LayoutParams.WRAP_CONTENT,
                                    LinearLayout.LayoutParams.WRAP_CONTENT);
                            params.setMargins(4 * density, 4 * density, 4 * density, 4 * density);
                            myText.setLayoutParams(params);
                            myText.setGravity(Gravity.CENTER);
                            myText.setTextColor(Color.WHITE);
                            myText.setTextSize(16);
                            myText.setPadding(8 * density, 4 * density, 8 * density, 4 * density);
                            myText.setBackgroundResource(R.drawable.timeslot_white_rounded_corner);
                            myText.setText("Now");
                            myText.setBackgroundResource(R.drawable.timeslot_blue_rounded_corner);
                            myText.setClickable(true);
                            previousSelectedTv = myText;
                            if (str_appointmenttype.toLowerCase().contains("video")
                                    || str_appointmenttype.toLowerCase().contains("video or phone")) {
                                videoList.add(myText);
                            }
                            if (str_appointmenttype.toLowerCase().contains("phone")) {
                                phoneList.add(myText);
                            }

                            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                                    LinearLayout.LayoutParams.WRAP_CONTENT,
                                    LinearLayout.LayoutParams.WRAP_CONTENT);
                            lp.setMargins(4 * density, 4 * density, 4 * density, 4 * density);
                            myText.setLayoutParams(lp);
                            myText.setTag("Now");
                            defaultNowTextPreferences(myText, str_appointmenttype);
                            selectedTimeslot = true;
                            clickEventForHorizontalText(myText, str_timeslot, str_phys_avail_id);
                            layout.addView(myText);
                        } else {
                            setHorizontalScrollviewTimeslots(layout, str_timeslot, j, str_phys_avail_id);
                        }
                    }
                }
            } else {
                if (layout.getChildCount() == 0) {
                    selectedTimeslot = false;
                    findViewById(R.id.noappmtsTxtLayout).setVisibility(View.VISIBLE);
                    ((TextView) findViewById(R.id.noAppmtsTxt))
                            .setText(getString(R.string.mdl_notimeslots_txt));
                    reqfutureapptBtnLayout.setVisibility(viewsVisibility);
                    ((TextView) findViewById(R.id.reqfutureapptBtn)).setText("Make an appointment request");
                    ((TextView) findViewById(R.id.reqfutureapptBtn)).setTextColor(Color.parseColor("#0079FD"));
                    videophoneparentLl.setVisibility(View.GONE);
                    tapReqFutureBtnAction();
                    findViewById(R.id.reqApmtBtm).setVisibility(View.GONE);
                }
            }
        }
    }

}

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/*from  w  w  w. java2s .  c  o 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.xandy.calendar.EventInfoFragment.java

public void initReminders(View view, Cursor cursor) {

    // Add reminders
    mOriginalReminders.clear();/*from  ww  w.j ava2 s  .  c  om*/
    mUnsupportedReminders.clear();
    while (cursor.moveToNext()) {
        int minutes = cursor.getInt(EditEventHelper.REMINDERS_INDEX_MINUTES);
        int method = cursor.getInt(EditEventHelper.REMINDERS_INDEX_METHOD);

        if (method != Reminders.METHOD_DEFAULT && !mReminderMethodValues.contains(method)) {
            // Stash unsupported reminder types separately so we don't alter
            // them in the UI
            mUnsupportedReminders.add(CalendarEventModel.ReminderEntry.valueOf(minutes, method));
        } else {
            mOriginalReminders.add(CalendarEventModel.ReminderEntry.valueOf(minutes, method));
        }
    }
    // Sort appropriately for display (by time, then type)
    Collections.sort(mOriginalReminders);

    if (mUserModifiedReminders) {
        // If the user has changed the list of reminders don't change what's
        // shown.
        return;
    }

    LinearLayout parent = (LinearLayout) mScrollView.findViewById(R.id.reminder_items_container);
    if (parent != null) {
        parent.removeAllViews();
    }
    if (mReminderViews != null) {
        mReminderViews.clear();
    }

    if (mHasAlarm) {
        ArrayList<CalendarEventModel.ReminderEntry> reminders;
        // If applicable, use reminders saved in the bundle.
        if (mReminders != null) {
            reminders = mReminders;
        } else {
            reminders = mOriginalReminders;
        }
        // Insert any minute values that aren't represented in the minutes list.
        for (CalendarEventModel.ReminderEntry re : reminders) {
            EventViewUtils.addMinutesToList(mActivity, mReminderMinuteValues, mReminderMinuteLabels,
                    re.getMinutes());
        }
        // Create a UI element for each reminder.  We display all of the reminders we get
        // from the provider, even if the count exceeds the calendar maximum.  (Also, for
        // a new event, we won't have a maxReminders value available.)
        for (CalendarEventModel.ReminderEntry re : reminders) {
            EventViewUtils.addReminder(mActivity, mScrollView, this, mReminderViews, mReminderMinuteValues,
                    mReminderMinuteLabels, mReminderMethodValues, mReminderMethodLabels, re, Integer.MAX_VALUE,
                    mReminderChangeListener);
        }
        EventViewUtils.updateAddReminderButton(mView, mReminderViews, mMaxReminders);
        // TODO show unsupported reminder types in some fashion.
    }
}

From source file:com.android.calendar.EventInfoFragment.java

public void initReminders(View view, Cursor cursor) {

    // Add reminders
    mOriginalReminders.clear();/*from   w w w.  j av  a2s. c  om*/
    mUnsupportedReminders.clear();
    while (cursor.moveToNext()) {
        int minutes = cursor.getInt(EditEventHelper.REMINDERS_INDEX_MINUTES);
        int method = cursor.getInt(EditEventHelper.REMINDERS_INDEX_METHOD);

        if (method != Reminders.METHOD_DEFAULT && !mReminderMethodValues.contains(method)) {
            // Stash unsupported reminder types separately so we don't alter
            // them in the UI
            mUnsupportedReminders.add(ReminderEntry.valueOf(minutes, method));
        } else {
            mOriginalReminders.add(ReminderEntry.valueOf(minutes, method));
        }
    }
    // Sort appropriately for display (by time, then type)
    Collections.sort(mOriginalReminders);

    if (mUserModifiedReminders) {
        // If the user has changed the list of reminders don't change what's
        // shown.
        return;
    }

    LinearLayout parent = (LinearLayout) mScrollView.findViewById(R.id.reminder_items_container);
    if (parent != null) {
        parent.removeAllViews();
    }
    if (mReminderViews != null) {
        mReminderViews.clear();
    }

    if (mHasAlarm) {
        ArrayList<ReminderEntry> reminders;
        // If applicable, use reminders saved in the bundle.
        if (mReminders != null) {
            reminders = mReminders;
        } else {
            reminders = mOriginalReminders;
        }
        // Insert any minute values that aren't represented in the minutes list.
        for (ReminderEntry re : reminders) {
            EventViewUtils.addMinutesToList(mActivity, mReminderMinuteValues, mReminderMinuteLabels,
                    re.getMinutes());
        }
        // Create a UI element for each reminder.  We display all of the reminders we get
        // from the provider, even if the count exceeds the calendar maximum.  (Also, for
        // a new event, we won't have a maxReminders value available.)
        for (ReminderEntry re : reminders) {
            EventViewUtils.addReminder(mActivity, mScrollView, this, mReminderViews, mReminderMinuteValues,
                    mReminderMinuteLabels, mReminderMethodValues, mReminderMethodLabels, re, Integer.MAX_VALUE,
                    mReminderChangeListener);
        }
        EventViewUtils.updateAddReminderButton(mView, mReminderViews, mMaxReminders);
        // TODO show unsupported reminder types in some fashion.
    }
}

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.jav a 2 s .  com*/
    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:org.quantumbadger.redreader.activities.AlbumListingActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    PrefsUtility.applyTheme(this);

    OptionsMenuUtility.fixActionBar(AlbumListingActivity.this, getString(R.string.imgur_album));

    if (getActionBar() != null) {
        getActionBar().setHomeButtonEnabled(true);
        getActionBar().setDisplayHomeAsUpEnabled(true);
    }//www  .j a va  2 s. c  om

    final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    final boolean solidblack = PrefsUtility.appearance_solidblack(this, sharedPreferences)
            && PrefsUtility.appearance_theme(this, sharedPreferences) == PrefsUtility.AppearanceTheme.NIGHT;

    if (solidblack)
        getWindow().setBackgroundDrawable(new ColorDrawable(Color.BLACK));

    final Intent intent = getIntent();

    mUrl = intent.getDataString();

    if (mUrl == null) {
        finish();
        return;
    }

    final Matcher matchImgur = LinkHandler.imgurAlbumPattern.matcher(mUrl);
    final String albumId;

    if (matchImgur.find()) {
        albumId = matchImgur.group(2);
    } else {
        Log.e("AlbumListingActivity", "URL match failed");
        revertToWeb();
        return;
    }

    Log.i("AlbumListingActivity", "Loading URL " + mUrl + ", album id " + albumId);

    final ProgressBar progressBar = new ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal);
    progressBar.setIndeterminate(true);

    final LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(LinearLayout.VERTICAL);
    layout.addView(progressBar);

    ImgurAPI.getAlbumInfo(this, albumId, Constants.Priority.IMAGE_VIEW, 0, new GetAlbumInfoListener() {

        @Override
        public void onFailure(final RequestFailureType type, final Throwable t, final StatusLine status,
                final String readableMessage) {
            Log.e("AlbumListingActivity", "getAlbumInfo call failed: " + type);

            if (status != null)
                Log.e("AlbumListingActivity", "status was: " + status.toString());
            if (t != null)
                Log.e("AlbumListingActivity", "exception was: ", t);

            // It might be a single image, not an album

            if (status == null) {
                revertToWeb();
                return;
            }

            ImgurAPI.getImageInfo(AlbumListingActivity.this, albumId, Constants.Priority.IMAGE_VIEW, 0,
                    new GetImageInfoListener() {
                        @Override
                        public void onFailure(final RequestFailureType type, final Throwable t,
                                final StatusLine status, final String readableMessage) {
                            Log.e("AlbumListingActivity", "Image info request also failed: " + type);
                            revertToWeb();
                        }

                        @Override
                        public void onSuccess(final ImageInfo info) {
                            Log.i("AlbumListingActivity", "Link was actually an image.");
                            LinkHandler.onLinkClicked(AlbumListingActivity.this, info.urlOriginal);
                            finish();
                        }

                        @Override
                        public void onNotAnImage() {
                            Log.i("AlbumListingActivity", "Not an image either");
                            revertToWeb();
                        }
                    });
        }

        @Override
        public void onSuccess(final ImgurAPI.AlbumInfo info) {
            Log.i("AlbumListingActivity", "Got album, " + info.images.size() + " image(s)");

            AndroidApi.UI_THREAD_HANDLER.post(new Runnable() {
                @Override
                public void run() {

                    if (info.title != null && !info.title.trim().isEmpty()) {
                        OptionsMenuUtility.fixActionBar(AlbumListingActivity.this,
                                getString(R.string.imgur_album) + ": " + info.title);
                    }

                    layout.removeAllViews();

                    final ListView listView = new ListView(AlbumListingActivity.this);
                    listView.setAdapter(new AlbumAdapter(info));
                    layout.addView(listView);

                    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(final AdapterView<?> parent, final View view,
                                final int position, final long id) {

                            LinkHandler.onLinkClicked(AlbumListingActivity.this,
                                    info.images.get(position).urlOriginal, false, null, info, position);
                        }
                    });
                }
            });
        }
    });

    setContentView(layout);
}

From source file:es.ugr.swad.swadroid.modules.tests.TestsMake.java

/**
 * Shows a test question on screen/*from w  w w. j  a  va2 s .c  o m*/
 *
 * @param pos Question's position in questions's list of the test
 */
private void showQuestion(int pos) {
    TestQuestion question = test.getQuestions().get(pos);
    List<TestAnswer> answers = question.getAnswers();
    TestAnswer a;
    ScrollView scrollContent = (ScrollView) findViewById(R.id.testMakeScroll);
    LinearLayout testMakeList = (LinearLayout) findViewById(R.id.testMakeList);
    TextView stem = (TextView) findViewById(R.id.testMakeQuestionStem);
    TextView questionFeedback = (TextView) findViewById(R.id.testMakeQuestionFeedback);
    TextView answerFeedback = (TextView) findViewById(R.id.testMakeAnswerFeedback);
    TextView score = (TextView) findViewById(R.id.testMakeQuestionScore);
    TextView textCorrectAnswer = (TextView) findViewById(R.id.testMakeCorrectAnswer);
    EditText textAnswer = (EditText) findViewById(R.id.testMakeEditText);
    ImageView img = (ImageView) findViewById(R.id.testMakeCorrectAnswerImage);
    MenuItem actionScoreItem = menu.findItem(R.id.action_score);
    CheckedAnswersArrayAdapter checkedAnswersAdapter;
    String answerType = question.getAnswerType();
    String feedback = test.getFeedback();
    String questionFeedbackText = question.getFeedback();
    String correctAnswer = "";
    int numAnswers = answers.size();
    Float questionScore;
    DecimalFormat df = new DecimalFormat("0.00");
    int feedbackLevel;
    int mediumFeedbackLevel = Test.FEEDBACK_VALUES.indexOf(Test.FEEDBACK_MEDIUM);
    int maxFeedbackLevel = Test.FEEDBACK_VALUES.indexOf(Test.FEEDBACK_MAX);

    scrollContent.setOnTouchListener(new View.OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            findViewById(R.id.testMakeList).getParent().requestDisallowInterceptTouchEvent(false);
            return false;
        }
    });
    testMakeList.setOnTouchListener(new View.OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            // Disallow the touch request for parent scroll on touch of child view
            v.getParent().requestDisallowInterceptTouchEvent(true);
            return false;
        }
    });

    questionFeedback.setVisibility(View.GONE);
    answerFeedback.setVisibility(View.GONE);
    textAnswer.setVisibility(View.GONE);
    textCorrectAnswer.setVisibility(View.GONE);
    testMakeList.setVisibility(View.GONE);
    img.setVisibility(View.GONE);

    testMakeList.removeAllViews();
    stem.setText(Html.fromHtml(question.getStem()));

    if ((questionFeedbackText != null) && (!questionFeedbackText.equals(Constants.NULL_VALUE))) {
        questionFeedback.setText(Html.fromHtml(questionFeedbackText));
    }

    feedbackLevel = Test.FEEDBACK_VALUES.indexOf(feedback);

    if (test.isEvaluated() && (feedbackLevel == maxFeedbackLevel)
            && !question.getFeedback().equals(Constants.NULL_VALUE)) {
        questionFeedback.setVisibility(View.VISIBLE);
    } else {
        questionFeedback.setVisibility(View.GONE);
    }

    if (answerType.equals(TestAnswer.TYPE_TEXT) || answerType.equals(TestAnswer.TYPE_INT)
            || answerType.equals(TestAnswer.TYPE_FLOAT)) {

        if (answerType.equals(TestAnswer.TYPE_INT)) {
            textAnswer.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED);
        } else if (answerType.equals(TestAnswer.TYPE_FLOAT)) {
            textAnswer.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL
                    | InputType.TYPE_NUMBER_FLAG_SIGNED);
        } else {
            textAnswer.setInputType(InputType.TYPE_CLASS_TEXT);
        }

        a = answers.get(0);
        textAnswer.setText(a.getUserAnswer());
        textAnswer.setVisibility(View.VISIBLE);

        answerFeedback.setText(Html.fromHtml(a.getFeedback()));

        if (test.isEvaluated() && (feedbackLevel > mediumFeedbackLevel)) {
            if (answerType.equals(TestAnswer.TYPE_FLOAT)) {
                correctAnswer = "[" + a.getAnswer() + ";" + answers.get(1).getAnswer() + "]";

                if ((feedbackLevel == maxFeedbackLevel) && !a.getFeedback().equals(Constants.NULL_VALUE)) {
                    answerFeedback.setVisibility(View.VISIBLE);
                } else {
                    answerFeedback.setVisibility(View.GONE);
                }
            } else {
                for (int i = 0; i < numAnswers; i++) {
                    a = answers.get(i);

                    if ((feedbackLevel == maxFeedbackLevel) && !a.getFeedback().equals(Constants.NULL_VALUE)) {
                        correctAnswer += "<strong>" + a.getAnswer() + "</strong><br/>";
                        correctAnswer += "<i>" + a.getFeedback() + "</i><br/><br/>";
                    } else {
                        correctAnswer += a.getAnswer() + "<br/>";
                    }
                }
            }

            textCorrectAnswer.setText(Html.fromHtml(correctAnswer));
            textCorrectAnswer.setVisibility(View.VISIBLE);
        }
    } else if (answerType.equals(TestAnswer.TYPE_MULTIPLE_CHOICE)) {
        checkedAnswersAdapter = new CheckedAnswersArrayAdapter(this, R.layout.list_item_multiple_choice,
                answers, test.isEvaluated(), test.getFeedback(), answerType);

        for (int i = 0; i < numAnswers; i++) {
            a = answers.get(i);
            CheckableLinearLayout item = (CheckableLinearLayout) checkedAnswersAdapter.getView(i, null, null);
            item.setChecked(Utils.parseStringBool(a.getUserAnswer()));
            testMakeList.addView(item);
        }

        testMakeList.setVisibility(View.VISIBLE);
    } else {
        if (answerType.equals(TestAnswer.TYPE_TRUE_FALSE) && (numAnswers < 2)) {
            if (answers.get(0).getAnswer().equals(TestAnswer.VALUE_TRUE)) {
                answers.add(1,
                        new TestAnswer(0, 1, 0, false, TestAnswer.VALUE_FALSE, answers.get(0).getFeedback()));
            } else {
                answers.add(0,
                        new TestAnswer(0, 0, 0, false, TestAnswer.VALUE_TRUE, answers.get(0).getFeedback()));
            }

            numAnswers = 2;
        }

        checkedAnswersAdapter = new CheckedAnswersArrayAdapter(this, R.layout.list_item_single_choice, answers,
                test.isEvaluated(), test.getFeedback(), answerType);

        for (int i = 0; i < numAnswers; i++) {
            a = answers.get(i);
            CheckableLinearLayout item = (CheckableLinearLayout) checkedAnswersAdapter.getView(i, null, null);
            item.setChecked(a.getAnswer().equals(answers.get(0).getUserAnswer()));
            testMakeList.addView(item);
        }

        testMakeList.setVisibility(View.VISIBLE);
    }

    if (test.isEvaluated() && (feedbackLevel > mediumFeedbackLevel)) {
        textAnswer.setEnabled(false);
        textAnswer.setOnClickListener(null);

        if (feedback.equals(Test.FEEDBACK_HIGH)) {
            img.setImageResource(R.drawable.btn_check_buttonless_on);
            if (!answerType.equals(TestAnswer.TYPE_TRUE_FALSE)
                    && !answerType.equals(TestAnswer.TYPE_MULTIPLE_CHOICE)
                    && !answerType.equals(TestAnswer.TYPE_UNIQUE_CHOICE)) {

                if (!answers.get(0).isCorrectAnswered()) {
                    img.setImageResource(android.R.drawable.ic_delete);
                }

                img.setVisibility(View.VISIBLE);
            }
        }

        questionScore = test.getQuestionScore(pos);
        if (questionScore > 0) {
            score.setTextColor(getResources().getColor(R.color.green));
        } else if (questionScore < 0) {
            score.setTextColor(getResources().getColor(R.color.red));
        } else {
            score.setTextColor(Color.BLACK);
        }

        score.setText(df.format(questionScore));

        MenuItemCompat.setActionView(actionScoreItem, score);
        actionScoreItem.setVisible(true);
    }
}

From source file:cm.aptoide.pt.MainActivity.java

private void loadUItopapps() {
    ((ToggleButton) featuredView.findViewById(R.id.toggleButton1)).setOnCheckedChangeListener(null);
    Cursor c = db.getFeaturedTopApps();

    values = new ArrayList<HashMap<String, String>>();
    for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
        HashMap<String, String> item = new HashMap<String, String>();
        item.put("name", c.getString(1));
        item.put("icon", db.getIconsPath(0, Category.TOPFEATURED) + c.getString(4));
        item.put("rating", c.getString(5));
        item.put("id", c.getString(0));
        item.put("apkid", c.getString(7));
        item.put("vercode", c.getString(8));
        item.put("vername", c.getString(2));
        item.put("downloads", c.getString(6));
        if (values.size() == 26) {
            break;
        }// w  w w. j a va  2s.  com
        values.add(item);
    }
    c.close();

    runOnUiThread(new Runnable() {

        public void run() {

            LinearLayout ll = (LinearLayout) featuredView.findViewById(R.id.container);
            ll.removeAllViews();
            LinearLayout llAlso = new LinearLayout(MainActivity.this);
            llAlso.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT));
            llAlso.setOrientation(LinearLayout.HORIZONTAL);
            for (int i = 0; i != values.size(); i++) {
                LinearLayout txtSamItem = (LinearLayout) getLayoutInflater().inflate(R.layout.row_grid_item,
                        null);
                ((TextView) txtSamItem.findViewById(R.id.name)).setText(values.get(i).get("name"));
                // ((TextView) txtSamItem.findViewById(R.id.version))
                // .setText(getString(R.string.version) +" "+
                // values.get(i).get("vername"));
                ((TextView) txtSamItem.findViewById(R.id.downloads)).setText(
                        "(" + values.get(i).get("downloads") + " " + getString(R.string.downloads) + ")");
                String hashCode = (values.get(i).get("apkid") + "|" + values.get(i).get("vercode")) + "";
                cm.aptoide.com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage(
                        values.get(i).get("icon"), (ImageView) txtSamItem.findViewById(R.id.icon), hashCode);

                // imageLoader.DisplayImage(-1, values.get(i).get("icon"),
                // (ImageView) txtSamItem.findViewById(R.id.icon),
                // mContext);
                float stars = 0f;
                try {
                    stars = Float.parseFloat(values.get(i).get("rating"));
                } catch (Exception e) {
                    stars = 0f;
                }
                ((RatingBar) txtSamItem.findViewById(R.id.rating)).setRating(stars);
                ((RatingBar) txtSamItem.findViewById(R.id.rating)).setIsIndicator(true);
                txtSamItem.setPadding(10, 0, 0, 0);
                txtSamItem.setTag(values.get(i).get("id"));
                txtSamItem.setLayoutParams(
                        new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 100, 1));
                // txtSamItem.setOnClickListener(featuredListener);
                txtSamItem.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        Intent i = new Intent(MainActivity.this, ApkInfo.class);
                        long id = Long.parseLong((String) arg0.getTag());
                        i.putExtra("_id", id);
                        i.putExtra("top", true);
                        i.putExtra("category", Category.TOPFEATURED.ordinal());
                        startActivity(i);
                    }
                });

                txtSamItem.measure(0, 0);

                if (i % 2 == 0) {
                    ll.addView(llAlso);

                    llAlso = new LinearLayout(MainActivity.this);
                    llAlso.setLayoutParams(
                            new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 100));
                    llAlso.setOrientation(LinearLayout.HORIZONTAL);
                    llAlso.addView(txtSamItem);
                } else {
                    llAlso.addView(txtSamItem);
                }
            }

            ll.addView(llAlso);
            SharedPreferences sPref = PreferenceManager.getDefaultSharedPreferences(mContext);
            // System.out.println(sPref.getString("app_rating",
            // "All").equals(
            // "Mature"));
            ((ToggleButton) featuredView.findViewById(R.id.toggleButton1))
                    .setChecked(!sPref.getBoolean("matureChkBox", false));
            ((ToggleButton) featuredView.findViewById(R.id.toggleButton1))
                    .setOnCheckedChangeListener(adultCheckedListener);
        }
    });
}