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.retroteam.studio.retrostudio.EditorLandscape.java

/**
 * Create all the views associated with a track.
 * @param waveDrawableID//from  www . j  av  a 2  s  .c om
 * @param projectLoad
 * @return
 */

private ImageView addTrack(int waveDrawableID, boolean projectLoad) {
    //add the track with the measure adder to the view
    //get layout
    LinearLayout track_layout = (LinearLayout) findViewById(R.id.track_layout);

    //create track container
    HorizontalScrollView track_container = new HorizontalScrollView(getApplicationContext());
    track_container.setLayoutParams(new HorizontalScrollView.LayoutParams(
            HorizontalScrollView.LayoutParams.MATCH_PARENT, displaysize.y / 4));
    track_container.setBackground(getResources().getDrawable(R.color.track_container_bg));

    //create grid layout
    GridLayout track_grid = new GridLayout(getApplicationContext());
    track_grid.setColumnCount(100);
    track_grid.setRowCount(1);
    track_grid.setOrientation(GridLayout.HORIZONTAL);
    track_grid.setId(R.id.track_grid);

    //create linear layout for track id and wave
    LinearLayout track_identifier = new LinearLayout(getApplicationContext());
    track_identifier.setLayoutParams(new LinearLayout.LayoutParams(displaysize.x / 14, displaysize.y / 4));
    track_identifier.setOrientation(LinearLayout.VERTICAL);
    track_identifier.setBackgroundColor(getResources().getColor(R.color.black_overlay));

    //create textview for linear layout
    TextView track_num = new TextView(getApplicationContext());
    track_num.setText("1");
    track_num.setTextSize(45);
    track_num.setGravity(Gravity.CENTER | Gravity.CENTER_VERTICAL);

    //create imageview for linear layout
    ImageView track_type = new ImageView(getApplicationContext());
    track_type.setImageResource(waveDrawableID);
    track_type.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.MATCH_PARENT));

    //create "add measure" for grid layout
    ImageView add_measure = new ImageView(getApplicationContext());
    add_measure.setImageResource(R.drawable.measure_new);
    add_measure.setLayoutParams(new LinearLayout.LayoutParams((int) (displaysize.x / 3.32),
            LinearLayout.LayoutParams.MATCH_PARENT));
    if (projectLoad) {
        add_measure.setTag(R.id.TAG_ROW, trackReloadCounter);
        add_measure.setId(trackReloadCounter + 4200);
    } else {
        add_measure.setTag(R.id.TAG_ROW, theproject.size() - 1);
        add_measure.setId(theproject.size() - 1 + 4200);
    }

    add_measure.setTag(R.id.TAG_COLUMN, 0);
    add_measure.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            addMeasure(v, false);

        }
    });

    track_identifier.addView(track_num);
    if (projectLoad) {
        track_num.setText(Integer.toString(trackReloadCounter + 1));
        trackReloadCounter += 1;
    } else {
        track_num.setText(Integer.toString(theproject.size()));
    }
    track_num.setTextSize(45);
    track_identifier.addView(track_type);

    track_grid.addView(track_identifier);
    track_grid.addView(add_measure);

    track_container.addView(track_grid);

    track_layout.addView(track_container);

    return add_measure;

}

From source file:org.solovyev.android.messenger.BaseListFragment.java

@Override
public ViewGroup onCreateView(LayoutInflater inflater, ViewGroup container,
        @Nullable Bundle savedInstanceState) {
    Log.d(tag, "onCreateView");
    final LinearLayout root = new LinearLayout(themeContext);
    root.setOrientation(VERTICAL);

    if (listViewFilter != null) {
        final View filterView = listViewFilter.createView(savedInstanceState);
        root.addView(filterView, new LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT));
    }/*from   ww  w. j  a  va  2s.  co m*/

    final View listViewParent = createListView();

    final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(MATCH_PARENT, 0, 1f);
    params.gravity = CENTER_VERTICAL;
    root.addView(listViewParent, params);

    tryUpdateActionBar();

    multiPaneManager.onCreatePane(getActivity(), container, root);

    initViewStates(savedInstanceState);

    return root;
}

From source file:com.mediaexplorer.remote.MexRemoteActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);/*  w w  w  . ja  v a2 s. com*/

    this.setTitle(R.string.app_name);
    dbg = "MexWebremote";

    text_view = (TextView) findViewById(R.id.text);

    web_view = (WebView) findViewById(R.id.link_view);
    web_view.getSettings().setJavaScriptEnabled(true);/*
                                                      /* Future: setOverScrollMode is API level >8
                                                      * web_view.setOverScrollMode (OVER_SCROLL_NEVER);
                                                      */

    web_view.setBackgroundColor(0);

    web_view.setWebViewClient(new WebViewClient() {
        /* for some reason we only get critical errors so an auth error
         * is not handled here which is why there is some crack that test
         * the connection with a special httpclient
         */
        @Override
        public void onReceivedHttpAuthRequest(final WebView view, final HttpAuthHandler handler,
                final String host, final String realm) {
            String[] userpass = new String[2];

            userpass = view.getHttpAuthUsernamePassword(host, realm);

            HttpResponse response = null;
            HttpGet httpget;
            DefaultHttpClient httpclient;
            String target_host;
            int target_port;

            target_host = MexRemoteActivity.this.target_host;
            target_port = MexRemoteActivity.this.target_port;

            /* We may get null from getHttpAuthUsernamePassword which will
             * break the setCredentials so junk used instead to keep
             * it happy.
             */

            Log.d(dbg, "using the set httpauth, testing auth using client");
            try {
                if (userpass == null) {
                    userpass = new String[2];
                    userpass[0] = "none";
                    userpass[1] = "none";
                }
            } catch (Exception e) {
                userpass = new String[2];
                userpass[0] = "none";
                userpass[1] = "none";
            }

            /* Log.d ("debug",
             *  "trying: GET http://"+userpass[0]+":"+userpass[1]+"@"+target_host+":"+target_port+"/");
             */
            /* We're going to test the authentication credentials that we
             * have before using them so that we can act on the response.
             */

            httpclient = new DefaultHttpClient();

            httpget = new HttpGet("http://" + target_host + ":" + target_port + "/");

            httpclient.getCredentialsProvider().setCredentials(new AuthScope(target_host, target_port),
                    new UsernamePasswordCredentials(userpass[0], userpass[1]));

            try {
                response = httpclient.execute(httpget);
            } catch (IOException e) {
                Log.d(dbg, "Problem executing the http get");
                e.printStackTrace();
            }

            Log.d(dbg, "HTTP reponse:" + Integer.toString(response.getStatusLine().getStatusCode()));
            if (response.getStatusLine().getStatusCode() == 401) {
                /* We got Authentication failed (401) so ask user for u/p */

                /* login dialog box */
                final AlertDialog.Builder logindialog;
                final EditText user;
                final EditText pass;

                LinearLayout layout;
                LayoutParams params;

                TextView label_username;
                TextView label_password;

                logindialog = new AlertDialog.Builder(MexRemoteActivity.this);

                logindialog.setTitle("Mex Webremote login");

                user = new EditText(MexRemoteActivity.this);
                pass = new EditText(MexRemoteActivity.this);

                layout = new LinearLayout(MexRemoteActivity.this);

                pass.setTransformationMethod(new PasswordTransformationMethod());

                layout.setOrientation(LinearLayout.VERTICAL);

                params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);

                layout.setLayoutParams(params);
                user.setLayoutParams(params);
                pass.setLayoutParams(params);

                label_username = new TextView(MexRemoteActivity.this);
                label_password = new TextView(MexRemoteActivity.this);

                label_username.setText("Username:");
                label_password.setText("Password:");

                layout.addView(label_username);
                layout.addView(user);
                layout.addView(label_password);
                layout.addView(pass);
                logindialog.setView(layout);

                logindialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        dialog.cancel();
                    }
                });

                logindialog.setPositiveButton("Login", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        String uvalue = user.getText().toString().trim();
                        String pvalue = pass.getText().toString().trim();
                        view.setHttpAuthUsernamePassword(host, realm, uvalue, pvalue);

                        handler.proceed(uvalue, pvalue);
                    }
                });
                logindialog.show();
                /* End login dialog box */
            } else /* We didn't get a 401 */
            {
                handler.proceed(userpass[0], userpass[1]);
            }
        } /* End onReceivedHttpAuthRequest */
    }); /* End Override */

    /* Run mdns to check for service in a "runnable" (async) */
    handler.post(new Runnable() {
        public void run() {
            startMdns();
        }
    });

    dialog = ProgressDialog.show(MexRemoteActivity.this, "", "Searching...", true);

    /* Let's put something in the webview while we're waiting */
    String summary = "<html><head><style>body { background-color: #000000; color: #ffffff; }></style></head><body><p>Searching for the media explorer webservice</p><p>More infomation on <a href=\"http://media-explorer.github.com\" >Media Explorer's home page</a></p></body></html>";
    web_view.loadData(summary, "text/html", "utf-8");

}

From source file:it.ielettronica.TVS.MyListAdapterExt.java

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    //If there's no recycled view, inflate one and tag each of the views
    //you'll want to modify later
    //Log.d("Inside", "GetView");

    plv = null;/*from ww  w  .  j  a  v a2s  .co  m*/
    if (convertView == null) {

        convertView = mInflater.inflate(R.layout.row_site_remote, parent, false);
        plv = new PlaylistValues();

        plv.nameTxt = (TextView) convertView.findViewById(R.id.nameTxt);
        plv.aboutTxt = (TextView) convertView.findViewById(R.id.aboutTxt);
        plv.iconImg = (ImageView) convertView.findViewById(R.id.iconImg);
        plv.btnPlayLocal = (Button) convertView.findViewById(R.id.btnPlayLocal);
        plv.indicator = (ProgressBar) convertView.findViewById(R.id.progress);
        plv.btnAddLocal = (Button) convertView.findViewById(R.id.btnAddLocal);
        plv.imageState = (ImageView) convertView.findViewById(R.id.imgState);
        plv.btnEditDel = (Button) convertView.findViewById(R.id.btnEditDel);
        //This assumes layout/row_left.xml includes a TextView with an id of "textview"
        convertView.setTag(plv);
    } else {
        plv = (PlaylistValues) convertView.getTag();
    }

    //Initially we want the progress indicator visible, and the image invisible
    plv.indicator.setVisibility(View.VISIBLE);
    plv.iconImg.setVisibility(View.INVISIBLE);

    if (MainActivity.isAmministrator()) {
        plv.btnEditDel.setVisibility(View.VISIBLE);
    } else {
        plv.btnEditDel.setVisibility(View.INVISIBLE);
    }

    //Retrieve the tagged view, get the item for that position, and
    //update the text

    ImageLoadingListener listener = new ImageLoadingListener() {

        @Override
        public void onLoadingStarted(String arg0, View arg1) {
            // TODO Auto-generated method stub
            plv.indicator.setVisibility(View.INVISIBLE);
            plv.iconImg.setVisibility(View.VISIBLE);

        }

        @Override
        public void onLoadingCancelled(String arg0, View arg1) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onLoadingComplete(String arg0, View arg1, Bitmap arg2) {
            //plv.indicator.setVisibility(View.INVISIBLE);
            //plv.iconImg.setVisibility(View.VISIBLE);
        }

        @Override
        public void onLoadingFailed(String arg0, View arg1, FailReason arg2) {
            // TODO Auto-generated method stub

        }

    };

    stk = mItems.get(position);
    plv.nameTxt.setText(stk.getName());
    plv.aboutTxt.setText(stk.getAbout());

    String uri = "@drawable/myresource"; // where myresource.png is the file
    // extension removed from the String

    if (MainActivity.isAmministrator() == Boolean.TRUE) {
        Drawable res;
        if (stk.getAccepted() == 1) {
            res = ContextCompat.getDrawable(MainActivity.getAppContext(), R.drawable.good);
        } else {
            res = ContextCompat.getDrawable(MainActivity.getAppContext(), R.drawable.warning);
        }
        plv.imageState.setImageDrawable(res);
    }

    imageLoader.displayImage(stk.getImgUrl(), plv.iconImg, options, listener);

    plv.btnEditDel.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            final StackSite stkloc = mItems.get(position);
            MainActivity.posRemoteListBeforeExecuted = sitesMusic.getFirstVisiblePosition();
            Intent intent = new Intent(MainActivity.getAppContext(), ModChannel.class);

            intent.putExtra("TitleChannel", stkloc.getName());
            intent.putExtra("DescrChannel", stkloc.getAbout());
            intent.putExtra("IconChannel", stkloc.getImgUrl());
            intent.putExtra("isAccepted", stkloc.getAccepted());
            intent.putExtra("NameGroup", GroupVSeletced.getGroupName());
            intent.putExtra("LevelGroup", GroupVSeletced.getGroupLevel());
            intent.putExtra("TypeGroup", GroupVSeletced.getGroupType());

            intent.putExtra("GroupLevel", GroupVSeletced.getGroupLevel());
            tabFromDB.fa.startActivity(intent);

        }
    });

    plv.btnPlayLocal.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            //                final Intent intent = new Intent(v.getContext(), MediaPlayerDemo_Video.class);
            final StackSite stkloc = mItems.get(position);
            MainActivity.posRemoteListBeforeExecuted = sitesMusic.getFirstVisiblePosition();

            GroupType = GroupVSeletced.getGroupType();

            RemoteCommunications rm = new RemoteCommunications();
            List<StackLink> Links = new ArrayList<StackLink>();
            rm.getLinks(Links, stkloc.getName(), new GetLinkCallback() {
                @Override
                public void done(List<StackLink> returnedLinks) {
                    List<StackLink> Links = returnedLinks;
                    if (Links.size() == 1) {
                        MainActivity.posLocalListBeforeExecuted = tabFromDB.sitesMusic
                                .getFirstVisiblePosition();
                        if (MainActivity.isAmministrator()) {

                            Intent intent = new Intent(MainActivity.getAppContext(), LinksLists.class);
                            intent.putExtra("VideoStreamName", stkloc.getName());
                            intent.putExtra("GroupType", GroupType);

                            tabFromDB.fa.startActivity(intent);

                        } else {
                            String linkVal = Links.get(0).getLinkValue();
                            //Uri myUri = Uri.parse(linkVal);

                            if (GroupType == 0) {

                                Intent mpdIntent = new Intent(tabLocal.Fa.getContext(), PlayerActivity.class)
                                        .setData(Uri.parse(linkVal))
                                        .putExtra(PlayerActivity.CONTENT_ID_EXTRA, "")
                                        .putExtra(PlayerActivity.CONTENT_TYPE_EXTRA, PlayerActivity.TYPE_HLS)
                                        .putExtra(PlayerActivity.PROVIDER_EXTRA, "");
                                tabFromDB.fa.getContext().startActivity(mpdIntent);

                            } else if (GroupType == 1) {

                                //                                    Intent intent2 = new Intent(tabLocal.Fa.getContext(), MediaPlayerDemo_VideoView.class);
                                //                                    intent2.putExtra("pathValue", linkVal);
                                //                                    tabFromDB.fa.getContext().startActivity(intent2);

                            } else {

                                //                                    intent.putExtra("media", 5);
                                //                                    intent.putExtra("pathValue", linkVal);
                                //
                                //                                    try {
                                //                                        tabFromDB.fa.startActivity(intent);
                                //                                    } catch (Exception ex) {
                                //                                        Toast.makeText(cloc, ex.toString(),
                                //                                                Toast.LENGTH_SHORT).show();
                                //                                    }

                            }

                            Toast.makeText(cloc, "Play: " + stkloc.getName(), Toast.LENGTH_SHORT).show();

                        }

                    } else if (Links.size() == 0) {
                        Toast.makeText(cloc,
                                "the channel:  '" + stkloc.getName() + "' doesn't have any link associated",
                                Toast.LENGTH_SHORT).show();
                    } else {

                        Intent intent = new Intent(MainActivity.getAppContext(), LinksLists.class);
                        intent.putExtra("VideoStreamName", stkloc.getName());
                        tabFromDB.fa.startActivity(intent);

                    }
                }
            });

        }
    });

    plv.btnAddLocal.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            stkloc = mItems.get(position);

            RemoteCommunications rm = new RemoteCommunications();
            List<StackLink> Links = new ArrayList<StackLink>();
            rm.getLinks(Links, stkloc.getName(), new GetLinkCallback() {
                @Override
                public void done(List<StackLink> returnedLinks) {

                    AlertDialog.Builder alertDialog;
                    try {
                        alertDialog = new AlertDialog.Builder(tabFromDB.fa.getContext());
                    } catch (Exception ex) {
                        alertDialog = new AlertDialog.Builder(MainActivity.getAppContext());
                    }

                    retLinks = returnedLinks;
                    LinearLayout layout = new LinearLayout(MainActivity.getAppContext());
                    layout.setOrientation(LinearLayout.VERTICAL);

                    if (returnedLinks.size() > 1) {

                        LinearLayout rlayoutLink = new LinearLayout(MainActivity.getAppContext());
                        rlayoutLink.setOrientation(LinearLayout.HORIZONTAL);
                        final TextView textView = new TextView(MainActivity.getAppContext());
                        textView.setText("Links:  ");
                        textView.setGravity(Gravity.RIGHT);
                        textView.setLayoutParams(
                                new FrameLayout.LayoutParams(400, LinearLayout.LayoutParams.WRAP_CONTENT));
                        rlayoutLink.addView(textView);
                        listLinks = new Spinner(MainActivity.getAppContext());

                        List<String> retLinksString = new ArrayList<String>();
                        for (int i = 0; i < returnedLinks.size(); i++) {
                            retLinksString.add(returnedLinks.get(i).getLinkTxt());
                        }

                        listLinks.setAdapter(new MyCustomAdapter(MainActivity.getAppContext(),
                                R.layout.rowspinnertake, retLinksString, returnedLinks));

                        //ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.getAppContext(), android.R.layout.simple_spinner_item, retLinksString);
                        //adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        //listLinks.setAdapter(adapter);

                        listLinks.setLayoutParams(
                                new FrameLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                                        LinearLayout.LayoutParams.WRAP_CONTENT));

                        rlayoutLink.addView(listLinks);
                        layout.addView(rlayoutLink);
                    }

                    final Button btnAddToTheEnd = new Button(MainActivity.getAppContext());
                    btnAddToTheEnd.setText("Add");

                    btnAddToTheEnd.setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {

                            StackSite stkloc = mItems.get(position);

                            if (listLinks != null) {
                                posSpinnerLink = listLinks.getSelectedItemPosition();
                            } else {
                                posSpinnerLink = 0;
                            }

                            if (retLinks.size() == 0) {
                                Toast.makeText(cloc,
                                        "the channel:  '" + stkloc.getName()
                                                + "' doesn't have any link associated",
                                        Toast.LENGTH_SHORT).show();
                            } else {

                                String url;

                                if (retLinks.size() == 1) {

                                    url = retLinks.get(0).getLinkValue();

                                } else {
                                    url = retLinks.get(posSpinnerLink).getLinkValue();
                                }

                                stkloc.setLink(url);
                                stkloc.setTypeStream(GroupVSeletced.getGroupType());
                                stkloc.setStaticName(stkloc.getName());
                                String nameStation = stkloc.getName();
                                stkloc.setOrigin(0);
                                boolean isAdded = dbHandler.addSite(stkloc);
                                if (isAdded) {
                                    Toast.makeText(MainActivity.getAppContext(),
                                            nameStation + " is added in Local Playlist", Toast.LENGTH_SHORT)
                                            .show();
                                }
                                List<StackSite> itemsLocal;
                                itemsLocal = dbHandler.getStackSites();
                                if (itemsLocal.size() == 0) {
                                    tabLocal.editEmptyLocalList.setVisibility(View.VISIBLE);
                                } else {
                                    tabLocal.editEmptyLocalList.setVisibility(View.INVISIBLE);
                                }

                                tabLocal.sitesLocal.setCheeseList(itemsLocal);
                                tabLocal.sitesLocal.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
                                StableArrayAdapter adapterLocal = new StableArrayAdapter(
                                        tabLocal.Fa.getContext(), R.layout.row_site_local, itemsLocal);
                                tabLocal.sitesLocal.setAdapter(adapterLocal);

                                OptionDialog.dismiss();

                            }

                        }
                    });
                    btnAddToTheEnd.setLayoutParams(
                            new FrameLayout.LayoutParams(400, LinearLayout.LayoutParams.WRAP_CONTENT));
                    layout.addView(btnAddToTheEnd);

                    final Button btnAddAfter = new Button(MainActivity.getAppContext());
                    final Spinner listChannelAlreadyAdded = new Spinner(MainActivity.getAppContext());
                    List<String> ListNameChannel;
                    ListNameChannel = dbHandler.getNamesFromStackSites();
                    ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(MainActivity.getAppContext(),
                            android.R.layout.simple_spinner_item, ListNameChannel);
                    adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    listChannelAlreadyAdded.setAdapter(adapter2);
                    posSpinner = listChannelAlreadyAdded.getSelectedItemPosition();

                    if (posSpinner != -1) {
                        LinearLayout rlayout = new LinearLayout(MainActivity.getAppContext());
                        rlayout.setOrientation(LinearLayout.HORIZONTAL);

                        btnAddAfter.setText("Add Before");
                        btnAddAfter.setOnClickListener(new View.OnClickListener() {
                            public void onClick(View v) {

                                if (listLinks != null) {
                                    posSpinnerLink = listLinks.getSelectedItemPosition();
                                } else {
                                    posSpinnerLink = 0;
                                }

                                StackSite stkloc = mItems.get(position);

                                if (retLinks.size() == 0) {
                                    Toast.makeText(cloc,
                                            "the channel:  '" + stkloc.getName()
                                                    + "' doesn't have any link associated",
                                            Toast.LENGTH_SHORT).show();
                                } else {

                                    String url;

                                    if (retLinks.size() == 1) {

                                        url = retLinks.get(0).getLinkValue();

                                    } else {
                                        url = retLinks.get(posSpinnerLink).getLinkValue();
                                    }

                                    stkloc.setLink(url);
                                    stkloc.setOrigin(0);
                                    stkloc.setTypeStream(GroupVSeletced.getGroupType());
                                    String nameStation = stkloc.getName();
                                    posSpinner = listChannelAlreadyAdded.getSelectedItemPosition();

                                    boolean isAdded = dbHandler.addSiteBefore(stkloc, posSpinner);
                                    if (isAdded) {
                                        Toast.makeText(MainActivity.getAppContext(),
                                                nameStation + " is added in Local Playlist", Toast.LENGTH_SHORT)
                                                .show();
                                    }
                                    List<StackSite> itemsLocal;
                                    itemsLocal = dbHandler.getStackSites();
                                    tabLocal.sitesLocal.setCheeseList(itemsLocal);
                                    tabLocal.sitesLocal.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
                                    StableArrayAdapter adapterLocal = new StableArrayAdapter(
                                            tabLocal.Fa.getContext(), R.layout.row_site_local, itemsLocal);
                                    tabLocal.sitesLocal.setAdapter(adapterLocal);

                                    OptionDialog.dismiss();

                                }

                            }
                        });

                        btnAddAfter.setLayoutParams(
                                new FrameLayout.LayoutParams(400, LinearLayout.LayoutParams.WRAP_CONTENT));
                        rlayout.addView(btnAddAfter);
                        listChannelAlreadyAdded.setLayoutParams(
                                new FrameLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                                        LinearLayout.LayoutParams.WRAP_CONTENT));
                        rlayout.addView(listChannelAlreadyAdded);
                        layout.addView(rlayout);
                    }

                    final Button btnCancel = new Button(MainActivity.getAppContext());
                    btnCancel.setText("Cancel");
                    btnCancel.setLayoutParams(
                            new FrameLayout.LayoutParams(400, LinearLayout.LayoutParams.WRAP_CONTENT));

                    btnCancel.setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                            OptionDialog.dismiss();
                        }
                    });

                    layout.addView(btnCancel);
                    alertDialog.setView(layout); // uncomment this line
                    alertDialog.setTitle("Take the Channel");
                    OptionDialog = alertDialog.create();
                    OptionDialog.show();
                }

            });

        }

    });

    return convertView;
}

From source file:org.openremote.android.console.AppSettingsActivity.java

/**
 * It contains a list view to display custom servers, 
 * "Add" button to add custom server, "Delete" button to delete custom server.
 * The custom servers would be saved in customServers.xml. If click a list item, it would be saved as current server.
 * /*w  w w .j av a  2  s  .  c o  m*/
 * @return the linear layout
 */
private LinearLayout constructCustomServersView() {
    LinearLayout custumeView = new LinearLayout(this);
    custumeView.setOrientation(LinearLayout.VERTICAL);
    custumeView.setPadding(20, 5, 5, 0);
    custumeView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));

    ArrayList<String> customServers = new ArrayList<String>();
    initCustomServersFromFile(customServers);

    RelativeLayout buttonsView = new RelativeLayout(this);
    buttonsView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 80));
    Button addServer = new Button(this);
    addServer.setWidth(80);
    RelativeLayout.LayoutParams addServerLayout = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT);
    addServerLayout.addRule(RelativeLayout.CENTER_HORIZONTAL);
    addServer.setLayoutParams(addServerLayout);
    addServer.setText("Add");
    addServer.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            Intent intent = new Intent();
            intent.setClass(AppSettingsActivity.this, AddServerActivity.class);
            startActivityForResult(intent, Constants.REQUEST_CODE);
        }

    });
    Button deleteServer = new Button(this);
    deleteServer.setWidth(80);
    RelativeLayout.LayoutParams deleteServerLayout = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT);
    deleteServerLayout.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
    deleteServer.setLayoutParams(deleteServerLayout);
    deleteServer.setText("Delete");
    deleteServer.setOnClickListener(new OnClickListener() {
        @SuppressWarnings("unchecked")
        public void onClick(View v) {
            int checkedPosition = customListView.getCheckedItemPosition();
            if (!(checkedPosition == ListView.INVALID_POSITION)) {
                customListView.setItemChecked(checkedPosition, false);
                ((ArrayAdapter<String>) customListView.getAdapter())
                        .remove(customListView.getItemAtPosition(checkedPosition).toString());
                currentServer = "";
                AppSettingsModel.setCurrentServer(AppSettingsActivity.this, currentServer);
                writeCustomServerToFile();
            }
        }
    });

    buttonsView.addView(addServer);
    buttonsView.addView(deleteServer);

    customListView = new ListView(this);
    customListView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 200));
    customListView.setCacheColorHint(0);
    final ArrayAdapter<String> serverListAdapter = new ArrayAdapter<String>(appSettingsView.getContext(),
            R.layout.server_list_item, customServers);
    customListView.setAdapter(serverListAdapter);
    customListView.setItemsCanFocus(true);
    customListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    if (currentCustomServerIndex != -1) {
        customListView.setItemChecked(currentCustomServerIndex, true);
        currentServer = (String) customListView.getItemAtPosition(currentCustomServerIndex);
    }
    customListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            currentServer = (String) parent.getItemAtPosition(position);
            AppSettingsModel.setCurrentServer(AppSettingsActivity.this, currentServer);
            writeCustomServerToFile();
            requestPanelList();
            checkAuthentication();
            requestAccess();
        }

    });

    custumeView.addView(customListView);
    custumeView.addView(buttonsView);
    requestPanelList();
    checkAuthentication();
    requestAccess();
    return custumeView;
}

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

@Override
public View createView(Context context) {
    actionBar.setBackButtonImage(R.drawable.ic_ab_back);
    actionBar.setAllowOverlayTitle(true);
    actionBar.setTitle(LocaleController.getString("CacheSettings", R.string.CacheSettings));
    actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
        @Override//w w w. j  av a  2 s  . c  o  m
        public void onItemClick(int id) {
            if (id == -1) {
                finishFragment();
            }
        }
    });

    listAdapter = new ListAdapter(context);

    fragmentView = new FrameLayout(context);
    FrameLayout frameLayout = (FrameLayout) fragmentView;
    frameLayout.setBackgroundColor(ContextCompat.getColor(context, R.color.settings_background));

    ListView listView = new ListView(context);
    listView.setDivider(null);
    listView.setDividerHeight(0);
    listView.setVerticalScrollBarEnabled(false);
    listView.setDrawSelectorOnTop(true);
    frameLayout.addView(listView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    listView.setAdapter(listAdapter);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(final AdapterView<?> adapterView, View view, final int i, long l) {
            if (getParentActivity() == null) {
                return;
            }
            if (i == keepMediaRow) {
                BottomSheet.Builder builder = new BottomSheet.Builder(getParentActivity());
                builder.setItems(
                        new CharSequence[] { LocaleController.formatPluralString("Weeks", 1),
                                LocaleController.formatPluralString("Months", 1),
                                LocaleController.getString("KeepMediaForever", R.string.KeepMediaForever) },
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, final int which) {
                                SharedPreferences.Editor editor = ApplicationLoader.applicationContext
                                        .getSharedPreferences("mainconfig", Activity.MODE_PRIVATE).edit();
                                editor.putInt("keep_media", which).commit();
                                if (listAdapter != null) {
                                    listAdapter.notifyDataSetChanged();
                                }
                                PendingIntent pintent = PendingIntent.getService(
                                        ApplicationLoader.applicationContext, 0,
                                        new Intent(ApplicationLoader.applicationContext,
                                                ClearCacheService.class),
                                        0);
                                AlarmManager alarmManager = (AlarmManager) ApplicationLoader.applicationContext
                                        .getSystemService(Context.ALARM_SERVICE);
                                if (which == 2) {
                                    alarmManager.cancel(pintent);
                                } else {
                                    alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                                            AlarmManager.INTERVAL_DAY, AlarmManager.INTERVAL_DAY, pintent);
                                }
                            }
                        });
                showDialog(builder.create());
            } else if (i == databaseRow) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                builder.setMessage(
                        LocaleController.getString("LocalDatabaseClear", R.string.LocalDatabaseClear));
                builder.setPositiveButton(LocaleController.getString("CacheClear", R.string.CacheClear),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                final ProgressDialog progressDialog = new ProgressDialog(getParentActivity());
                                progressDialog
                                        .setMessage(LocaleController.getString("Loading", R.string.Loading));
                                progressDialog.setCanceledOnTouchOutside(false);
                                progressDialog.setCancelable(false);
                                progressDialog.show();
                                MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            SQLiteDatabase database = MessagesStorage.getInstance()
                                                    .getDatabase();
                                            ArrayList<Long> dialogsToCleanup = new ArrayList<>();
                                            SQLiteCursor cursor = database
                                                    .queryFinalized("SELECT did FROM dialogs WHERE 1");
                                            StringBuilder ids = new StringBuilder();
                                            while (cursor.next()) {
                                                long did = cursor.longValue(0);
                                                int lower_id = (int) did;
                                                int high_id = (int) (did >> 32);
                                                if (lower_id != 0 && high_id != 1) {
                                                    dialogsToCleanup.add(did);
                                                }
                                            }
                                            cursor.dispose();

                                            SQLitePreparedStatement state5 = database
                                                    .executeFast("REPLACE INTO messages_holes VALUES(?, ?, ?)");
                                            SQLitePreparedStatement state6 = database.executeFast(
                                                    "REPLACE INTO media_holes_v2 VALUES(?, ?, ?, ?)");

                                            database.beginTransaction();
                                            for (int a = 0; a < dialogsToCleanup.size(); a++) {
                                                Long did = dialogsToCleanup.get(a);
                                                int messagesCount = 0;
                                                cursor = database.queryFinalized(
                                                        "SELECT COUNT(mid) FROM messages WHERE uid = " + did);
                                                if (cursor.next()) {
                                                    messagesCount = cursor.intValue(0);
                                                }
                                                cursor.dispose();
                                                if (messagesCount <= 2) {
                                                    continue;
                                                }

                                                cursor = database.queryFinalized(
                                                        "SELECT last_mid_i, last_mid FROM dialogs WHERE did = "
                                                                + did);
                                                int messageId = -1;
                                                if (cursor.next()) {
                                                    long last_mid_i = cursor.longValue(0);
                                                    long last_mid = cursor.longValue(1);
                                                    SQLiteCursor cursor2 = database.queryFinalized(
                                                            "SELECT data FROM messages WHERE uid = " + did
                                                                    + " AND mid IN (" + last_mid_i + ","
                                                                    + last_mid + ")");
                                                    try {
                                                        while (cursor2.next()) {
                                                            NativeByteBuffer data = cursor2.byteBufferValue(0);
                                                            if (data != null) {
                                                                TLRPC.Message message = TLRPC.Message
                                                                        .TLdeserialize(data,
                                                                                data.readInt32(false), false);
                                                                data.reuse();
                                                                if (message != null) {
                                                                    messageId = message.id;
                                                                }
                                                            }
                                                        }
                                                    } catch (Exception e) {
                                                        FileLog.e("tmessages", e);
                                                    }
                                                    cursor2.dispose();

                                                    database.executeFast("DELETE FROM messages WHERE uid = "
                                                            + did + " AND mid != " + last_mid_i + " AND mid != "
                                                            + last_mid).stepThis().dispose();
                                                    database.executeFast(
                                                            "DELETE FROM messages_holes WHERE uid = " + did)
                                                            .stepThis().dispose();
                                                    database.executeFast(
                                                            "DELETE FROM bot_keyboard WHERE uid = " + did)
                                                            .stepThis().dispose();
                                                    database.executeFast(
                                                            "DELETE FROM media_counts_v2 WHERE uid = " + did)
                                                            .stepThis().dispose();
                                                    database.executeFast(
                                                            "DELETE FROM media_v2 WHERE uid = " + did)
                                                            .stepThis().dispose();
                                                    database.executeFast(
                                                            "DELETE FROM media_holes_v2 WHERE uid = " + did)
                                                            .stepThis().dispose();
                                                    BotQuery.clearBotKeyboard(did, null);
                                                    if (messageId != -1) {
                                                        MessagesStorage.createFirstHoles(did, state5, state6,
                                                                messageId);
                                                    }
                                                }
                                                cursor.dispose();
                                            }
                                            state5.dispose();
                                            state6.dispose();
                                            database.commitTransaction();
                                            database.executeFast("VACUUM").stepThis().dispose();
                                        } catch (Exception e) {
                                            FileLog.e("tmessages", e);
                                        } finally {
                                            AndroidUtilities.runOnUIThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    try {
                                                        progressDialog.dismiss();
                                                    } catch (Exception e) {
                                                        FileLog.e("tmessages", e);
                                                    }
                                                    if (listAdapter != null) {
                                                        File file = new File(
                                                                ApplicationLoader.getFilesDirFixed(),
                                                                "cache4.db");
                                                        databaseSize = file.length();
                                                        listAdapter.notifyDataSetChanged();
                                                    }
                                                }
                                            });
                                        }
                                    }
                                });
                            }
                        });
                showDialog(builder.create());
            } else if (i == cacheRow) {
                if (totalSize <= 0 || getParentActivity() == null) {
                    return;
                }
                BottomSheet.Builder builder = new BottomSheet.Builder(getParentActivity());
                builder.setApplyTopPadding(false);
                builder.setApplyBottomPadding(false);
                LinearLayout linearLayout = new LinearLayout(getParentActivity());
                linearLayout.setOrientation(LinearLayout.VERTICAL);
                for (int a = 0; a < 6; a++) {
                    long size = 0;
                    String name = null;
                    if (a == 0) {
                        size = photoSize;
                        name = LocaleController.getString("LocalPhotoCache", R.string.LocalPhotoCache);
                    } else if (a == 1) {
                        size = videoSize;
                        name = LocaleController.getString("LocalVideoCache", R.string.LocalVideoCache);
                    } else if (a == 2) {
                        size = documentsSize;
                        name = LocaleController.getString("LocalDocumentCache", R.string.LocalDocumentCache);
                    } else if (a == 3) {
                        size = musicSize;
                        name = LocaleController.getString("LocalMusicCache", R.string.LocalMusicCache);
                    } else if (a == 4) {
                        size = audioSize;
                        name = LocaleController.getString("LocalAudioCache", R.string.LocalAudioCache);
                    } else if (a == 5) {
                        size = cacheSize;
                        name = LocaleController.getString("LocalCache", R.string.LocalCache);
                    }
                    if (size > 0) {
                        clear[a] = true;
                        CheckBoxCell checkBoxCell = new CheckBoxCell(getParentActivity());
                        checkBoxCell.setTag(a);
                        checkBoxCell.setBackgroundResource(R.drawable.list_selector);
                        linearLayout.addView(checkBoxCell,
                                LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 48));
                        checkBoxCell.setText(name, AndroidUtilities.formatFileSize(size), true, true);
                        checkBoxCell.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                CheckBoxCell cell = (CheckBoxCell) v;
                                int num = (Integer) cell.getTag();
                                clear[num] = !clear[num];
                                cell.setChecked(clear[num], true);
                            }
                        });
                    } else {
                        clear[a] = false;
                    }
                }
                BottomSheet.BottomSheetCell cell = new BottomSheet.BottomSheetCell(getParentActivity(), 1);
                cell.setBackgroundResource(R.drawable.list_selector);
                cell.setTextAndIcon(
                        LocaleController.getString("ClearMediaCache", R.string.ClearMediaCache).toUpperCase(),
                        0);
                cell.setTextColor(Theme.STICKERS_SHEET_REMOVE_TEXT_COLOR);
                cell.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        try {
                            if (visibleDialog != null) {
                                visibleDialog.dismiss();
                            }
                        } catch (Exception e) {
                            FileLog.e("tmessages", e);
                        }
                        cleanupFolders();
                    }
                });
                linearLayout.addView(cell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 48));
                builder.setCustomView(linearLayout);
                showDialog(builder.create());
            }
        }
    });

    return fragmentView;
}

From source file:jp.ne.sakura.kkkon.java.net.inetaddress.testapp.android.NetworkConnectionCheckerTestApp.java

/** Called when the activity is first created. */
@Override/* www .j  av  a2s.  c om*/
public void onCreate(Bundle savedInstanceState) {
    final Context context = this.getApplicationContext();

    {
        NetworkConnectionChecker.initialize();
    }

    super.onCreate(savedInstanceState);

    /* Create a TextView and set its content.
     * the text is retrieved by calling a native
     * function.
     */
    LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(LinearLayout.VERTICAL);

    TextView tv = new TextView(this);
    tv.setText("reachable=");
    layout.addView(tv);
    this.textView = tv;

    Button btn1 = new Button(this);
    btn1.setText("invoke Exception");
    btn1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            final int count = 2;
            int[] array = new int[count];
            int value = array[count]; // invoke IndexOutOfBOundsException
        }
    });
    layout.addView(btn1);

    {
        Button btn = new Button(this);
        btn.setText("disp isReachable");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                final boolean isReachable = NetworkConnectionChecker.isReachable();
                Toast toast = Toast.makeText(context, "IsReachable=" + isReachable, Toast.LENGTH_LONG);
                toast.show();
            }
        });
        layout.addView(btn);
    }

    {
        Button btn = new Button(this);
        btn.setText("upload http AsyncTask");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                AsyncTask<String, Void, Boolean> asyncTask = new AsyncTask<String, Void, Boolean>() {

                    @Override
                    protected Boolean doInBackground(String... paramss) {
                        Boolean result = true;
                        Log.d(TAG, "upload AsyncTask tid=" + android.os.Process.myTid());
                        try {
                            //$(BRAND)/$(PRODUCT)/$(DEVICE)/$(BOARD):$(VERSION.RELEASE)/$(ID)/$(VERSION.INCREMENTAL):$(TYPE)/$(TAGS)
                            Log.d(TAG, "fng=" + Build.FINGERPRINT);
                            final List<NameValuePair> list = new ArrayList<NameValuePair>(16);
                            list.add(new BasicNameValuePair("fng", Build.FINGERPRINT));

                            HttpPost httpPost = new HttpPost(paramss[0]);
                            //httpPost.getParams().setParameter( CoreConnectionPNames.SO_TIMEOUT, new Integer(5*1000) );
                            httpPost.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));
                            DefaultHttpClient httpClient = new DefaultHttpClient();
                            Log.d(TAG, "socket.timeout=" + httpClient.getParams()
                                    .getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1));
                            Log.d(TAG, "connection.timeout=" + httpClient.getParams()
                                    .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1));
                            httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
                                    new Integer(5 * 1000));
                            httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
                                    new Integer(5 * 1000));
                            Log.d(TAG, "socket.timeout=" + httpClient.getParams()
                                    .getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1));
                            Log.d(TAG, "connection.timeout=" + httpClient.getParams()
                                    .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1));
                            // <uses-permission android:name="android.permission.INTERNET"/>
                            // got android.os.NetworkOnMainThreadException, run at UI Main Thread
                            HttpResponse response = httpClient.execute(httpPost);
                            Log.d(TAG, "response=" + response.getStatusLine().getStatusCode());
                        } catch (Exception e) {
                            Log.d(TAG, "got Exception. msg=" + e.getMessage(), e);
                            result = false;
                        }
                        Log.d(TAG, "upload finish");
                        return result;
                    }

                };

                asyncTask.execute("http://kkkon.sakura.ne.jp/android/bug");
                asyncTask.isCancelled();
            }
        });
        layout.addView(btn);
    }

    {
        Button btn = new Button(this);
        btn.setText("pre DNS query(0.0.0.0)");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                isReachable = false;
                Thread thread = new Thread(new Runnable() {

                    public void run() {
                        try {
                            destHost = InetAddress.getByName("0.0.0.0");
                            if (null != destHost) {
                                try {
                                    if (destHost.isReachable(5 * 1000)) {
                                        Log.d(TAG, "destHost=" + destHost.toString() + " reachable");
                                    } else {
                                        Log.d(TAG, "destHost=" + destHost.toString() + " not reachable");
                                    }
                                } catch (IOException e) {

                                }
                            }
                        } catch (UnknownHostException e) {

                        }
                        Log.d(TAG, "destHost=" + destHost);
                    }
                });
                thread.start();
                try {
                    thread.join(1000);
                } catch (InterruptedException e) {

                }
            }
        });
        layout.addView(btn);
    }
    {
        Button btn = new Button(this);
        btn.setText("pre DNS query(www.google.com)");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                isReachable = false;
                Thread thread = new Thread(new Runnable() {

                    public void run() {
                        Log.d(TAG, "start");
                        try {
                            InetAddress dest = InetAddress.getByName("www.google.com");
                            if (null == dest) {
                                dest = destHost;
                            }

                            if (null != dest) {
                                final String[] uris = new String[] { "http://www.google.com/",
                                        "https://www.google.com/" };
                                for (final String destURI : uris) {
                                    URI uri = null;
                                    try {
                                        uri = new URI(destURI);
                                    } catch (URISyntaxException e) {
                                        //Log.d( TAG, e.toString() );
                                    }

                                    if (null != uri) {
                                        URL url = null;
                                        try {
                                            url = uri.toURL();
                                        } catch (MalformedURLException ex) {
                                            Log.d(TAG, "got exception:" + ex.toString(), ex);
                                        }

                                        URLConnection conn = null;
                                        if (null != url) {
                                            Log.d(TAG, "openConnection before");
                                            try {
                                                conn = url.openConnection();
                                                if (null != conn) {
                                                    conn.setConnectTimeout(3 * 1000);
                                                    conn.setReadTimeout(3 * 1000);
                                                }
                                            } catch (IOException e) {
                                                //Log.d( TAG, "got Exception" + e.toString(), e );
                                            }
                                            Log.d(TAG, "openConnection after");
                                            if (conn instanceof HttpURLConnection) {
                                                HttpURLConnection httpConn = (HttpURLConnection) conn;
                                                int responceCode = -1;
                                                try {
                                                    Log.d(TAG, "getResponceCode before");
                                                    responceCode = httpConn.getResponseCode();
                                                    Log.d(TAG, "getResponceCode after");
                                                } catch (IOException ex) {
                                                    Log.d(TAG, "got exception:" + ex.toString(), ex);
                                                }
                                                Log.d(TAG, "responceCode=" + responceCode);
                                                if (0 < responceCode) {
                                                    isReachable = true;
                                                    destHost = dest;
                                                }
                                                Log.d(TAG,
                                                        " HTTP ContentLength=" + httpConn.getContentLength());
                                                httpConn.disconnect();
                                                Log.d(TAG,
                                                        " HTTP ContentLength=" + httpConn.getContentLength());
                                            }
                                        }
                                    } // if uri

                                    if (isReachable) {
                                        //break;
                                    }
                                } // for uris
                            } else {
                            }
                        } catch (UnknownHostException e) {
                            Log.d(TAG, "dns error" + e.toString());
                            destHost = null;
                        }
                        {
                            if (null != destHost) {
                                Log.d(TAG, "destHost=" + destHost);
                            }
                        }
                        Log.d(TAG, "end");
                    }
                });
                thread.start();
                try {
                    thread.join();
                    {
                        final String addr = (null == destHost) ? ("") : (destHost.toString());
                        final String reachable = (isReachable) ? ("reachable") : ("not reachable");
                        Toast toast = Toast.makeText(context, "DNS result=\n" + addr + "\n " + reachable,
                                Toast.LENGTH_LONG);
                        toast.show();
                    }
                } catch (InterruptedException e) {

                }
            }
        });
        layout.addView(btn);
    }

    {
        Button btn = new Button(this);
        btn.setText("pre DNS query(kkkon.sakura.ne.jp)");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                isReachable = false;
                Thread thread = new Thread(new Runnable() {

                    public void run() {
                        Log.d(TAG, "start");
                        try {
                            InetAddress dest = InetAddress.getByName("kkkon.sakura.ne.jp");
                            if (null == dest) {
                                dest = destHost;
                            }
                            if (null != dest) {
                                try {
                                    if (dest.isReachable(5 * 1000)) {
                                        Log.d(TAG, "destHost=" + dest.toString() + " reachable");
                                        isReachable = true;
                                    } else {
                                        Log.d(TAG, "destHost=" + dest.toString() + " not reachable");
                                    }
                                    destHost = dest;
                                } catch (IOException e) {

                                }
                            } else {
                            }
                        } catch (UnknownHostException e) {
                            Log.d(TAG, "dns error" + e.toString());
                            destHost = null;
                        }
                        {
                            if (null != destHost) {
                                Log.d(TAG, "destHost=" + destHost);
                            }
                        }
                        Log.d(TAG, "end");
                    }
                });
                thread.start();
                try {
                    thread.join();
                    {
                        final String addr = (null == destHost) ? ("") : (destHost.toString());
                        final String reachable = (isReachable) ? ("reachable") : ("not reachable");
                        Toast toast = Toast.makeText(context, "DNS result=\n" + addr + "\n " + reachable,
                                Toast.LENGTH_LONG);
                        toast.show();
                    }
                } catch (InterruptedException e) {

                }
            }
        });
        layout.addView(btn);
    }

    {
        Button btn = new Button(this);
        btn.setText("pre DNS query(kkkon.sakura.ne.jp) support proxy");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                isReachable = false;
                Thread thread = new Thread(new Runnable() {

                    public void run() {
                        try {
                            String target = null;
                            {
                                ProxySelector proxySelector = ProxySelector.getDefault();
                                Log.d(TAG, "proxySelector=" + proxySelector);
                                if (null != proxySelector) {
                                    URI uri = null;
                                    try {
                                        uri = new URI("http://www.google.com/");
                                    } catch (URISyntaxException e) {
                                        Log.d(TAG, e.toString());
                                    }
                                    List<Proxy> proxies = proxySelector.select(uri);
                                    if (null != proxies) {
                                        for (final Proxy proxy : proxies) {
                                            Log.d(TAG, " proxy=" + proxy);
                                            if (null != proxy) {
                                                if (Proxy.Type.HTTP == proxy.type()) {
                                                    final SocketAddress sa = proxy.address();
                                                    if (sa instanceof InetSocketAddress) {
                                                        final InetSocketAddress isa = (InetSocketAddress) sa;
                                                        target = isa.getHostName();
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            if (null == target) {
                                target = "kkkon.sakura.ne.jp";
                            }
                            InetAddress dest = InetAddress.getByName(target);
                            if (null == dest) {
                                dest = destHost;
                            }
                            if (null != dest) {
                                try {
                                    if (dest.isReachable(5 * 1000)) {
                                        Log.d(TAG, "destHost=" + dest.toString() + " reachable");
                                        isReachable = true;
                                    } else {
                                        Log.d(TAG, "destHost=" + dest.toString() + " not reachable");
                                        {
                                            ProxySelector proxySelector = ProxySelector.getDefault();
                                            //Log.d( TAG, "proxySelector=" + proxySelector );
                                            if (null != proxySelector) {
                                                URI uri = null;
                                                try {
                                                    uri = new URI("http://www.google.com/");
                                                } catch (URISyntaxException e) {
                                                    //Log.d( TAG, e.toString() );
                                                }

                                                if (null != uri) {
                                                    List<Proxy> proxies = proxySelector.select(uri);
                                                    if (null != proxies) {
                                                        for (final Proxy proxy : proxies) {
                                                            //Log.d( TAG, " proxy=" + proxy );
                                                            if (null != proxy) {
                                                                if (Proxy.Type.HTTP == proxy.type()) {
                                                                    URL url = uri.toURL();
                                                                    URLConnection conn = null;
                                                                    if (null != url) {
                                                                        try {
                                                                            conn = url.openConnection(proxy);
                                                                            if (null != conn) {
                                                                                conn.setConnectTimeout(
                                                                                        3 * 1000);
                                                                                conn.setReadTimeout(3 * 1000);
                                                                            }
                                                                        } catch (IOException e) {
                                                                            Log.d(TAG, "got Exception"
                                                                                    + e.toString(), e);
                                                                        }
                                                                        if (conn instanceof HttpURLConnection) {
                                                                            HttpURLConnection httpConn = (HttpURLConnection) conn;
                                                                            if (0 < httpConn
                                                                                    .getResponseCode()) {
                                                                                isReachable = true;
                                                                            }
                                                                            Log.d(TAG, " HTTP ContentLength="
                                                                                    + httpConn
                                                                                            .getContentLength());
                                                                            Log.d(TAG, " HTTP res=" + httpConn
                                                                                    .getResponseCode());
                                                                            //httpConn.setInstanceFollowRedirects( false );
                                                                            //httpConn.setRequestMethod( "HEAD" );
                                                                            //conn.connect();
                                                                            httpConn.disconnect();
                                                                            Log.d(TAG, " HTTP ContentLength="
                                                                                    + httpConn
                                                                                            .getContentLength());
                                                                            Log.d(TAG, " HTTP res=" + httpConn
                                                                                    .getResponseCode());
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }

                                    }
                                    destHost = dest;
                                } catch (IOException e) {
                                    Log.d(TAG, "got Excpetion " + e.toString());
                                }
                            } else {
                            }
                        } catch (UnknownHostException e) {
                            Log.d(TAG, "dns error" + e.toString());
                            destHost = null;
                        }
                        {
                            if (null != destHost) {
                                Log.d(TAG, "destHost=" + destHost);
                            }
                        }
                    }
                });
                thread.start();
                try {
                    thread.join();
                    {
                        final String addr = (null == destHost) ? ("") : (destHost.toString());
                        final String reachable = (isReachable) ? ("reachable") : ("not reachable");
                        Toast toast = Toast.makeText(context, "DNS result=\n" + addr + "\n " + reachable,
                                Toast.LENGTH_LONG);
                        toast.show();
                    }
                } catch (InterruptedException e) {

                }
            }
        });
        layout.addView(btn);
    }

    setContentView(layout);
}

From source file:org.apache.cordova.core.InAppBrowser.java

/**
 * Display a new browser with the specified URL.
 *
 * @param url           The url to load.
 * @param jsonObject//www  .j  a va2  s . c  om
 */
public String showWebPage(final String url, HashMap<String, Boolean> features) {
    // Determine if we should hide the location bar.
    showLocationBar = true;
    openWindowHidden = false;
    if (features != null) {
        Boolean show = features.get(LOCATION);
        if (show != null) {
            showLocationBar = show.booleanValue();
        }
        Boolean hidden = features.get(HIDDEN);
        if (hidden != null) {
            openWindowHidden = hidden.booleanValue();
        }
    }

    final CordovaWebView thatWebView = this.webView;

    // Create dialog in new thread
    Runnable runnable = new Runnable() {
        /**
         * Convert our DIP units to Pixels
         *
         * @return int
         */
        private int dpToPixels(int dipValue) {
            int value = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) dipValue,
                    cordova.getActivity().getResources().getDisplayMetrics());

            return value;
        }

        public void run() {
            // Let's create the main dialog
            dialog = new Dialog(cordova.getActivity(), android.R.style.Theme_NoTitleBar);
            dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog;
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setCancelable(true);
            dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                public void onDismiss(DialogInterface dialog) {
                    try {
                        JSONObject obj = new JSONObject();
                        obj.put("type", EXIT_EVENT);

                        sendUpdate(obj, false);
                    } catch (JSONException e) {
                        Log.d(LOG_TAG, "Should never happen");
                    }
                }
            });

            // Main container layout
            LinearLayout main = new LinearLayout(cordova.getActivity());
            main.setOrientation(LinearLayout.VERTICAL);

            // Toolbar layout
            RelativeLayout toolbar = new RelativeLayout(cordova.getActivity());
            toolbar.setLayoutParams(
                    new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, this.dpToPixels(44)));
            toolbar.setPadding(this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2));
            toolbar.setHorizontalGravity(Gravity.LEFT);
            toolbar.setVerticalGravity(Gravity.TOP);

            // Action Button Container layout
            RelativeLayout actionButtonContainer = new RelativeLayout(cordova.getActivity());
            actionButtonContainer.setLayoutParams(
                    new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            actionButtonContainer.setHorizontalGravity(Gravity.LEFT);
            actionButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL);
            actionButtonContainer.setId(1);

            // Back button
            Button back = new Button(cordova.getActivity());
            RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT);
            back.setLayoutParams(backLayoutParams);
            back.setContentDescription("Back Button");
            back.setId(2);
            back.setText("<");
            back.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goBack();
                }
            });

            // Forward button
            Button forward = new Button(cordova.getActivity());
            RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2);
            forward.setLayoutParams(forwardLayoutParams);
            forward.setContentDescription("Forward Button");
            forward.setId(3);
            forward.setText(">");
            forward.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goForward();
                }
            });

            // Edit Text Box
            edittext = new EditText(cordova.getActivity());
            RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
            textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1);
            textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5);
            edittext.setLayoutParams(textLayoutParams);
            edittext.setId(4);
            edittext.setSingleLine(true);
            edittext.setText(url);
            edittext.setInputType(InputType.TYPE_TEXT_VARIATION_URI);
            edittext.setImeOptions(EditorInfo.IME_ACTION_GO);
            edittext.setInputType(InputType.TYPE_NULL); // Will not except input... Makes the text NON-EDITABLE
            edittext.setOnKeyListener(new View.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)) {
                        navigate(edittext.getText().toString());
                        return true;
                    }
                    return false;
                }
            });

            // Close button
            Button close = new Button(cordova.getActivity());
            RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
            close.setLayoutParams(closeLayoutParams);
            forward.setContentDescription("Close Button");
            close.setId(5);
            close.setText(buttonLabel);
            close.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    closeDialog();
                }
            });

            // WebView
            inAppWebView = new WebView(cordova.getActivity());
            inAppWebView.setLayoutParams(
                    new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
            inAppWebView.setWebChromeClient(new InAppChromeClient(thatWebView));
            WebViewClient client = new InAppBrowserClient(thatWebView, edittext);
            inAppWebView.setWebViewClient(client);
            WebSettings settings = inAppWebView.getSettings();
            settings.setJavaScriptEnabled(true);
            settings.setJavaScriptCanOpenWindowsAutomatically(true);
            settings.setBuiltInZoomControls(true);
            settings.setPluginState(android.webkit.WebSettings.PluginState.ON);

            //Toggle whether this is enabled or not!
            Bundle appSettings = cordova.getActivity().getIntent().getExtras();
            boolean enableDatabase = appSettings == null ? true
                    : appSettings.getBoolean("InAppBrowserStorageEnabled", true);
            if (enableDatabase) {
                String databasePath = cordova.getActivity().getApplicationContext()
                        .getDir("inAppBrowserDB", Context.MODE_PRIVATE).getPath();
                settings.setDatabasePath(databasePath);
                settings.setDatabaseEnabled(true);
            }
            settings.setDomStorageEnabled(true);

            inAppWebView.loadUrl(url);
            inAppWebView.setId(6);
            inAppWebView.getSettings().setLoadWithOverviewMode(true);
            inAppWebView.getSettings().setUseWideViewPort(true);
            inAppWebView.requestFocus();
            inAppWebView.requestFocusFromTouch();

            // Add the back and forward buttons to our action button container layout
            actionButtonContainer.addView(back);
            actionButtonContainer.addView(forward);

            // Add the views to our toolbar
            toolbar.addView(actionButtonContainer);
            toolbar.addView(edittext);
            toolbar.addView(close);

            // Don't add the toolbar if its been disabled
            if (getShowLocationBar()) {
                // Add our toolbar to our main view/layout
                main.addView(toolbar);
            }

            // Add our webview to our main view/layout
            main.addView(inAppWebView);

            WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
            lp.copyFrom(dialog.getWindow().getAttributes());
            lp.width = WindowManager.LayoutParams.MATCH_PARENT;
            lp.height = WindowManager.LayoutParams.MATCH_PARENT;

            dialog.setContentView(main);
            dialog.show();
            dialog.getWindow().setAttributes(lp);
            // the goal of openhidden is to load the url and not display it
            // Show() needs to be called to cause the URL to be loaded
            if (openWindowHidden) {
                dialog.hide();
            }
        }
    };
    this.cordova.getActivity().runOnUiThread(runnable);
    return "";
}

From source file:se.liu.tddd77.bilsensor.MainActivity.java

@SuppressLint("UseValueOf")
public void addNewDynamicEventString(String name) {
    //TODO: Storlek p denna ruta mste hllas konstant.
    if (name == null || name.isEmpty()) {
        Toast.makeText(this, "Dynamic Events require a name.", Toast.LENGTH_SHORT).show();
        return;/* w w w  . ja  va  2  s  .  com*/
    }
    //TODO: r this korrekt?

    LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(LinearLayout.HORIZONTAL);

    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT);//(LinearLayout.LayoutParams)layout.getLayoutParams();
    layout.setLayoutParams(params);

    Button button = new Button(this);
    buttonList.add(button);

    LinearLayout.LayoutParams buttonparams = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT, 1.0f);
    button.setLayoutParams(buttonparams);
    button.setText(name);
    button.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            try {
                Backend.getInstance().sendDynamicMessage((Long) (System.currentTimeMillis() / 1000L),
                        ((Button) v).getText().toString());
            } catch (BackendError e) {
                e.printStackTrace();
            }

        }
    });

    Button rmEventButton = new Button(this);
    LinearLayout.LayoutParams rmButtonparams = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT, 0.0f);
    rmEventButton.setLayoutParams(rmButtonparams);
    rmEventButton.setText("-");
    rmEventButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            //TODO: For-loop through trying to find the one with matching name?
            buttonList.remove(((Button) ((LinearLayout) v.getParent()).getChildAt(0)));
            ((LinearLayout) v.getParent().getParent()).removeView((LinearLayout) v.getParent());
        }
    });
    layout.addView(button);
    layout.addView(rmEventButton);
    ((LinearLayout) findViewById(R.id.dynamic_events_buttons_container)).addView(layout);
    //((LinearLayout)((LinearLayout)(view.getParent().getParent())).getChildAt(1)).addView(layout);
    //((LinearLayout) ((LinearLayout)(view.getParent().getParent()))findViewById(R.id.dynamic_events_buttons_container)).addView(button);

    //textfield.setText("");

}

From source file:com.mifos.mifosxdroid.online.generatecollectionsheet.GenerateCollectionSheetFragment.java

private void inflateCollectionTable(CollectionSheetResponse collectionSheetResponse) {
    //Clear old views in case they are present.
    if (tableProductive.getChildCount() > 0) {
        tableProductive.removeAllViews();
    }/* w ww.ja  v a  2  s . co m*/

    //A List to be used to inflate Attendance Spinners
    ArrayList<String> attendanceTypes = new ArrayList<>();
    attendanceTypeOptions.clear();
    attendanceTypeOptions = presenter.filterAttendanceTypes(collectionSheetResponse.getAttendanceTypeOptions(),
            attendanceTypes);

    additionalPaymentTypeMap.clear();
    additionalPaymentTypeMap = presenter.filterPaymentTypes(collectionSheetResponse.getPaymentTypeOptions(),
            paymentTypes);

    //Add the heading Row
    TableRow headingRow = new TableRow(getContext());
    TableRow.LayoutParams headingRowParams = new TableRow.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT);
    headingRowParams.gravity = Gravity.CENTER;
    headingRowParams.setMargins(0, 0, 0, 10);
    headingRow.setLayoutParams(headingRowParams);

    TextView tvGroupName = new TextView(getContext());
    tvGroupName.setText(collectionSheetResponse.getGroups().get(0).getGroupName());
    tvGroupName.setTypeface(tvGroupName.getTypeface(), Typeface.BOLD);
    tvGroupName.setGravity(Gravity.CENTER);
    headingRow.addView(tvGroupName);

    for (LoanProducts loanProduct : collectionSheetResponse.getLoanProducts()) {
        TextView tvProduct = new TextView(getContext());
        tvProduct.setText(getString(R.string.collection_loan_product, loanProduct.getName()));
        tvProduct.setTypeface(tvProduct.getTypeface(), Typeface.BOLD);
        tvProduct.setGravity(Gravity.CENTER);
        headingRow.addView(tvProduct);
    }

    for (SavingsProduct savingsProduct : collectionSheetResponse.getSavingsProducts()) {
        TextView tvSavingProduct = new TextView(getContext());
        tvSavingProduct.setText(getString(R.string.collection_saving_product, savingsProduct.getName()));
        tvSavingProduct.setTypeface(tvSavingProduct.getTypeface(), Typeface.BOLD);
        tvSavingProduct.setGravity(Gravity.CENTER);
        headingRow.addView(tvSavingProduct);
    }

    TextView tvAttendance = new TextView(getContext());
    tvAttendance.setText(getString(R.string.attendance));
    tvAttendance.setGravity(Gravity.CENTER);
    tvAttendance.setTypeface(tvAttendance.getTypeface(), Typeface.BOLD);
    headingRow.addView(tvAttendance);

    tableProductive.addView(headingRow);

    for (ClientCollectionSheet clientCollectionSheet : collectionSheetResponse.getGroups().get(0)
            .getClients()) {
        //Insert rows
        TableRow row = new TableRow(getContext());
        TableRow.LayoutParams rowParams = new TableRow.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        rowParams.gravity = Gravity.CENTER;
        rowParams.setMargins(0, 0, 0, 10);
        row.setLayoutParams(rowParams);

        //Column 1: Client Name and Id
        TextView tvClientName = new TextView(getContext());
        tvClientName.setText(
                concatIdWithName(clientCollectionSheet.getClientName(), clientCollectionSheet.getClientId()));
        row.addView(tvClientName);

        //Subsequent columns: The Loan products
        for (LoanProducts loanProduct : collectionSheetResponse.getLoanProducts()) {
            //Since there may be several items in this column, create a container.
            LinearLayout productContainer = new LinearLayout(getContext());
            productContainer.setOrientation(LinearLayout.HORIZONTAL);

            //Iterate through all the loans in of this type and add in the container
            for (LoanCollectionSheet loan : clientCollectionSheet.getLoans()) {
                if (loanProduct.getName().equals(loan.getProductShortName())) {
                    //This loan should be shown in this column. So, add it in the container.
                    EditText editText = new EditText(getContext());
                    editText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
                    editText.setText(String.format(Locale.getDefault(), "%f", 0.0));
                    //Set the loan id as the Tag of the EditText
                    // in format 'TYPE:ID' which
                    //will later be used as the identifier for this.
                    editText.setTag(TYPE_LOAN + ":" + loan.getLoanId());
                    productContainer.addView(editText);
                }
            }
            row.addView(productContainer);
        }

        //After Loans, show Savings columns
        for (SavingsProduct product : collectionSheetResponse.getSavingsProducts()) {
            //Since there may be several Savings items in this column, create a container.
            LinearLayout productContainer = new LinearLayout(getContext());
            productContainer.setOrientation(LinearLayout.HORIZONTAL);

            //Iterate through all the Savings in of this type and add in the container
            for (SavingsCollectionSheet saving : clientCollectionSheet.getSavings()) {
                if (saving.getProductId() == product.getId()) {
                    //Add the saving in the container
                    EditText editText = new EditText(getContext());
                    editText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
                    editText.setText(String.format(Locale.getDefault(), "%f", 0.0));
                    //Set the Saving id as the Tag of the EditText
                    // in 'TYPE:ID' format which
                    //will later be used as the identifier for this.
                    editText.setTag(TYPE_SAVING + ":" + saving.getSavingsId());
                    productContainer.addView(editText);
                }
            }
            row.addView(productContainer);
        }

        Spinner spAttendance = new Spinner(getContext());
        //Set the clientId as its tag which will be used as identifier later.
        spAttendance.setTag(clientCollectionSheet.getClientId());
        setSpinner(spAttendance, attendanceTypes);
        row.addView(spAttendance);

        tableProductive.addView(row);
    }

    if (btnSubmitProductive.getVisibility() != View.VISIBLE) {
        //Show the button the first time sheet is loaded.
        btnSubmitProductive.setVisibility(View.VISIBLE);
        btnSubmitProductive.setOnClickListener(this);
    }

    //If this block has been executed, that means the CollectionSheet
    //which is already shown is for groups.
    btnSubmitProductive.setTag(TAG_TYPE_COLLECTION);

    if (tableAdditional.getVisibility() != View.VISIBLE) {
        tableAdditional.setVisibility(View.VISIBLE);
    }
    //Show Additional Views
    TableRow rowPayment = new TableRow(getContext());
    TextView tvLabelPayment = new TextView(getContext());
    tvLabelPayment.setText(getString(R.string.payment_type));
    rowPayment.addView(tvLabelPayment);
    Spinner spPayment = new Spinner(getContext());
    setSpinner(spPayment, paymentTypes);
    rowPayment.addView(spPayment);
    tableAdditional.addView(rowPayment);

    TableRow rowAccount = new TableRow(getContext());
    TextView tvLabelAccount = new TextView(getContext());
    tvLabelAccount.setText(getString(R.string.account_number));
    rowAccount.addView(tvLabelAccount);
    EditText etPayment = new EditText(getContext());
    rowAccount.addView(etPayment);
    tableAdditional.addView(rowAccount);

    TableRow rowCheck = new TableRow(getContext());
    TextView tvLabelCheck = new TextView(getContext());
    tvLabelCheck.setText(getString(R.string.cheque_number));
    rowCheck.addView(tvLabelCheck);
    EditText etCheck = new EditText(getContext());
    rowCheck.addView(etCheck);
    tableAdditional.addView(rowCheck);

    TableRow rowRouting = new TableRow(getContext());
    TextView tvLabelRouting = new TextView(getContext());
    tvLabelRouting.setText(getString(R.string.routing_code));
    rowRouting.addView(tvLabelRouting);
    EditText etRouting = new EditText(getContext());
    rowRouting.addView(etRouting);
    tableAdditional.addView(rowRouting);

    TableRow rowReceipt = new TableRow(getContext());
    TextView tvLabelReceipt = new TextView(getContext());
    tvLabelReceipt.setText(getString(R.string.receipt_number));
    rowReceipt.addView(tvLabelReceipt);
    EditText etReceipt = new EditText(getContext());
    rowReceipt.addView(etReceipt);
    tableAdditional.addView(rowReceipt);

    TableRow rowBank = new TableRow(getContext());
    TextView tvLabelBank = new TextView(getContext());
    tvLabelBank.setText(getString(R.string.bank_number));
    rowBank.addView(tvLabelBank);
    EditText etBank = new EditText(getContext());
    rowBank.addView(etBank);
    tableAdditional.addView(rowBank);
}