Example usage for android.widget LinearLayout setOrientation

List of usage examples for android.widget LinearLayout setOrientation

Introduction

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

Prototype

public void setOrientation(@OrientationMode int orientation) 

Source Link

Document

Should the layout be a column or a row.

Usage

From source file:com.lifehackinnovations.siteaudit.FloorPlanActivity.java

public static AlertDialog getaddtextdialog(String title, final int itemnumber, Context ctx) {

    AlertDialog.Builder getaddtext = new AlertDialog.Builder(ctx);

    final LinearLayout linearlayout = new LinearLayout(ctx);
    linearlayout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
    linearlayout.setOrientation(LinearLayout.VERTICAL);

    final EditText nameet = new EditText(ctx);
    nameet.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));

    final TextView fontname = new TextView(ctx);
    fontname.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));

    final TextView colorname = new TextView(ctx);
    colorname.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));

    final Spinner fontsizespinner = new Spinner(ctx);
    fontsizespinner.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
    final Spinner colorspinner = new Spinner(ctx);
    fontsizespinner.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));

    List<String> fontsizelist = new ArrayList<String>();
    for (int t = 1; t < 200; t++) {
        fontsizelist.add(u.s(t));//from   w  w w .j av  a2s  .  c om
    }
    ArrayAdapter<String> fontsizearrayadapter = new ArrayAdapter<String>(ctx, R.layout.spinnertextview,
            fontsizelist);
    fontsizearrayadapter.setDropDownViewResource(R.layout.spinnertextview);

    List<String> colorlist = new ArrayList<String>();
    {
        colorlist.add("RED");
        colorlist.add("BLACK");
        colorlist.add("BLUE");
        colorlist.add("GREEN");
        colorlist.add("WHITE");
        colorlist.add("GRAY");
    }
    ArrayAdapter<String> colorlistarrayadapter = new ArrayAdapter<String>(ctx, R.layout.spinnertextview,
            colorlist);
    fontsizearrayadapter.setDropDownViewResource(R.layout.spinnertextview);
    colorspinner.setAdapter(colorlistarrayadapter);
    fontsizespinner.setAdapter(fontsizearrayadapter);
    fontsizespinner.setSelection(getIndexofSpinner(fontsizespinner, "25"));

    fontname.setText("Select Font Size");
    fontname.setTextSize(20f);
    colorname.setText("Select Color");
    colorname.setTextSize(20f);

    linearlayout.addView(nameet);
    linearlayout.addView(fontname);
    linearlayout.addView(fontsizespinner);
    linearlayout.addView(colorname);
    linearlayout.addView(colorspinner);

    if (!(itemnumber == view.i)) {
        nameet.setText(view.ITEMstring[itemnumber]);
        fontsizespinner.setSelection(getIndexofSpinner(fontsizespinner, u.s(view.ITEMfontsize[itemnumber])));
        colorspinner.setSelection(getIndexofSpinner(colorspinner, u.s(view.ITEMfontcolor[itemnumber])));
    }

    getaddtext.setView(linearlayout);
    getaddtext.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            dialog.cancel();
        }
    });
    getaddtext.setTitle(title);
    getaddtext.setPositiveButton("OK", new DialogInterface.OnClickListener() {

        @Override

        public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub
            String string = nameet.getText().toString();

            float fontsize = fontsizespinner.getSelectedItemPosition() + 1;
            //ITEMelcnumber[itemselectednumber]=u.i(string);
            int colpos = colorspinner.getSelectedItemPosition();
            int[] col = new int[] { Color.RED, Color.BLACK, Color.BLUE, Color.GREEN, Color.WHITE, Color.GRAY };
            int color = col[colpos];

            Log.d("addtext", u.s((int) fontsize) + colpos + color);

            view.ITEMstring[itemnumber] = string;
            view.ITEMfontsize[itemnumber] = (int) fontsize;
            view.ITEMfontcolor[itemnumber] = color;

            view.itemname = string;
            view.fontsize = (int) fontsize;
            view.color = color;
            view.invalidate();
            dialog.dismiss();
            FloorPlanActivity.writeonedbitem(itemnumber);
        }

    });

    return getaddtext.create();
}

From source file:com.adarshahd.indianrailinfo.donate.PNRStat.java

private void combineTrainAndPsnDetails() {
    if (mPageResult.contains("FLUSHED PNR / ") || mPageResult.contains("Invalid PNR")) {
        mTextViewPNRSts.setText("The PNR entered is either invalid or expired! Please check.");
        mFrameLayout.removeAllViews();//from   w  w  w  .j  a  v  a 2 s . co  m
        mFrameLayout.addView(mTextViewPNRSts);
        return;
    }
    if (mPageResult.contains("Connectivity Failure") || mPageResult.contains("try again")) {
        mTextViewPNRSts.setText("Looks like server is busy or currently unavailable. Please try again later!");
        mFrameLayout.removeAllViews();
        mFrameLayout.addView(mTextViewPNRSts);
        return;
    }
    //Combine both Train & Passenger details table into a single LinearLayout and add it to FrameLayout
    LinearLayout ll = new LinearLayout(mActivity);
    TextView textViewTrnDtls = new TextView(mActivity);
    TextView textViewPsnDtls = new TextView(mActivity);

    textViewTrnDtls.setText("Train Details: " + mPNRNumber);
    textViewTrnDtls.setFocusable(true);
    textViewPsnDtls.setText("Passenger Details");
    textViewTrnDtls.setTextAppearance(mActivity, android.R.style.TextAppearance_DeviceDefault_Large);
    textViewPsnDtls.setTextAppearance(mActivity, android.R.style.TextAppearance_DeviceDefault_Large);
    textViewTrnDtls.setPadding(10, 10, 10, 10);
    textViewPsnDtls.setPadding(10, 10, 10, 10);
    textViewTrnDtls.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
    textViewPsnDtls.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
    ll.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT));
    ll.setOrientation(LinearLayout.VERTICAL);
    ll.addView(textViewTrnDtls);
    ll.addView(mTableLayoutTrn);
    ll.addView(textViewPsnDtls);
    ll.addView(mTableLayoutPsn);
    mFrameLayout.removeAllViews();
    mFrameLayout.addView(ll);
    if (isWaitingList && !mPNRList.contains(mPNRNumber)) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Track this PNR?");
        builder.setMessage("Would you like this PNR to be tracked for status change?");
        builder.setPositiveButton("Track", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //save the pnr
                pnrDB.addPNRToTrack(mPNRNumber);
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("No thanks", null);
        builder.create().show();
    }

}

From source file:com.mishiranu.dashchan.ui.navigator.DrawerForm.java

private View makeHeader(ViewGroup parent, boolean button, float density) {
    if (C.API_LOLLIPOP) {
        LinearLayout linearLayout = new LinearLayout(context);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        View divider = makeSimpleDivider();
        int paddingTop = divider.getPaddingBottom();
        divider.setPadding(divider.getPaddingLeft(), divider.getPaddingTop(), divider.getPaddingRight(), 0);
        linearLayout.addView(divider, LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        LinearLayout linearLayout2 = new LinearLayout(context);
        linearLayout2.setOrientation(LinearLayout.HORIZONTAL);
        linearLayout.addView(linearLayout2, LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        TextView textView = makeCommonTextView(true);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(0, (int) (32f * density), 1);
        layoutParams.setMargins((int) (16f * density), paddingTop, (int) (16f * density), (int) (8f * density));
        linearLayout2.addView(textView, layoutParams);
        ViewHolder holder = new ViewHolder();
        holder.text = textView;/*from  ww  w. j a  v a 2s .  c  o  m*/
        if (button) {
            ImageView imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.CENTER);
            imageView.setBackgroundResource(ResourceUtils.getResourceId(context,
                    android.R.attr.borderlessButtonStyle, android.R.attr.background, 0));
            imageView.setOnClickListener(headerButtonListener);
            imageView.setImageAlpha(0x5e);
            int size = (int) (48f * density);
            layoutParams = new LinearLayout.LayoutParams(size, size);
            layoutParams.rightMargin = (int) (4f * density);
            linearLayout2.addView(imageView, layoutParams);
            holder.extra = imageView;
            holder.icon = imageView;
        }
        linearLayout.setTag(holder);
        return linearLayout;
    } else {
        View view = LayoutInflater.from(context)
                .inflate(ResourceUtils.getResourceId(context, android.R.attr.preferenceCategoryStyle,
                        android.R.attr.layout, android.R.layout.preference_category), parent, false);
        ViewHolder holder = new ViewHolder();
        holder.text = (TextView) view.findViewById(android.R.id.title);
        if (button) {
            int measureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
            view.measure(measureSpec, measureSpec);
            int size = view.getMeasuredHeight();
            if (size == 0) {
                size = (int) (32f * density);
            }
            FrameLayout frameLayout = new FrameLayout(context);
            frameLayout.addView(view);
            view = frameLayout;
            ImageView imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
            int padding = (int) (4f * density);
            imageView.setPadding(padding, padding, padding, padding);
            frameLayout.addView(imageView,
                    new FrameLayout.LayoutParams((int) (48f * density), size, Gravity.END));
            View buttonView = new View(context);
            buttonView.setBackgroundResource(
                    ResourceUtils.getResourceId(context, android.R.attr.selectableItemBackground, 0));
            buttonView.setOnClickListener(headerButtonListener);
            frameLayout.addView(buttonView, FrameLayout.LayoutParams.MATCH_PARENT,
                    FrameLayout.LayoutParams.MATCH_PARENT);
            holder.extra = buttonView;
            holder.icon = imageView;
        }
        view.setTag(holder);
        return view;
    }
}

From source file:com.mishiranu.dashchan.ui.navigator.DrawerForm.java

public DrawerForm(Context context, Context unstyledContext, Callback callback,
        WatcherService.Client watcherServiceClient) {
    this.context = context;
    this.unstyledContext = unstyledContext;
    this.callback = callback;
    this.watcherServiceClient = watcherServiceClient;
    float density = ResourceUtils.obtainDensity(context);
    LinearLayout linearLayout = new LinearLayout(context);
    linearLayout.setOrientation(LinearLayout.VERTICAL);
    linearLayout.setLayoutParams(new SortableListView.LayoutParams(SortableListView.LayoutParams.MATCH_PARENT,
            SortableListView.LayoutParams.WRAP_CONTENT));
    LinearLayout editTextContainer = new LinearLayout(context);
    editTextContainer.setGravity(Gravity.CENTER_VERTICAL);
    linearLayout.addView(editTextContainer);
    searchEdit = new SafePasteEditText(context);
    searchEdit.setOnKeyListener((v, keyCode, event) -> {
        if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
            v.clearFocus();/*from  w  w  w  . ja v a2  s  .  co  m*/
        }
        return false;
    });
    searchEdit.setHint(context.getString(R.string.text_code_number_address));
    searchEdit.setOnEditorActionListener(this);
    searchEdit.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI);
    searchEdit.setImeOptions(EditorInfo.IME_ACTION_GO | EditorInfo.IME_FLAG_NO_EXTRACT_UI);
    ImageView searchIcon = new ImageView(context, null, android.R.attr.buttonBarButtonStyle);
    searchIcon.setImageResource(ResourceUtils.getResourceId(context, R.attr.buttonForward, 0));
    searchIcon.setScaleType(ImageView.ScaleType.CENTER);
    searchIcon.setOnClickListener(this);
    editTextContainer.addView(searchEdit,
            new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1));
    editTextContainer.addView(searchIcon, (int) (40f * density), (int) (40f * density));
    if (C.API_LOLLIPOP) {
        editTextContainer.setPadding((int) (12f * density), (int) (8f * density), (int) (8f * density), 0);
    } else {
        editTextContainer.setPadding(0, (int) (2f * density), (int) (4f * density), (int) (2f * density));
    }
    LinearLayout selectorContainer = new LinearLayout(context);
    selectorContainer.setBackgroundResource(
            ResourceUtils.getResourceId(context, android.R.attr.selectableItemBackground, 0));
    selectorContainer.setOrientation(LinearLayout.HORIZONTAL);
    selectorContainer.setGravity(Gravity.CENTER_VERTICAL);
    selectorContainer.setOnClickListener(v -> {
        hideKeyboard();
        setChanSelectMode(!chanSelectMode);
    });
    linearLayout.addView(selectorContainer);
    selectorContainer.setMinimumHeight((int) (40f * density));
    if (C.API_LOLLIPOP) {
        selectorContainer.setPadding((int) (16f * density), 0, (int) (16f * density), 0);
        ((LinearLayout.LayoutParams) selectorContainer.getLayoutParams()).topMargin = (int) (4f * density);
    } else {
        selectorContainer.setPadding((int) (8f * density), 0, (int) (12f * density), 0);
    }
    chanNameView = new TextView(context, null, android.R.attr.textAppearanceListItem);
    chanNameView.setTextSize(TypedValue.COMPLEX_UNIT_SP, C.API_LOLLIPOP ? 14f : 16f);
    if (C.API_LOLLIPOP) {
        chanNameView.setTypeface(GraphicsUtils.TYPEFACE_MEDIUM);
    } else {
        chanNameView.setFilters(new InputFilter[] { new InputFilter.AllCaps() });
    }
    selectorContainer.addView(chanNameView,
            new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1));
    chanSelectorIcon = new ImageView(context);
    chanSelectorIcon.setImageResource(ResourceUtils.getResourceId(context, R.attr.buttonDropDownDrawer, 0));
    selectorContainer.addView(chanSelectorIcon, (int) (24f * density), (int) (24f * density));
    ((LinearLayout.LayoutParams) chanSelectorIcon.getLayoutParams()).gravity = Gravity.CENTER_VERTICAL
            | Gravity.END;
    headerView = linearLayout;
    inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
    chans.add(new ListItem(ListItem.ITEM_DIVIDER, 0, 0, null));
    int color = ResourceUtils.getColor(context, R.attr.drawerIconColor);
    ChanManager manager = ChanManager.getInstance();
    Collection<String> availableChans = manager.getAvailableChanNames();
    for (String chanName : availableChans) {
        ChanConfiguration configuration = ChanConfiguration.get(chanName);
        if (configuration.getOption(ChanConfiguration.OPTION_READ_POSTS_COUNT)) {
            watcherSupportSet.add(chanName);
        }
        Drawable drawable = manager.getIcon(chanName, color);
        chanIcons.put(chanName, drawable);
        chans.add(
                new ListItem(ListItem.ITEM_CHAN, chanName, null, null, configuration.getTitle(), 0, drawable));
    }
    if (availableChans.size() == 1) {
        selectorContainer.setVisibility(View.GONE);
    }
}

From source file:com.mishiranu.dashchan.ui.navigator.DrawerForm.java

@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
    if (chanSelectMode) {
        return listView.startSorting(2, chans.size(), position);
    }//from  w  w w  . j  a va 2s .  c  o m
    final ListItem listItem = getItem(position);
    if (listItem != null) {
        if (listItem.type == ListItem.ITEM_FAVORITE && listItem.threadNumber != null
                && FavoritesStorage.getInstance().canSortManually()) {
            long time = multipleFingersTime
                    + (multipleFingersCountingTime ? System.currentTimeMillis() - multipleFingersStartTime
                            : 0L);
            if (time >= ViewConfiguration.getLongPressTimeout() / 10) {
                int start = position;
                int end = position;
                for (int i = position - 1;; i--) {
                    ListItem checkingListItem = getItem(i);
                    if (checkingListItem == null) {
                        break;
                    }
                    if (checkingListItem.type != ListItem.ITEM_FAVORITE
                            || !listItem.chanName.equals(checkingListItem.chanName)) {
                        start = i + 1;
                        break;
                    }
                }
                for (int i = position + 1;; i++) {
                    ListItem checkingListItem = getItem(i);
                    if (checkingListItem == null) {
                        break;
                    }
                    if (checkingListItem.type != ListItem.ITEM_FAVORITE
                            || !listItem.chanName.equals(checkingListItem.chanName)) {
                        end = i - 1;
                        break;
                    }
                }
                listView.startSorting(start, end, position);
                return true;
            }
        }
        switch (listItem.type) {
        case ListItem.ITEM_PAGE:
        case ListItem.ITEM_FAVORITE: {
            DialogMenu dialogMenu = new DialogMenu(context, new DialogMenu.Callback() {
                @Override
                public void onItemClick(Context context, int id, Map<String, Object> extra) {
                    switch (id) {
                    case MENU_COPY_LINK:
                    case MENU_SHARE_LINK: {
                        ChanLocator locator = ChanLocator.get(listItem.chanName);
                        Uri uri = listItem.isThreadItem()
                                ? locator.safe(true).createThreadUri(listItem.boardName, listItem.threadNumber)
                                : locator.safe(true).createBoardUri(listItem.boardName, 0);
                        if (uri != null) {
                            switch (id) {
                            case MENU_COPY_LINK: {
                                StringUtils.copyToClipboard(context, uri.toString());
                                break;
                            }
                            case MENU_SHARE_LINK: {
                                String subject = listItem.title;
                                if (StringUtils.isEmptyOrWhitespace(subject)) {
                                    subject = uri.toString();
                                }
                                NavigationUtils.share(context, subject, null, uri);
                                break;
                            }
                            }
                        }
                        break;
                    }
                    case MENU_ADD_TO_FAVORITES: {
                        if (listItem.isThreadItem()) {
                            FavoritesStorage.getInstance().add(listItem.chanName, listItem.boardName,
                                    listItem.threadNumber, listItem.title, 0);
                        } else {
                            FavoritesStorage.getInstance().add(listItem.chanName, listItem.boardName);
                        }
                        break;
                    }
                    case MENU_REMOVE_FROM_FAVORITES: {
                        FavoritesStorage.getInstance().remove(listItem.chanName, listItem.boardName,
                                listItem.threadNumber);
                        break;
                    }
                    case MENU_RENAME: {
                        final EditText editText = new SafePasteEditText(context);
                        editText.setSingleLine(true);
                        editText.setText(listItem.title);
                        editText.setSelection(editText.length());
                        LinearLayout linearLayout = new LinearLayout(context);
                        linearLayout.setOrientation(LinearLayout.HORIZONTAL);
                        linearLayout.addView(editText, LinearLayout.LayoutParams.MATCH_PARENT,
                                LinearLayout.LayoutParams.WRAP_CONTENT);
                        int padding = context.getResources().getDimensionPixelSize(R.dimen.dialog_padding_view);
                        linearLayout.setPadding(padding, padding, padding, padding);
                        AlertDialog dialog = new AlertDialog.Builder(context).setView(linearLayout)
                                .setTitle(R.string.action_rename)
                                .setNegativeButton(android.R.string.cancel, null)
                                .setPositiveButton(android.R.string.ok, (d, which) -> {
                                    String newTitle = editText.getText().toString();
                                    FavoritesStorage.getInstance().modifyTitle(listItem.chanName,
                                            listItem.boardName, listItem.threadNumber, newTitle, true);
                                }).create();
                        dialog.getWindow()
                                .setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
                        dialog.show();
                        break;
                    }
                    }
                }
            });
            dialogMenu.addItem(MENU_COPY_LINK, R.string.action_copy_link);
            if (listItem.isThreadItem()) {
                dialogMenu.addItem(MENU_SHARE_LINK, R.string.action_share_link);
            }
            if (listItem.type != ListItem.ITEM_FAVORITE && !FavoritesStorage.getInstance()
                    .hasFavorite(listItem.chanName, listItem.boardName, listItem.threadNumber)) {
                dialogMenu.addItem(MENU_ADD_TO_FAVORITES, R.string.action_add_to_favorites);
            }
            if (listItem.type == ListItem.ITEM_FAVORITE) {
                dialogMenu.addItem(MENU_REMOVE_FROM_FAVORITES, R.string.action_remove_from_favorites);
                if (listItem.threadNumber != null) {
                    dialogMenu.addItem(MENU_RENAME, R.string.action_rename);
                }
            }
            dialogMenu.show();
            return true;
        }
        }
    }
    return false;
}

From source file:com.richtodd.android.quiltdesign.app.QuiltEditActivity.java

private void populateLayoutBlocks() {
    List<BlockContainerEntry> entries;
    try {/*from ww w . j  av a 2s .c  om*/
        Repository repository = Repository.getDefaultRepository(this);
        BlockContainer blocks = repository.getBlocks();
        entries = blocks.getEntries(true);
    } catch (RepositoryException ex) {
        return;
    }

    LinearLayout layoutRow = null;

    for (BlockContainerEntry entry : entries) {
        View view = QuiltEditActivity.this.getLayoutInflater().inflate(R.layout.listentry_block_selector, null);

        ImageView image_thumbnail = (ImageView) view.findViewById(R.id.image_thumbnail);
        image_thumbnail.setImageBitmap(entry.getThumbnail());

        view.setTag(entry.getBlockName());
        view.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                String blockName = (String) v.getTag();
                try {
                    getQuiltEditFragment().setBlock(blockName);
                } catch (Exception e) {
                    Handle.asRuntimeError(e);
                }
            }
        });

        if (m_layout_blocks.getOrientation() == LinearLayout.HORIZONTAL) {
            m_layout_blocks.addView(view);
        } else {
            if (layoutRow != null && layoutRow.getChildCount() == m_layout_blocks.getNumColumns()) {
                layoutRow = null;
            }
            if (layoutRow == null) {
                layoutRow = new LinearLayout(this);
                layoutRow.setOrientation(LinearLayout.HORIZONTAL);
                m_layout_blocks.addView(layoutRow);
            }
            layoutRow.addView(view);
        }
    }
}

From source file:org.telegram.ui.ThemeActivity.java

private void openThemeCreate() {
    final EditTextBoldCursor editText = new EditTextBoldCursor(getParentActivity());
    editText.setBackgroundDrawable(Theme.createEditTextDrawable(getParentActivity(), true));

    AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
    builder.setTitle(LocaleController.getString("NewTheme", R.string.NewTheme));
    builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
    builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), (dialog, which) -> {

    });/*  w w w  . j a  v  a 2  s. com*/

    LinearLayout linearLayout = new LinearLayout(getParentActivity());
    linearLayout.setOrientation(LinearLayout.VERTICAL);
    builder.setView(linearLayout);

    final TextView message = new TextView(getParentActivity());
    message.setText(LocaleController.formatString("EnterThemeName", R.string.EnterThemeName));
    message.setTextSize(16);
    message.setPadding(AndroidUtilities.dp(23), AndroidUtilities.dp(12), AndroidUtilities.dp(23),
            AndroidUtilities.dp(6));
    message.setTextColor(Theme.getColor(Theme.key_dialogTextBlack));
    linearLayout.addView(message,
            LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));

    editText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
    editText.setTextColor(Theme.getColor(Theme.key_dialogTextBlack));
    editText.setMaxLines(1);
    editText.setLines(1);
    editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
    editText.setGravity(Gravity.LEFT | Gravity.TOP);
    editText.setSingleLine(true);
    editText.setImeOptions(EditorInfo.IME_ACTION_DONE);
    editText.setCursorColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
    editText.setCursorSize(AndroidUtilities.dp(20));
    editText.setCursorWidth(1.5f);
    editText.setPadding(0, AndroidUtilities.dp(4), 0, 0);
    linearLayout.addView(editText,
            LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 36, Gravity.TOP | Gravity.LEFT, 24, 6, 24, 0));
    editText.setOnEditorActionListener((textView, i, keyEvent) -> {
        AndroidUtilities.hideKeyboard(textView);
        return false;
    });
    final AlertDialog alertDialog = builder.create();
    alertDialog.setOnShowListener(dialog -> AndroidUtilities.runOnUIThread(() -> {
        editText.requestFocus();
        AndroidUtilities.showKeyboard(editText);
    }));
    showDialog(alertDialog);
    alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(v -> {
        if (editText.length() == 0) {
            Vibrator vibrator = (Vibrator) ApplicationLoader.applicationContext
                    .getSystemService(Context.VIBRATOR_SERVICE);
            if (vibrator != null) {
                vibrator.vibrate(200);
            }
            AndroidUtilities.shakeView(editText, 2, 0);
            return;
        }
        ThemeEditorView themeEditorView = new ThemeEditorView();
        String name = editText.getText().toString() + ".attheme";
        themeEditorView.show(getParentActivity(), name);
        Theme.saveCurrentTheme(name, true);
        updateRows();
        alertDialog.dismiss();

        SharedPreferences preferences = MessagesController.getGlobalMainSettings();
        if (preferences.getBoolean("themehint", false)) {
            return;
        }
        preferences.edit().putBoolean("themehint", true).commit();
        try {
            Toast.makeText(getParentActivity(),
                    LocaleController.getString("CreateNewThemeHelp", R.string.CreateNewThemeHelp),
                    Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            FileLog.e(e);
        }
    });
}

From source file:terse.a1.TerseActivity.java

private void viewPath9display(String path, LayoutParams widgetParams) {
    String explain;//from ww w .ja v a2 s  .  c om
    if (terp_error != null) {
        explain = "terp_error = " + terp_error;
    } else {
        try {
            terp.say("Sending to terp: %s", path);
            final Dict d = terp.handleUrl(path, taQuery);
            explain = "DEFAULT EXPLANATION:\n\n" + d.toString();

            Str TYPE = d.cls.terp.newStr("type");
            Str VALUE = d.cls.terp.newStr("value");
            Str TITLE = d.cls.terp.newStr("title");
            Str type = (Str) d.dict.get(TYPE);
            Ur value = d.dict.get(VALUE);
            Ur title = d.dict.get(TITLE);

            // {
            // double ticks = Static.floatAt(d, "ticks", -1);
            // double nanos = Static.floatAt(d, "nanos", -1);
            // Toast.makeText(
            // getApplicationContext(),
            // Static.fmt("%d ticks, %.3f secs", (long) ticks,
            // (double) nanos / 1e9), Toast.LENGTH_SHORT)
            // .show();
            // }

            if (type.str.equals("list") && value instanceof Vec) {
                final ArrayList<Ur> v = ((Vec) value).vec;
                final ArrayList<String> labels = new ArrayList<String>();
                final ArrayList<String> links = new ArrayList<String>();
                for (int i = 0; i < v.size(); i++) {
                    Ur item = v.get(i);
                    String label = item instanceof Str ? ((Str) item).str : item.toString();
                    if (item instanceof Vec && ((Vec) item).vec.size() == 2) {
                        // OLD STYLE
                        label = ((Vec) item).vec.get(0).toString();
                        Matcher m = LINK_P.matcher(label);
                        if (m.lookingAt()) {
                            label = m.group(2) + " " + m.group(3);
                        }
                        label += "    [" + ((Vec) item).vec.get(1).toString().length() + "]";
                        links.add(null); // Use old style, not links.
                    } else {
                        // NEW STYLE
                        label = item.toString();
                        if (label.charAt(0) == '/') {
                            String link = Terp.WHITE_PLUS.split(label, 2)[0];
                            links.add(link);
                        } else {
                            links.add("");
                        }
                    }
                    labels.add(label);
                }
                if (labels.size() != links.size())
                    terp.toss("lables#%d links#%d", labels.size(), links.size());

                ListView listv = new ListView(this);
                listv.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item, labels));
                listv.setLayoutParams(widgetParams);
                listv.setTextFilterEnabled(true);

                listv.setOnItemClickListener(new OnItemClickListener() {
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        // When clicked, show a toast with the TextView text
                        // Toast.makeText(getApplicationContext(),
                        // ((TextView) view).getText(),
                        // Toast.LENGTH_SHORT).show();
                        String toast_text = ((TextView) view).getText().toString();
                        // if (v.get(position) instanceof Vec) {
                        if (links.get(position) == null) {
                            // OLD STYLE
                            Vec pair = (Vec) v.get(position);
                            if (pair.vec.size() == 2) {
                                if (pair.vec.get(0) instanceof Str) {
                                    String[] words = ((Str) pair.vec.get(0)).str.split("\\|");
                                    Log.i("TT-WORDS", terp.arrayToString(words));
                                    toast_text += "\n\n" + Static.arrayToString(words);
                                    if (words[1].equals("link")) {
                                        Uri uri = new Uri.Builder().scheme("terse").path(words[2]).build();
                                        Intent intent = new Intent("android.intent.action.MAIN", uri);
                                        intent.setClass(getApplicationContext(), TerseActivity.class);

                                        startActivity(intent);
                                    }
                                }
                            }
                        } else {
                            // NEW STYLE
                            terp.say("NEW STYLE LIST SELECT #%d link=<%s> label=<%s>", position,
                                    links.get(position), labels.get(position));
                            if (links.get(position).length() > 0) {
                                Uri uri = new Uri.Builder().scheme("terse").path(links.get(position)).build();
                                Intent intent = new Intent("android.intent.action.MAIN", uri);
                                intent.setClass(getApplicationContext(), TerseActivity.class);

                                startActivity(intent);
                            }
                        }
                        // }
                        // Toast.makeText(getApplicationContext(),
                        // ((TextView) view).getText(),
                        // Toast.LENGTH_SHORT).show();
                    }
                });
                setContentView(listv);
                return;
            } else if (type.str.equals("edit") && value instanceof Str) {
                final EditText ed = new EditText(this);

                ed.setText(taSaveMe == null ? value.toString() : taSaveMe);

                ed.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE
                        | InputType.TYPE_TEXT_VARIATION_LONG_MESSAGE | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
                ed.setLayoutParams(widgetParams);
                // ed.setTextSize(TypedValue.COMPLEX_UNIT_SP, 22);
                ed.setTextAppearance(this, R.style.teletype);
                ed.setBackgroundColor(Color.BLACK);
                ed.setGravity(Gravity.TOP);
                ed.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_INSET);
                ed.setVerticalFadingEdgeEnabled(true);
                ed.setVerticalScrollBarEnabled(true);
                ed.setOnKeyListener(new OnKeyListener() {
                    public boolean onKey(View v, int keyCode, KeyEvent event) {
                        // If the event is a key-down event on the "enter"
                        // button
                        // if ((event.getAction() == KeyEvent.ACTION_DOWN)
                        // &&
                        // (keyCode == KeyEvent.KEYCODE_ENTER)) {
                        // // Perform action on key press
                        // Toast.makeText(TerseActivity.this, ed.getText(),
                        // Toast.LENGTH_SHORT).show();
                        // return true;
                        // }
                        return false;
                    }
                });

                Button btn = new Button(this);
                btn.setText("Save");
                btn.setOnClickListener(new OnClickListener() {
                    public void onClick(View v) {
                        // Perform action on clicks
                        String text = ed.getText().toString();
                        text = Parser.charSubsts(text);
                        Toast.makeText(TerseActivity.this, text, Toast.LENGTH_SHORT).show();
                        String action = stringAt(d, "action");
                        String query = "";

                        String f1 = stringAt(d, "field1");
                        String v1 = stringAt(d, "value1");
                        String f2 = stringAt(d, "field2");
                        String v2 = stringAt(d, "value2");
                        f1 = (f1 == null) ? "f1null" : f1;
                        v1 = (v1 == null) ? "v1null" : v1;
                        f2 = (f2 == null) ? "f2null" : f2;
                        v2 = (v2 == null) ? "v2null" : v2;

                        startTerseActivity(action, query, stringAt(d, "field1"), stringAt(d, "value1"),
                                stringAt(d, "field2"), stringAt(d, "value2"), "text", text);
                    }
                });

                LinearLayout linear = new LinearLayout(this);
                linear.setOrientation(LinearLayout.VERTICAL);
                linear.addView(btn);
                linear.addView(ed);
                setContentView(linear);
                return;

            } else if (type.str.equals("draw") && value instanceof Vec) {
                Vec v = ((Vec) value);
                DrawView dv = new DrawView(this, v.vec, d);
                dv.setLayoutParams(widgetParams);
                setContentView(dv);
                return;
            } else if (type.str.equals("live")) {
                Blk blk = value.mustBlk();
                Blk event = Static.urAt(d, "event").asBlk();
                TerseSurfView tsv = new TerseSurfView(this, blk, event);
                setContentView(tsv);
                return;
            } else if (type.str.equals("fnord")) {
                Blk blk = value.mustBlk();
                Blk event = Static.urAt(d, "event").asBlk();
                FnordView fnord = new FnordView(this, blk, event);
                setContentView(fnord);
                return;
            } else if (type.str.equals("world") && value instanceof Str) {
                String newWorld = value.toString();
                if (Terp.WORLD_P.matcher(newWorld).matches()) {
                    world = newWorld;
                    resetTerp();
                    explain = Static.fmt("Switching to world <%s>\nUse menu to go Home.", world);
                    Toast.makeText(getApplicationContext(), explain, Toast.LENGTH_LONG).show();
                } else {
                    terp.toss("Bad world syntax (must be 3 letters then 0 to 3 digits: <%s>", newWorld);
                }
                // Fall thru for explainv.setText(explain).
            } else if (type.str.equals("text")) {
                explain = "<<< " + title + " >>>\n\n" + value.toString();
                // Fall thru for explainv.setText(explain).
            } else if (type.str.equals("html")) {
                final WebView webview = new WebView(this);
                // webview.loadData(value.toString(), "text/html", null);
                webview.loadDataWithBaseURL("terse://terse", value.toString(), "text/html", "UTF-8", null);
                webview.setWebViewClient(new WebViewClient() {
                    @Override
                    public boolean shouldOverrideUrlLoading(WebView view, String url) {
                        // terp.say("WebView UrlLoading: url=%s", url);
                        URI uri = URI.create("" + url);
                        // terp.say("WebView UrlLoading: URI=%s", uri);
                        terp.say("WebView UrlLoading: getPath=%s", uri.getPath());
                        terp.say("WebView UrlLoading: getQuery=%s", uri.getQuery());

                        // Toast.makeText(getApplicationContext(),
                        // uri.toASCIIString(), Toast.LENGTH_SHORT)
                        // .show();
                        // webview.invalidate();
                        //
                        // TextView quick = new
                        // TextView(TerseActivity.this);
                        // quick.setText(uri.toASCIIString());
                        // quick.setBackgroundColor(Color.BLACK);
                        // quick.setTextColor(Color.WHITE);
                        // setContentView(quick);

                        startTerseActivity(uri.getPath(), uri.getQuery());

                        return true;
                    }
                });

                // webview.setWebChromeClient(new WebChromeClient());
                webview.getSettings().setBuiltInZoomControls(true);
                // webview.getSettings().setJavaScriptEnabled(true);
                webview.getSettings().setDefaultFontSize(18);
                webview.getSettings().setNeedInitialFocus(true);
                webview.getSettings().setSupportZoom(true);
                webview.getSettings().setSaveFormData(true);
                setContentView(webview);

                // ScrollView scrollv = new ScrollView(this);
                // scrollv.addView(webview);
                // setContentView(scrollv);
                return;
            } else {
                explain = "Unknown page type: " + type.str + " with vaule type: " + value.cls
                        + "\n\n##############\n\n";
                explain += value.toString();
                // Fall thru for explainv.setText(explain).
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            explain = Static.describe(ex);
        }
    }

    TextView explainv = new TextView(this);
    explainv.setText(explain);
    explainv.setBackgroundColor(Color.BLACK);
    explainv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 24);
    explainv.setTextColor(Color.YELLOW);

    SetContentViewWithHomeButtonAndScroll(explainv);
}

From source file:foam.jellyfish.StarwispBuilder.java

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

    try {// w  w  w .j ava 2 s .c  om
        String type = arr.getString(0);

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

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

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

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

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

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

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

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

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

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

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

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

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

            String image = arr.getString(2);

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

            parent.addView(v);
        }

        if (type.equals("text-view")) {
            TextView v = new TextView(ctx);
            v.setId(arr.getInt(1));
            v.setText(Html.fromHtml(arr.getString(2)));
            v.setTextSize(arr.getInt(3));
            v.setMovementMethod(LinkMovementMethod.getInstance());
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4)));
            if (arr.length() > 5) {
                if (arr.getString(5).equals("left")) {
                    v.setGravity(Gravity.LEFT);
                } else {
                    if (arr.getString(5).equals("fill")) {
                        v.setGravity(Gravity.FILL);
                    } else {
                        v.setGravity(Gravity.CENTER);
                    }
                }
            } else {
                v.setGravity(Gravity.LEFT);
            }
            v.setTypeface(((StarwispActivity) ctx).m_Typeface);
            parent.addView(v);
        }

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

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

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

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

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

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

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

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

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

            parent.addView(v);
        }

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

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

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

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

                public void onStartTrackingTouch(SeekBar v) {
                }

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

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

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

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

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

            parent.addView(v);
        }

        if (type.equals("nomadic")) {
            final int wid = arr.getInt(1);
            NomadicSurfaceView v = new NomadicSurfaceView(ctx, wid);
            v.setId(wid);
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));

            parent.addView(v);
        }

        /*
                    if (type.equals("canvas")) {
        StarwispCanvas v = new StarwispCanvas(ctx);
        final int wid = arr.getInt(1);
        v.setId(wid);
        v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
        v.SetDrawList(arr.getJSONArray(3));
        parent.addView(v);
                    }
                
                    if (type.equals("camera-preview")) {
        PictureTaker pt = new PictureTaker();
        CameraPreview v = new CameraPreview(ctx,pt);
        final int wid = arr.getInt(1);
        v.setId(wid);
                
                
        //              LinearLayout.LayoutParams lp =
        //  new LinearLayout.LayoutParams(minWidth, minHeight, 1);
                
        v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
                
        //                v.setLayoutParams(lp);
        parent.addView(v);
                    }
        */
        if (type.equals("button-grid")) {
            LinearLayout horiz = new LinearLayout(ctx);
            final int id = arr.getInt(1);
            final String buttontype = arr.getString(2);
            horiz.setId(id);
            horiz.setOrientation(LinearLayout.HORIZONTAL);
            parent.addView(horiz);
            int height = arr.getInt(3);
            int textsize = arr.getInt(4);
            LinearLayout.LayoutParams lp = BuildLayoutParams(arr.getJSONArray(5));
            JSONArray buttons = arr.getJSONArray(6);
            int count = buttons.length();
            int vertcount = 0;
            LinearLayout vert = null;

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

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

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

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

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

}

From source file:com.saulcintero.moveon.fragments.Statistics.java

private void paintData(int sql_option, int activity) {
    boolean isMetric = FunctionUtils.checkIfUnitsAreMetric(mContext);

    sum_distance = 0;//w  w w  .j  a  v a2s.c o m
    sum_kcal = 0;
    sum_time = 0;
    sum_up_accum_altitude = 0;
    sum_down_accum_altitude = 0;
    sum_avg_speed = 0;
    sum_steps = 0;
    sum_avg_hr = 0;
    practices_counter = 0;
    hr_practices_counter = 0;

    int[] colors = { Color.rgb(111, 183, 217), Color.rgb(54, 165, 54), Color.rgb(246, 103, 88),
            Color.rgb(234, 206, 74), Color.rgb(246, 164, 83), Color.LTGRAY, Color.rgb(35, 142, 36),
            Color.rgb(0, 129, 125), Color.rgb(0, 0, 220), Color.rgb(255, 255, 0), Color.rgb(255, 215, 0),
            Color.rgb(184, 134, 11), Color.rgb(245, 245, 220), Color.rgb(139, 137, 137), Color.rgb(96, 57, 138),
            Color.rgb(176, 0, 103), Color.rgb(77, 19, 106), Color.rgb(218, 0, 0), Color.rgb(252, 115, 0),
            Color.rgb(243, 42, 0), Color.rgb(255, 202, 44), Color.rgb(176, 214, 7), Color.rgb(255, 235, 44),
            Color.rgb(255, 255, 255), Color.rgb(186, 29, 29), Color.rgb(146, 436, 20), Color.rgb(245, 175, 209),
            Color.rgb(29, 91, 139), Color.rgb(128, 128, 0), Color.rgb(128, 0, 128), Color.rgb(0, 128, 128),
            Color.rgb(246, 233, 207), Color.rgb(231, 56, 142), Color.rgb(173, 141, 193),
            Color.rgb(191, 199, 32), Color.rgb(0, 128, 0), Color.rgb(4, 136, 125), Color.rgb(140, 0, 255),
            Color.rgb(135, 0, 118), Color.rgb(2, 132, 132), Color.rgb(0, 127, 204), Color.rgb(128, 250, 255),
            Color.rgb(192, 192, 192), Color.rgb(207, 94, 97), Color.rgb(137, 189, 199),
            Color.rgb(138, 168, 161), Color.rgb(171, 166, 191), Color.rgb(199, 153, 125) };

    DBManager = null;
    cursor = null;

    distance_distribution = null;
    kcal_distribution = null;
    time_distribution = null;

    DBManager = new DataManager(mContext);
    DBManager.Open();

    cursor = DBManager.CustomQuery(getString(R.string.checking_routes), "SELECT * FROM routes");

    cursor.moveToFirst();
    if (cursor.getCount() > 0) {
        between_dates_query_part = "";

        DatesTypes whichDate = DatesTypes.values()[sql_option];
        switch (whichDate) {
        case ALL_DATES:
            removeCustomDataValues();

            if (activity > 0) {
                cursor = DBManager.CustomQuery(
                        getString(R.string.selecting_all_routes) + " " + getString(R.string.filter_by_activity)
                                + " " + getString(R.string.and) + " " + getString(R.string.group_by_activities),
                        "SELECT category_id, COUNT(*) AS count_practices, SUM(distance) AS sum_distance, "
                                + "SUM(kcal) AS sum_kcal, SUM(time) AS sum_time, SUM(avg_speed) AS sum_avg_speed, "
                                + "SUM(up_accum_altitude) AS sum_up_accum_altitude, "
                                + "SUM(down_accum_altitude) AS sum_down_accum_altitude, "
                                + "SUM(steps) AS sum_steps " + "FROM routes " + "WHERE category_id = '"
                                + activity + "' " + "GROUP BY category_id");
            } else {
                cursor = DBManager.CustomQuery(
                        getString(R.string.selecting_all_routes) + " "
                                + getString(R.string.group_by_activities),
                        "SELECT category_id, COUNT(*) AS count_practices, SUM(distance) AS sum_distance, "
                                + "SUM(kcal) AS sum_kcal, SUM(time) AS sum_time, SUM(avg_speed) AS sum_avg_speed, "
                                + "SUM(up_accum_altitude) AS sum_up_accum_altitude, "
                                + "SUM(down_accum_altitude) AS sum_down_accum_altitude, "
                                + "SUM(steps) AS sum_steps " + "FROM routes GROUP BY category_id");
            }

            break;
        case THIS_YEAR:
            removeCustomDataValues();

            if (activity > 0) {
                cursor = DBManager.CustomQuery(
                        getString(R.string.selecting_this_year_routes) + " "
                                + getString(R.string.filter_by_activity) + " " + getString(R.string.and) + " "
                                + getString(R.string.group_by_activities),
                        "SELECT category_id, COUNT(*) AS count_practices, SUM(distance) AS sum_distance, "
                                + "SUM(kcal) AS sum_kcal, SUM(time) AS sum_time, SUM(avg_speed) AS sum_avg_speed, "
                                + "SUM(up_accum_altitude) AS sum_up_accum_altitude, "
                                + "SUM(down_accum_altitude) AS sum_down_accum_altitude, "
                                + "SUM(steps) AS sum_steps " + "FROM routes " + "WHERE substr(date,7) = '"
                                + Calendar.getInstance().get(Calendar.YEAR) + "' " + "AND category_id = '"
                                + activity + "' " + "GROUP BY category_id");
            } else {
                cursor = DBManager.CustomQuery(
                        getString(R.string.selecting_this_year_routes) + " "
                                + getString(R.string.group_by_activities),
                        "SELECT category_id, COUNT(*) AS count_practices, SUM(distance) AS sum_distance, "
                                + "SUM(kcal) AS sum_kcal, SUM(time) AS sum_time, SUM(avg_speed) AS sum_avg_speed, "
                                + "SUM(up_accum_altitude) AS sum_up_accum_altitude, "
                                + "SUM(down_accum_altitude) AS sum_down_accum_altitude, "
                                + "SUM(steps) AS sum_steps " + "FROM routes " + "WHERE substr(date,7) = '"
                                + Calendar.getInstance().get(Calendar.YEAR) + "' " + "GROUP BY category_id");
            }

            between_dates_query_part = "substr(date,7) = '" + Calendar.getInstance().get(Calendar.YEAR) + "' ";

            break;
        case THIS_MONTH:
            removeCustomDataValues();

            int month = Calendar.getInstance().get(Calendar.MONTH) + 1;
            String sMonth = String.valueOf(month);
            if (month < 10)
                sMonth = "0" + sMonth;

            if (activity > 0) {
                cursor = DBManager.CustomQuery(
                        getString(R.string.selecting_this_month_routes) + " "
                                + getString(R.string.filter_by_activity) + " " + getString(R.string.and) + " "
                                + getString(R.string.group_by_activities),
                        "SELECT category_id, COUNT(*) AS count_practices, SUM(distance) AS sum_distance, "
                                + "SUM(kcal) AS sum_kcal, SUM(time) AS sum_time, SUM(avg_speed) AS sum_avg_speed, "
                                + "SUM(up_accum_altitude) AS sum_up_accum_altitude, "
                                + "SUM(down_accum_altitude) AS sum_down_accum_altitude, "
                                + "SUM(steps) AS sum_steps " + "FROM routes " + "WHERE substr(date,4,2) = '"
                                + sMonth + "' " + "AND substr(date,7) = '"
                                + Calendar.getInstance().get(Calendar.YEAR) + "' " + "AND category_id = '"
                                + activity + "' " + "GROUP BY category_id");
            } else {
                cursor = DBManager.CustomQuery(
                        getString(R.string.selecting_this_month_routes) + " "
                                + getString(R.string.group_by_activities),
                        "SELECT category_id, COUNT(*) AS count_practices, SUM(distance) AS sum_distance, "
                                + "SUM(kcal) AS sum_kcal, SUM(time) AS sum_time, SUM(avg_speed) AS sum_avg_speed, "
                                + "SUM(up_accum_altitude) AS sum_up_accum_altitude, "
                                + "SUM(down_accum_altitude) AS sum_down_accum_altitude, "
                                + "SUM(steps) AS sum_steps " + "FROM routes " + "WHERE substr(date,4,2) = '"
                                + sMonth + "' " + "AND substr(date,7) = '"
                                + Calendar.getInstance().get(Calendar.YEAR) + "' " + "GROUP BY category_id");
            }

            between_dates_query_part = "substr(date,4,2) = '" + sMonth + "' AND substr(date,7) = '"
                    + Calendar.getInstance().get(Calendar.YEAR) + "' ";

            break;
        case THIS_WEAK:
            removeCustomDataValues();

            Calendar c1 = Calendar.getInstance();
            c1.setFirstDayOfWeek(Calendar.MONDAY);
            c1.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);

            int y = c1.get(Calendar.YEAR);
            int m = c1.get(Calendar.MONTH) + 1;
            int d = c1.get(Calendar.DAY_OF_MONTH);

            String sYear1 = String.valueOf(y);
            String sMonth1 = String.valueOf(m);
            if (m < 10)
                sMonth1 = "0" + sMonth1;
            String sDay1 = String.valueOf(d);
            if (d < 10)
                sDay1 = "0" + sDay1;

            c1.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);

            int y2 = c1.get(Calendar.YEAR);
            int m2 = c1.get(Calendar.MONTH) + 1;
            int d2 = c1.get(Calendar.DAY_OF_MONTH);

            String sYear2 = String.valueOf(y2);
            String sMonth2 = String.valueOf(m2);
            if (m2 < 10)
                sMonth2 = "0" + sMonth2;
            String sDay2 = String.valueOf(d2);
            if (d2 < 10)
                sDay2 = "0" + sDay2;

            if (activity > 0) {
                cursor = DBManager.CustomQuery(
                        getString(R.string.selecting_this_weak_routes) + " "
                                + getString(R.string.filter_by_activity) + " " + getString(R.string.and) + " "
                                + getString(R.string.group_by_activities),
                        "SELECT category_id, COUNT(*) AS count_practices, SUM(distance) AS sum_distance, "
                                + "SUM(kcal) AS sum_kcal, SUM(time) AS sum_time, SUM(avg_speed) AS sum_avg_speed, "
                                + "SUM(up_accum_altitude) AS sum_up_accum_altitude, "
                                + "SUM(down_accum_altitude) AS sum_down_accum_altitude, "
                                + "SUM(steps) AS sum_steps " + "FROM routes "
                                + "WHERE substr(date,7)||substr(date,4,2)||substr(date,1,2) " + "BETWEEN '"
                                + sYear1 + sMonth1 + sDay1 + "' AND '" + sYear2 + sMonth2 + sDay2 + "' "
                                + "AND category_id = '" + activity + "' " + "GROUP BY category_id");
            } else {
                cursor = DBManager.CustomQuery(
                        getString(R.string.selecting_this_weak_routes) + " "
                                + getString(R.string.group_by_activities),
                        "SELECT category_id, COUNT(*) AS count_practices, SUM(distance) AS sum_distance, "
                                + "SUM(kcal) AS sum_kcal, SUM(time) AS sum_time, SUM(avg_speed) AS sum_avg_speed, "
                                + "SUM(up_accum_altitude) AS sum_up_accum_altitude, "
                                + "SUM(down_accum_altitude) AS sum_down_accum_altitude, "
                                + "SUM(steps) AS sum_steps " + "FROM routes "
                                + "WHERE substr(date,7)||substr(date,4,2)||substr(date,1,2) " + "BETWEEN '"
                                + sYear1 + sMonth1 + sDay1 + "' AND '" + sYear2 + sMonth2 + sDay2 + "' "
                                + "GROUP BY category_id");
            }

            between_dates_query_part = "substr(date,7)||substr(date,4,2)||substr(date,1,2) " + "BETWEEN '"
                    + sYear1 + sMonth1 + sDay1 + "' AND '" + sYear2 + sMonth2 + sDay2 + "' ";

            break;
        case BETWEEN_TWO_DATES:
            String mYear1 = String.valueOf(year1);
            String mMonth1 = String.valueOf(month1);
            if (month1 < 10)
                mMonth1 = "0" + mMonth1;
            String mDay1 = String.valueOf(day1);
            if (day1 < 10)
                mDay1 = "0" + mDay1;

            String mYear2 = String.valueOf(year2);
            String mMonth2 = String.valueOf(month2);
            if (month2 < 10)
                mMonth2 = "0" + mMonth2;
            String mDay2 = String.valueOf(day2);
            if (day2 < 10)
                mDay2 = "0" + mDay2;

            customDay1 = mDay1;
            customDay2 = mDay2;
            customMonth1 = mMonth1;
            customMonth2 = mMonth2;
            customYear1 = mYear1;
            customYear2 = mYear2;

            if (activity > 0) {
                cursor = DBManager.CustomQuery("Seleccionando las rutas de este mes agrupadas por actividad",
                        "SELECT category_id, COUNT(*) AS count_practices, SUM(distance) AS sum_distance, "
                                + "SUM(kcal) AS sum_kcal, SUM(time) AS sum_time, SUM(avg_speed) AS sum_avg_speed, "
                                + "SUM(up_accum_altitude) AS sum_up_accum_altitude, "
                                + "SUM(down_accum_altitude) AS sum_down_accum_altitude, "
                                + "SUM(steps) AS sum_steps " + "FROM routes "
                                + "WHERE substr(date,7)||substr(date,4,2)||substr(date,1,2) " + "BETWEEN '"
                                + customYear1 + customMonth1 + customDay1 + "' AND '" + customYear2
                                + customMonth2 + customDay2 + "' " + "AND category_id = '" + activity + "' "
                                + "GROUP BY category_id");
            } else {
                cursor = DBManager.CustomQuery("Seleccionando las rutas de este mes agrupadas por actividad",
                        "SELECT category_id, COUNT(*) AS count_practices, SUM(distance) AS sum_distance, "
                                + "SUM(kcal) AS sum_kcal, SUM(time) AS sum_time, SUM(avg_speed) AS sum_avg_speed, "
                                + "SUM(up_accum_altitude) AS sum_up_accum_altitude, "
                                + "SUM(down_accum_altitude) AS sum_down_accum_altitude, "
                                + "SUM(steps) AS sum_steps " + "FROM routes "
                                + "WHERE substr(date,7)||substr(date,4,2)||substr(date,1,2) " + "BETWEEN '"
                                + customYear1 + customMonth1 + customDay1 + "' AND '" + customYear2
                                + customMonth2 + customDay2 + "' " + "GROUP BY category_id");
            }

            between_dates_query_part = "substr(date,7)||substr(date,4,2)||substr(date,1,2) " + "BETWEEN '"
                    + customYear1 + customMonth1 + customDay1 + "' AND '" + customYear2 + customMonth2
                    + customDay2 + "' ";

            break;
        }
        cursor.moveToFirst();

        base_layout.setVisibility(View.VISIBLE);
        scrollView.setVisibility(View.VISIBLE);
        layout1.setVisibility(View.VISIBLE);
        layout2.setVisibility(View.VISIBLE);
        layout3.setVisibility(View.VISIBLE);
        layout4.setVisibility(View.VISIBLE);

        distance_distribution = new float[cursor.getCount()];
        kcal_distribution = new int[cursor.getCount()];
        time_distribution = new int[cursor.getCount()];

        int i = 0;

        mTableLayout.removeAllViews();

        while (!cursor.isAfterLast()) {
            TextView color = new TextView(mContext);
            TextView label = new TextView(mContext);
            TextView value = new TextView(mContext);
            LinearLayout.LayoutParams colorLayoutParams = new LinearLayout.LayoutParams(
                    new LayoutParams(FunctionUtils.calculateDpFromPx(mContext, 20),
                            FunctionUtils.calculateDpFromPx(mContext, 20)));
            colorLayoutParams.setMargins(0, 1, 5, 1);
            color.setLayoutParams(colorLayoutParams);
            label.setLayoutParams(
                    new LayoutParams(FunctionUtils.calculateDpFromPx(mContext, 95), LayoutParams.WRAP_CONTENT));
            label.setTypeface(null, Typeface.BOLD);
            label.setTextColor(Color.parseColor("#b5b5b5"));
            value.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
            value.setTextColor(res.getColor(R.color.white));

            color.setBackgroundColor(colors[i]);

            label.setText(activities[cursor.getInt(cursor.getColumnIndex("category_id")) - 1] + ":");
            value.setText((isMetric
                    ? String.valueOf(cursor.getFloat(cursor.getColumnIndex("sum_distance"))) + " "
                            + getString(R.string.long_unit1_detail_1) + ", "
                    : String.valueOf(FunctionUtils.customizedRound(
                            ((cursor.getFloat(cursor.getColumnIndex("sum_distance")) * 1000f) / 1609f), 2))
                            + " " + getString(R.string.long_unit2_detail_1) + ", ")
                    + String.valueOf((int) cursor.getFloat(cursor.getColumnIndex("sum_kcal"))) + " "
                    + getString(R.string.tell_calories_setting_details) + ", "
                    + String.valueOf(FunctionUtils.statisticsFormatTime(mContext,
                            (long) cursor.getFloat(cursor.getColumnIndex("sum_time")))));

            LinearLayout mLinearLayout = new LinearLayout(mContext);
            mLinearLayout
                    .setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            mLinearLayout.setOrientation(0);
            mLinearLayout.addView(color);
            mLinearLayout.addView(label);
            mLinearLayout.addView(value);
            mTableLayout.addView(mLinearLayout);

            sum_distance = sum_distance + cursor.getFloat(cursor.getColumnIndex("sum_distance"));
            sum_kcal = sum_kcal + cursor.getInt(cursor.getColumnIndex("sum_kcal"));
            sum_time = sum_time + cursor.getInt(cursor.getColumnIndex("sum_time"));
            sum_up_accum_altitude = sum_up_accum_altitude
                    + cursor.getInt(cursor.getColumnIndex("sum_up_accum_altitude"));
            sum_down_accum_altitude = sum_down_accum_altitude
                    + cursor.getInt(cursor.getColumnIndex("sum_down_accum_altitude"));
            sum_avg_speed = sum_avg_speed + cursor.getFloat(cursor.getColumnIndex("sum_avg_speed"));
            sum_steps = sum_steps + cursor.getInt(cursor.getColumnIndex("sum_steps"));

            distance_distribution[i] = cursor.getFloat(cursor.getColumnIndex("sum_distance"));
            kcal_distribution[i] = cursor.getInt(cursor.getColumnIndex("sum_kcal"));
            time_distribution[i] = cursor.getInt(cursor.getColumnIndex("sum_time"));

            practices_counter = practices_counter
                    + (int) cursor.getFloat(cursor.getColumnIndex("count_practices"));

            i++;

            cursor.moveToNext();
        }

        String activity_query_part = "";
        if (activity > 0)
            activity_query_part = " AND category_id = '" + activity + "'";

        if (between_dates_query_part.length() > 0) {
            cursor = DBManager.CustomQuery(getString(R.string.routes_with_hr),
                    "SELECT avg_hr FROM routes WHERE avg_hr > 0 AND " + between_dates_query_part
                            + activity_query_part);
        } else {
            cursor = DBManager.CustomQuery(getString(R.string.routes_with_hr),
                    "SELECT avg_hr FROM routes WHERE avg_hr > 0" + activity_query_part);
        }
        cursor.moveToFirst();
        if (cursor.getCount() > 0) {
            while (!cursor.isAfterLast()) {
                sum_avg_hr = sum_avg_hr + cursor.getInt(cursor.getColumnIndex("avg_hr"));
                hr_practices_counter += 1;

                cursor.moveToNext();
            }
        }

        text8.setText("");
        if (between_dates_query_part.length() > 0) {
            if (activity > 0)
                activity_query_part = " AND category_id = '" + activity + "' ";

            cursor = DBManager.CustomQuery(getString(R.string.selecting_most_used_shoes),
                    "SELECT shoe_id, COUNT(shoe_id) AS count_shoes " + "FROM routes " + "WHERE "
                            + between_dates_query_part + activity_query_part + "GROUP BY shoe_id "
                            + "ORDER BY count_shoes DESC");
        } else {
            if (activity > 0)
                activity_query_part = "WHERE category_id = '" + activity + "' ";

            cursor = DBManager.CustomQuery(getString(R.string.selecting_most_used_shoes_in_data_range),
                    "SELECT shoe_id, COUNT(shoe_id) AS count_shoes " + "FROM routes " + activity_query_part
                            + "GROUP BY shoe_id " + "ORDER BY count_shoes DESC");
        }
        cursor.moveToFirst();
        if (cursor.getCount() > 0) {
            int shoe = cursor.getInt(cursor.getColumnIndex("shoe_id"));
            if (cursor.getCount() > 1) {
                int[] shoes = new int[cursor.getCount()];
                int m = 0;
                while (!cursor.isAfterLast()) {
                    shoes[m] = cursor.getInt(cursor.getColumnIndex("shoe_id"));
                    m++;
                    cursor.moveToNext();
                }

                if (shoe == 0 && shoes.length > 1)
                    shoe = shoes[1];
            }

            if (shoe > 0) {
                cursor = DBManager.CustomQuery(getString(R.string.shoe_name),
                        "SELECT name FROM shoes WHERE _id = '" + shoe + "'");
                cursor.moveToFirst();
                text8.setText(cursor.getString(cursor.getColumnIndex("name")));
            }

        }

        text1.setText(String.valueOf(practices_counter));
        text2.setText(String.valueOf(FunctionUtils.statisticsFormatTime(mContext, (long) sum_time)));
        text3.setText(isMetric
                ? String.valueOf(FunctionUtils.customizedRound(sum_distance, 2)) + " "
                        + getString(R.string.long_unit1_detail_1)
                : String.valueOf(FunctionUtils.customizedRound(((sum_distance * 1000f) / 1609f), 2)) + " "
                        + getString(R.string.long_unit2_detail_1));
        text4.setText(
                isMetric ? String.valueOf(sum_up_accum_altitude) + " " + getString(R.string.long_unit1_detail_4)
                        : String.valueOf((int) (sum_up_accum_altitude * 1.0936f)) + " "
                                + getString(R.string.long_unit2_detail_4));
        text5.setText(isMetric
                ? String.valueOf(sum_down_accum_altitude) + " " + getString(R.string.long_unit1_detail_4)
                : String.valueOf((int) (sum_down_accum_altitude * 1.0936f)) + " "
                        + getString(R.string.long_unit2_detail_4));
        if ((sum_avg_speed > 0) && (practices_counter > 0)) {
            text6.setText((isMetric
                    ? String.valueOf(FunctionUtils.customizedRound((sum_avg_speed / practices_counter), 2))
                            + " " + getString(R.string.long_unit1_detail_2)
                    : String.valueOf(FunctionUtils
                            .customizedRound((((sum_avg_speed * 1000f) / 1609f) / practices_counter), 2)) + " "
                            + getString(R.string.long_unit2_detail_2)));
        } else {
            text6.setText(
                    getString(R.string.zero_value) + " " + (isMetric ? getString(R.string.long_unit1_detail_2)
                            : mContext.getString(R.string.long_unit2_detail_2)));
        }
        text7.setText(String.valueOf(
                FunctionUtils.calculateRitm(mContext, sum_time, String.valueOf(sum_distance), isMetric, false))
                + " " + (isMetric ? getString(R.string.long_unit1_detail_3)
                        : mContext.getString(R.string.long_unit2_detail_3)));
        text9.setText(String.valueOf(sum_kcal) + " " + getString(R.string.tell_calories_setting_details));
        text10.setText(String.valueOf(sum_steps));
        if ((sum_avg_hr > 0) && (hr_practices_counter > 0)) {
            text11.setText(String.valueOf(sum_avg_hr / hr_practices_counter) + " "
                    + getString(R.string.beats_per_minute));
        } else {
            text11.setText(getString(R.string.zero_value) + " " + getString(R.string.beats_per_minute));
        }
        if (sum_kcal > 0) {
            text12.setText(String.valueOf(sum_kcal / Constants.CHEESE_BURGER));
        } else {
            text12.setText(getString(R.string.zero_value));
        }
        if (sum_distance > 0) {
            text13.setText(String.valueOf(
                    FunctionUtils.customizedRound((sum_distance / Constants.ALL_THE_WAY_AROUND_THE_WORLD), 3)));
        } else {
            text13.setText(getString(R.string.zero_with_three_decimal_places_value));
        }
        if (sum_distance > 0) {
            double moon_distance = ((double) sum_distance) / ((double) Constants.TO_THE_MOON);
            text14.setText(String.valueOf(
                    FunctionUtils.customizedRound(Float.parseFloat(String.valueOf(moon_distance)), 1)));
        } else {
            text14.setText(getString(R.string.zero_with_one_decimal_place_value));
        }

        layout1.removeAllViews();
        layout2.removeAllViews();
        layout3.removeAllViews();

        mChartView1 = null;
        mChartView2 = null;
        mChartView3 = null;

        for (int h = 0; h < distance_distribution.length; h++) {
            float percent = 0;

            if (distance_distribution[h] > 0)
                percent = (distance_distribution[h] * 100) / sum_distance;

            if (sum_distance == 0)
                percent = 100 / distance_distribution.length;

            distance_distribution[h] = percent;
        }

        for (int b = 0; b < kcal_distribution.length; b++) {
            int percent = 0;

            if (sum_kcal > 0)
                percent = (kcal_distribution[b] * 100) / sum_kcal;

            if (sum_kcal == 0)
                percent = 100 / kcal_distribution.length;

            kcal_distribution[b] = percent;
        }

        final CategorySeries distance_distributionSeries = new CategorySeries("");
        for (int g = 0; g < distance_distribution.length; g++) {
            if (distance_distribution.length == 1) {
                distance_distributionSeries.add("", 100);
            } else {
                distance_distributionSeries.add("", distance_distribution[g]);
            }
        }

        final CategorySeries kcal_distributionSeries = new CategorySeries("");
        for (int p = 0; p < kcal_distribution.length; p++) {
            if (kcal_distribution.length == 1) {
                kcal_distributionSeries.add("", 100);
            } else {
                kcal_distributionSeries.add("", kcal_distribution[p]);
            }
        }

        final CategorySeries time_distributionSeries = new CategorySeries("");
        for (int l = 0; l < time_distribution.length; l++) {
            if (time_distribution.length == 1) {
                time_distributionSeries.add("", 100);
            } else {
                time_distributionSeries.add("", time_distribution[l]);
            }
        }

        DefaultRenderer defaultRenderer = new DefaultRenderer();
        DefaultRenderer defaultRenderer2 = new DefaultRenderer();
        DefaultRenderer defaultRenderer3 = new DefaultRenderer();

        defaultRenderer.setShowLabels(false);
        defaultRenderer.setZoomButtonsVisible(false);
        defaultRenderer.setStartAngle(180);
        defaultRenderer.setDisplayValues(false);
        defaultRenderer.setClickEnabled(true);
        defaultRenderer.setInScroll(true);
        defaultRenderer.setShowLegend(false);

        defaultRenderer2.setShowLabels(false);
        defaultRenderer2.setZoomButtonsVisible(false);
        defaultRenderer2.setStartAngle(180);
        defaultRenderer2.setDisplayValues(false);
        defaultRenderer2.setClickEnabled(true);
        defaultRenderer2.setInScroll(true);
        defaultRenderer2.setShowLegend(false);

        defaultRenderer3.setShowLabels(false);
        defaultRenderer3.setZoomButtonsVisible(false);
        defaultRenderer3.setStartAngle(180);
        defaultRenderer3.setDisplayValues(false);
        defaultRenderer3.setClickEnabled(true);
        defaultRenderer3.setInScroll(true);
        defaultRenderer3.setShowLegend(false);

        for (int u = 0; u < distance_distribution.length; u++) {
            SimpleSeriesRenderer seriesRenderer = new SimpleSeriesRenderer();
            seriesRenderer.setColor(colors[u]);
            seriesRenderer.setDisplayChartValues(true);
            seriesRenderer.setHighlighted(false);

            defaultRenderer.addSeriesRenderer(seriesRenderer);
        }

        for (int p = 0; p < kcal_distribution.length; p++) {
            SimpleSeriesRenderer seriesRenderer2 = new SimpleSeriesRenderer();
            seriesRenderer2.setColor(colors[p]);
            seriesRenderer2.setDisplayChartValues(true);
            seriesRenderer2.setHighlighted(false);

            defaultRenderer2.addSeriesRenderer(seriesRenderer2);
        }

        for (int o = 0; o < distance_distribution.length; o++) {
            SimpleSeriesRenderer seriesRenderer3 = new SimpleSeriesRenderer();
            seriesRenderer3.setColor(colors[o]);
            seriesRenderer3.setDisplayChartValues(true);
            seriesRenderer3.setHighlighted(false);

            defaultRenderer3.addSeriesRenderer(seriesRenderer3);
        }

        mChartView1 = ChartFactory.getPieChartView(mContext, distance_distributionSeries, defaultRenderer);
        mChartView2 = ChartFactory.getPieChartView(mContext, kcal_distributionSeries, defaultRenderer2);
        mChartView3 = ChartFactory.getPieChartView(mContext, time_distributionSeries, defaultRenderer3);

        layout1.addView(mChartView1);
        layout2.addView(mChartView2);
        layout3.addView(mChartView3);
    } else {
        base_layout.setVisibility(View.INVISIBLE);
        scrollView.setVisibility(View.INVISIBLE);
        layout1.setVisibility(View.INVISIBLE);
        layout2.setVisibility(View.INVISIBLE);
        layout3.setVisibility(View.INVISIBLE);
        layout4.setVisibility(View.INVISIBLE);
    }
    cursor.close();
    DBManager.Close();
}