Example usage for android.widget RadioGroup getChildCount

List of usage examples for android.widget RadioGroup getChildCount

Introduction

In this page you can find the example usage for android.widget RadioGroup getChildCount.

Prototype

public int getChildCount() 

Source Link

Document

Returns the number of children in the group.

Usage

From source file:universe.constellation.orion.viewer.OrionViewerActivity.java

public void updatePageLayout() {
    String walkOrder = controller.getDirection();
    int lid = controller.getLayout();
    ((RadioGroup) findMyViewById(R.id.layoutGroup))
            .check(lid == 0 ? R.id.layout1 : lid == 1 ? R.id.layout2 : R.id.layout3);
    //((RadioGroup) findMyViewById(R.id.directionGroup)).check(did == 0 ? R.id.direction1 : did == 1 ? R.id.direction2 : R.id.direction3);

    RadioGroup group = (RadioGroup) findMyViewById(R.id.directionGroup);
    for (int i = 0; i < group.getChildCount(); i++) {
        View child = group.getChildAt(i);
        if (child instanceof universe.constellation.orion.viewer.android.RadioButton) {
            universe.constellation.orion.viewer.android.RadioButton button = (universe.constellation.orion.viewer.android.RadioButton) child;
            if (walkOrder.equals(button.getWalkOrder())) {
                group.check(button.getId());
            }/* www .j av  a 2  s  .co m*/
        }
    }
}

From source file:com.esri.squadleader.view.SquadLeaderActivity.java

public SquadLeaderActivity() throws SocketException {
    super();//from   ww w  .j  av a 2s.c o  m
    chemLightCheckedChangeListener = new RadioGroup.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            for (int j = 0; j < group.getChildCount(); j++) {
                final ToggleButton view = (ToggleButton) group.getChildAt(j);
                view.setChecked(view.getId() == checkedId);
            }
        }
    };

    defaultOnSingleTapListener = createDefaultOnSingleTapListener();
}

From source file:com.google.code.twisty.Twisty.java

/** Have our activity manage and persist dialogs, showing and hiding them */
@Override//from  w  w w  .ja  v  a2  s. co m
protected Dialog onCreateDialog(int id) {
    switch (id) {

    case DIALOG_ENTER_WRITEFILE:
        LayoutInflater factory = LayoutInflater.from(this);
        final View textEntryView = factory.inflate(R.layout.save_file_prompt, null);
        final EditText et = (EditText) textEntryView.findViewById(R.id.savefile_entry);
        return new AlertDialog.Builder(Twisty.this).setTitle("Write to file").setView(textEntryView)
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        savefile_path = savegame_dir + "/" + et.getText().toString();
                        // Directly modify the message-object passed to us by the terp thread:
                        dialog_message.path = savefile_path;
                        // Wake up the terp thread again
                        synchronized (glkLayout) {
                            glkLayout.notify();
                        }
                    }
                }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        // This makes op_save() fail.
                        dialog_message.path = "";
                        // Wake up the terp thread again
                        synchronized (glkLayout) {
                            glkLayout.notify();
                        }
                    }
                }).create();

    case DIALOG_ENTER_READFILE:
        restoredialog = new Dialog(Twisty.this);
        restoredialog.setContentView(R.layout.restore_file_prompt);
        restoredialog.setTitle("Read a file");
        android.widget.RadioGroup rg = (RadioGroup) restoredialog.findViewById(R.id.radiomenu);
        updateRestoreRadioButtons(rg);
        android.widget.Button okbutton = (Button) restoredialog.findViewById(R.id.restoreokbutton);
        okbutton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                android.widget.RadioGroup rg = (RadioGroup) restoredialog.findViewById(R.id.radiomenu);
                int checkedid = rg.getCheckedRadioButtonId();
                if (rg.getChildCount() == 0) { // no saved games:  FAIL
                    savefile_path = "";
                } else if (checkedid == -1) { // no game selected
                    RadioButton firstbutton = (RadioButton) rg.getChildAt(0); // default to first game
                    savefile_path = savegame_dir + "/" + firstbutton.getText();
                } else {
                    RadioButton checkedbutton = (RadioButton) rg.findViewById(checkedid);
                    savefile_path = savegame_dir + "/" + checkedbutton.getText();
                }
                dismissDialog(DIALOG_ENTER_READFILE);
                // Return control to the z-machine thread
                dialog_message.path = savefile_path;
                synchronized (glkLayout) {
                    glkLayout.notify();
                }
            }
        });
        android.widget.Button cancelbutton = (Button) restoredialog.findViewById(R.id.restorecancelbutton);
        cancelbutton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                dismissDialog(DIALOG_ENTER_READFILE);
                // Return control to the z-machine thread
                dialog_message.path = "";
                synchronized (glkLayout) {
                    glkLayout.notify();
                }
            }
        });
        return restoredialog;

    case DIALOG_CHOOSE_GAME:
        choosegamedialog = new Dialog(Twisty.this);
        choosegamedialog.setContentView(R.layout.choose_game_prompt);
        choosegamedialog.setTitle("Choose Game");
        android.widget.RadioGroup zrg = (RadioGroup) choosegamedialog.findViewById(R.id.game_radiomenu);
        updateGameRadioButtons(zrg);
        zrg.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                dismissDialog(DIALOG_CHOOSE_GAME);
                String path = (String) game_paths.get(checkedId);
                if (path != null) {
                    stopTerp();
                    startTerp(path);
                }
            }
        });
        return choosegamedialog;

    case DIALOG_CANT_SAVE:
        return new AlertDialog.Builder(Twisty.this).setTitle("Cannot Access Games")
                .setMessage("Twisty Games folder is not available on external media.")
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        // A path of "" makes op_save() fail.
                        dialog_message.path = "";
                        // Wake up the terp thread again
                        synchronized (glkLayout) {
                            glkLayout.notify();
                        }
                    }
                }).create();

    case DIALOG_NO_SDCARD:
        return new AlertDialog.Builder(Twisty.this).setTitle("No External Media")
                .setMessage("Cannot find sdcard or other media.")
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        // do nothing
                    }
                }).create();
    }
    return null;
}

From source file:sliding_tab.SlidingTabs.java

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public View getView(final int position, View convertView, ViewGroup viewGroup) {
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    convertView = inflater.inflate(R.layout.event_attending_list_item, null);

    TextView name = (TextView) convertView.findViewById(R.id.tv_ea_list_item);
    final RadioGroup radioGroup = (RadioGroup) convertView.findViewById(R.id.radioGroup);
    radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            ArrayList<String>[] dbResult = Helper.getFriends_From_Event(Event_ID);
            switch (radioGroup.getCheckedRadioButtonId()) {
            case R.id.rb_ea_list_yes: {
                Update_Attending(dbResult, Constants.Yes, position);
                break;
            }/*from   w w w  .ja v a2 s  . c  o m*/
            case R.id.rb_ea_list_maybe: {
                Update_Attending(dbResult, Constants.Maybe, position);
                break;
            }
            case R.id.rb_ea_list_no: {
                Update_Attending(dbResult, Constants.No, position);
                break;
            }
            }
        }
    });
    ArrayList<String>[] dbResult = Helper.getFriends_From_Event(Event_ID);
    //name.setText(dbResult[1].get(position));
    name.setText(Helper.getNickname(dbResult[1].get(position)));
    switch (dbResult[2].get(position)) {
    case Constants.Yes: {
        radioGroup.check(R.id.rb_ea_list_yes);
        break;
    }
    case Constants.Maybe: {
        radioGroup.check(R.id.rb_ea_list_maybe);
        break;
    }
    case Constants.No: {
        radioGroup.check(R.id.rb_ea_list_no);
        break;
    }
    default: {
        break;
    }
    }
    if (!dbResult[1].get(position).equals(Constants.MY_User_ID)) {
        for (int i = 0; i < radioGroup.getChildCount(); i++) {
            radioGroup.getChildAt(i).setEnabled(false);
        }
    }

    return convertView;
}

From source file:com.wanikani.androidnotifier.ItemsFragment.java

/**
 * Builds the GUI and create the default item listing. Which is
 * by item type, sorted by time.//from ww  w.ja  v  a 2 s.c  o  m
 * @param inflater the inflater
 * @param container the parent view
 * @param savedInstance an (unused) bundle
 */
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
    RadioGroup rg;
    ImageButton btn;
    View sview;
    int i;

    super.onCreateView(inflater, container, bundle);

    scheduleRefresh();

    parent = inflater.inflate(R.layout.items, container, false);

    lview = (ListView) parent.findViewById(R.id.lv_levels);
    lview.setAdapter(lad);
    lview.setOnItemClickListener(lcl);

    iview = (ListView) parent.findViewById(R.id.lv_items);
    iview.setAdapter(iad);

    sview = parent.findViewById(R.id.it_search_win);
    isd = new ItemSearchDialog(sview, iss, fmap.get(filterType), iad);

    btn = (ImageButton) parent.findViewById(R.id.btn_item_filter);
    btn.setOnClickListener(mpl);
    btn = (ImageButton) parent.findViewById(R.id.btn_item_sort);
    btn.setOnClickListener(mpl);
    btn = (ImageButton) parent.findViewById(R.id.btn_item_view);
    btn.setOnClickListener(mpl);
    btn = (ImageButton) parent.findViewById(R.id.btn_item_search);
    btn.setOnClickListener(mpl);

    rg = (RadioGroup) parent.findViewById(R.id.rg_filter);
    for (i = 0; i < rg.getChildCount(); i++)
        rg.getChildAt(i).setOnClickListener(rgl);
    rg.check(R.id.btn_filter_none);

    rg = (RadioGroup) parent.findViewById(R.id.rg_order);
    for (i = 0; i < rg.getChildCount(); i++)
        rg.getChildAt(i).setOnClickListener(rgl);
    rg.check(R.id.btn_sort_type);

    enableSorting(true, true, true, true);

    return parent;
}

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (mTts.isSpeaking()) {
        mTts.stop();/*from  w  w w .j  a  v a2s .  c o  m*/
    }

    StringBuffer sb = new StringBuffer();
    switch (item.getItemId()) {
    /*      
             case(R.id.set_language):   
    initSetLanguage();
    //refresh the menu options
    supportInvalidateOptionsMenu(); //added by Mike, 20160507
    invalidateOptionsMenu();
    return true;
             case(R.id.speak):
    processSpeak(sb);
    return true;
             case(R.id.settings):
    //20160417
    //Reference: http://stackoverflow.com/questions/16954196/alertdialog-with-checkbox-in-android;
    //last accessed: 20160408; answer by: kamal; edited by: Empty2K12
    final CharSequence[] items = {UsbongConstants.AUTO_NARRATE_STRING, UsbongConstants.AUTO_PLAY_STRING, UsbongConstants.AUTO_LOOP_STRING};
    // arraylist to keep the selected items
    selectedSettingsItems=new ArrayList<Integer>();
            
    //check saved settings
    if (UsbongUtils.IS_IN_AUTO_NARRATE_MODE) {               
       selectedSettingsItems.add(UsbongConstants.AUTO_NARRATE);         
    }
    if (UsbongUtils.IS_IN_AUTO_PLAY_MODE) {
       selectedSettingsItems.add(UsbongConstants.AUTO_PLAY);   
       selectedSettingsItems.add(UsbongConstants.AUTO_NARRATE); //if AUTO_PLAY is checked, AUTO_NARRATE should also be checked
     }                       
    if (UsbongUtils.IS_IN_AUTO_LOOP_MODE) {               
       selectedSettingsItems.add(UsbongConstants.AUTO_LOOP);         
    }
             
     selectedSettingsItemsInBoolean = new boolean[items.length];
     for(int k=0; k<items.length; k++) {
        selectedSettingsItemsInBoolean[k] = false;                   
     }
     for(int i=0; i<selectedSettingsItems.size(); i++) {
        selectedSettingsItemsInBoolean[selectedSettingsItems.get(i)] = true;
     }
                       
    inAppSettingsDialog = new AlertDialog.Builder(this)
    .setTitle("Settings")
    .setMultiChoiceItems(items, selectedSettingsItemsInBoolean, new DialogInterface.OnMultiChoiceClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int indexSelected, boolean isChecked) {
           Log.d(">>>","onClick");
            
           if (isChecked) {
                // If the user checked the item, add it to the selected items
                selectedSettingsItems.add(indexSelected);
                if ((indexSelected==UsbongConstants.AUTO_PLAY) 
                     && !selectedSettingsItems.contains(UsbongConstants.AUTO_NARRATE)) {
                    final ListView list = inAppSettingsDialog.getListView();
                    list.setItemChecked(UsbongConstants.AUTO_NARRATE, true);
                }                       
            } else if (selectedSettingsItems.contains(indexSelected)) {
               if ((indexSelected==UsbongConstants.AUTO_NARRATE) 
                  && selectedSettingsItems.contains(UsbongConstants.AUTO_PLAY)) {
                    final ListView list = inAppSettingsDialog.getListView();
                    list.setItemChecked(indexSelected, false);
               }
               else {           
                   // Else, if the item is already in the array, remove it
                   selectedSettingsItems.remove(Integer.valueOf(indexSelected));
               }
            }
                    
            //updated selectedSettingsItemsInBoolean
           for(int k=0; k<items.length; k++) {
              selectedSettingsItemsInBoolean[k] = false;                   
           }
           for(int i=0; i<selectedSettingsItems.size(); i++) {
              selectedSettingsItemsInBoolean[selectedSettingsItems.get(i)] = true;
           }
        }
    }).setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int id) {
            try {          
              InputStreamReader reader = UsbongUtils.getFileFromSDCardAsReader(UsbongUtils.BASE_FILE_PATH + "usbong.config");   
              BufferedReader br = new BufferedReader(reader);          
               String currLineString;           
            
               //write first to a temporary file
             PrintWriter out = UsbongUtils.getFileFromSDCardAsWriter(UsbongUtils.BASE_FILE_PATH + "usbong.config" +"TEMP");
            
               while((currLineString=br.readLine())!=null)
               {    
                  Log.d(">>>", "currLineString: "+currLineString);
                if ((currLineString.contains("IS_IN_AUTO_NARRATE_MODE="))
                || (currLineString.contains("IS_IN_AUTO_PLAY_MODE="))
                || (currLineString.contains("IS_IN_AUTO_LOOP_MODE="))) {
                   continue;
                }   
                else {
                   out.println(currLineString);                       
                }
               }                       
            
             for (int i=0; i<items.length; i++) {
                Log.d(">>>>", i+"");
                if (selectedSettingsItemsInBoolean[i]==true) {
                   if (i==UsbongConstants.AUTO_NARRATE) {
                       out.println("IS_IN_AUTO_NARRATE_MODE=ON");
                       UsbongUtils.IS_IN_AUTO_NARRATE_MODE=true;                     
                   }                        
                   else if (i==UsbongConstants.AUTO_PLAY) {
                       out.println("IS_IN_AUTO_PLAY_MODE=ON");
                       UsbongUtils.IS_IN_AUTO_PLAY_MODE=true;                  
                   }   
                   else if (i==UsbongConstants.AUTO_LOOP) {
                       out.println("IS_IN_AUTO_LOOP_MODE=ON");
                       UsbongUtils.IS_IN_AUTO_LOOP_MODE=true;                  
                   }
                }
                else {
                   if (i==UsbongConstants.AUTO_NARRATE) {
                       out.println("IS_IN_AUTO_NARRATE_MODE=OFF");
                       UsbongUtils.IS_IN_AUTO_NARRATE_MODE=false;                                             
                   }                     
                   else if (i==UsbongConstants.AUTO_PLAY) {
                       out.println("IS_IN_AUTO_PLAY_MODE=OFF");
                       UsbongUtils.IS_IN_AUTO_PLAY_MODE=false;   
                   }
                   else if (i==UsbongConstants.AUTO_LOOP) {
                       out.println("IS_IN_AUTO_LOOP_MODE=OFF");
                       UsbongUtils.IS_IN_AUTO_LOOP_MODE=false;   
                   }
                }            
             }               
              out.close(); //remember to close
                      
              //copy temp file to actual usbong.config file
              InputStreamReader reader2 = UsbongUtils.getFileFromSDCardAsReader(UsbongUtils.BASE_FILE_PATH + "usbong.config"+"TEMP");   
              BufferedReader br2 = new BufferedReader(reader2);          
               String currLineString2;           
            
               //write to actual usbong.config file
             PrintWriter out2 = UsbongUtils.getFileFromSDCardAsWriter(UsbongUtils.BASE_FILE_PATH + "usbong.config");
            
               while((currLineString2=br2.readLine())!=null)
               {    
                out2.println(currLineString2);                       
               }                    
               out2.close();
                       
               UsbongUtils.deleteRecursive(new File(UsbongUtils.BASE_FILE_PATH + "usbong.config"+"TEMP"));
           }
           catch(Exception e) {
              e.printStackTrace();
           }                
        }
    }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int id) {
            //  Your code when user clicked on Cancel
        }
    }).create();
    inAppSettingsDialog.show();
    return true;
    */
    case (R.id.about):
        new AlertDialog.Builder(UsbongDecisionTreeEngineActivity.this).setTitle("About")
                .setMessage(UsbongUtils.readTextFileInAssetsFolder(UsbongDecisionTreeEngineActivity.this,
                        "credits.txt")) //don't add a '/', otherwise the file would not be found
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                }).show();
        return true;
    case (R.id.account):
        final EditText firstName = new EditText(this);
        firstName.setHint("First Name");
        final EditText surName = new EditText(this);
        surName.setHint("Surname");
        final EditText contactNumber = new EditText(this);
        contactNumber.setHint("Contact Number");
        contactNumber.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);

        //added by Mike, 20170223
        final RadioGroup preference = new RadioGroup(this);
        preference.setOrientation(RadioGroup.HORIZONTAL);

        RadioButton meetup = new AppCompatRadioButton(this);
        meetup.setText("Meet-up");
        preference.addView(meetup);

        RadioButton shipping = new AppCompatRadioButton(this);
        shipping.setText("Shipping");
        preference.addView(shipping);

        final EditText shippingAddress = new EditText(this);
        shippingAddress.setHint("Shipping Address");
        shippingAddress.setMinLines(5);

        //added by Mike, 20170223
        final RadioGroup modeOfPayment = new RadioGroup(this);
        modeOfPayment.setOrientation(RadioGroup.VERTICAL);

        RadioButton cashUponMeetup = new AppCompatRadioButton(this);
        cashUponMeetup.setText("Cash upon meet-up");
        modeOfPayment.addView(cashUponMeetup);

        RadioButton bankDeposit = new AppCompatRadioButton(this);
        bankDeposit.setText("Bank Deposit");
        modeOfPayment.addView(bankDeposit);

        RadioButton peraPadala = new AppCompatRadioButton(this);
        peraPadala.setText("Pera Padala");
        modeOfPayment.addView(peraPadala);

        //Reference: http://stackoverflow.com/questions/23024831/android-shared-preferences-example
        //; last accessed: 20150609
        //answer by Elenasys
        //added by Mike, 20150207
        SharedPreferences prefs = getSharedPreferences(UsbongConstants.MY_ACCOUNT_DETAILS, MODE_PRIVATE);
        if (prefs != null) {
            firstName.setText(prefs.getString("firstName", ""));//"" is the default value.
            surName.setText(prefs.getString("surname", "")); //"" is the default value.
            contactNumber.setText(prefs.getString("contactNumber", "")); //"" is the default value.

            //added by Mike, 20170223
            ((RadioButton) preference.getChildAt(prefs.getInt("preference", UsbongConstants.defaultPreference)))
                    .setChecked(true);

            shippingAddress.setText(prefs.getString("shippingAddress", "")); //"" is the default value.

            //added by Mike, 20170223              
            ((RadioButton) modeOfPayment
                    .getChildAt(prefs.getInt("modeOfPayment", UsbongConstants.defaultModeOfPayment)))
                            .setChecked(true);
        }

        LinearLayout ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);
        ll.addView(firstName);
        ll.addView(surName);
        ll.addView(contactNumber);
        ll.addView(preference);
        ll.addView(shippingAddress);
        ll.addView(modeOfPayment);

        new AlertDialog.Builder(this).setTitle("My Account").setView(ll)
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        //ACTION
                    }
                }).setPositiveButton("Save & Exit", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        //ACTION
                        //Reference: http://stackoverflow.com/questions/23024831/android-shared-preferences-example
                        //; last accessed: 20150609
                        //answer by Elenasys
                        //added by Mike, 20170207
                        SharedPreferences.Editor editor = getSharedPreferences(
                                UsbongConstants.MY_ACCOUNT_DETAILS, MODE_PRIVATE).edit();
                        editor.putString("firstName", firstName.getText().toString());
                        editor.putString("surname", surName.getText().toString());
                        editor.putString("contactNumber", contactNumber.getText().toString());

                        for (int i = 0; i < preference.getChildCount(); i++) {
                            if (((RadioButton) preference.getChildAt(i)).isChecked()) {
                                currPreference = i;
                            }
                        }
                        editor.putInt("preference", currPreference); //added by Mike, 20170223                    

                        editor.putString("shippingAddress", shippingAddress.getText().toString());

                        for (int i = 0; i < modeOfPayment.getChildCount(); i++) {
                            if (((RadioButton) modeOfPayment.getChildAt(i)).isChecked()) {
                                currModeOfPayment = i;
                            }
                        }
                        editor.putInt("modeOfPayment", currModeOfPayment); //added by Mike, 20170223
                        editor.commit();
                    }
                }).show();
        return true;
    case android.R.id.home: //added by Mike, 22 Sept. 2015
        /*//commented out by Mike, 201702014; UsbongDecisionTreeEngineActivity is already the main menu            
                    processReturnToMainMenuActivity();
        */
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

From source file:org.thoughtland.xlocation.ActivityShare.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Check privacy service client
    if (!PrivacyService.checkClient())
        return;// w  ww .jav a 2 s.c  om

    // Get data
    int userId = Util.getUserId(Process.myUid());
    final Bundle extras = getIntent().getExtras();
    final String action = getIntent().getAction();
    final int[] uids = (extras != null && extras.containsKey(cUidList) ? extras.getIntArray(cUidList)
            : new int[0]);
    final String restrictionName = (extras != null ? extras.getString(cRestriction) : null);
    int choice = (extras != null && extras.containsKey(cChoice) ? extras.getInt(cChoice) : -1);
    if (action.equals(ACTION_EXPORT))
        mFileName = (extras != null && extras.containsKey(cFileName) ? extras.getString(cFileName) : null);

    // License check
    if (action.equals(ACTION_IMPORT) || action.equals(ACTION_EXPORT)) {
        if (!Util.isProEnabled() && Util.hasProLicense(this) == null) {
            Util.viewUri(this, ActivityMain.cProUri);
            finish();
            return;
        }
    } else if (action.equals(ACTION_FETCH) || (action.equals(ACTION_TOGGLE) && uids.length > 1)) {
        if (Util.hasProLicense(this) == null) {
            Util.viewUri(this, ActivityMain.cProUri);
            finish();
            return;
        }
    }

    // Registration check
    if (action.equals(ACTION_SUBMIT) && !registerDevice(this)) {
        finish();
        return;
    }

    // Check whether we need a user interface
    if (extras != null && extras.containsKey(cInteractive) && extras.getBoolean(cInteractive, false))
        mInteractive = true;

    // Set layout
    setContentView(R.layout.sharelist);

    // Reference controls
    final TextView tvDescription = (TextView) findViewById(R.id.tvDescription);
    final ScrollView svToggle = (ScrollView) findViewById(R.id.svToggle);
    final RadioGroup rgToggle = (RadioGroup) findViewById(R.id.rgToggle);
    final Spinner spRestriction = (Spinner) findViewById(R.id.spRestriction);
    RadioButton rbClear = (RadioButton) findViewById(R.id.rbClear);
    RadioButton rbTemplateFull = (RadioButton) findViewById(R.id.rbTemplateFull);
    RadioButton rbODEnable = (RadioButton) findViewById(R.id.rbEnableOndemand);
    RadioButton rbODDisable = (RadioButton) findViewById(R.id.rbDisableOndemand);
    final Spinner spTemplate = (Spinner) findViewById(R.id.spTemplate);
    final CheckBox cbClear = (CheckBox) findViewById(R.id.cbClear);
    final Button btnOk = (Button) findViewById(R.id.btnOk);
    final Button btnCancel = (Button) findViewById(R.id.btnCancel);

    // Set title
    if (action.equals(ACTION_TOGGLE)) {
        mActionId = R.string.menu_toggle;
        setTitle(R.string.menu_toggle);
    } else if (action.equals(ACTION_IMPORT)) {
        mActionId = R.string.menu_import;
        setTitle(R.string.menu_import);
    } else if (action.equals(ACTION_EXPORT)) {
        mActionId = R.string.menu_export;
        setTitle(R.string.menu_export);
    } else if (action.equals(ACTION_FETCH)) {
        mActionId = R.string.menu_fetch;
        setTitle(R.string.menu_fetch);
    } else if (action.equals(ACTION_SUBMIT)) {
        mActionId = R.string.menu_submit;
        setTitle(R.string.menu_submit);
    } else {
        finish();
        return;
    }

    // Get localized restriction name
    List<String> listRestrictionName = new ArrayList<String>(
            PrivacyManager.getRestrictions(this).navigableKeySet());
    listRestrictionName.add(0, getString(R.string.menu_all));

    // Build restriction adapter
    SpinnerAdapter saRestriction = new SpinnerAdapter(this, android.R.layout.simple_spinner_item);
    saRestriction.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    saRestriction.addAll(listRestrictionName);

    // Setup restriction spinner
    int pos = 0;
    if (restrictionName != null)
        for (String restriction : PrivacyManager.getRestrictions(this).values()) {
            pos++;
            if (restrictionName.equals(restriction))
                break;
        }

    spRestriction.setAdapter(saRestriction);
    spRestriction.setSelection(pos);

    // Build template adapter
    SpinnerAdapter spAdapter = new SpinnerAdapter(this, android.R.layout.simple_spinner_item);
    spAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spAdapter.add(getString(R.string.title_default));
    for (int i = 1; i <= 4; i++)
        spAdapter.add(getString(R.string.title_alternate) + " " + i);
    spTemplate.setAdapter(spAdapter);

    // Build application list
    AppListTask appListTask = new AppListTask();
    appListTask.executeOnExecutor(mExecutor, uids);

    // Import/export filename
    if (action.equals(ACTION_EXPORT) || action.equals(ACTION_IMPORT)) {
        // Check for availability of sharing intent
        Intent file = new Intent(Intent.ACTION_GET_CONTENT);
        file.setType("file/*");
        boolean hasIntent = Util.isIntentAvailable(ActivityShare.this, file);

        // Get file name
        if (mFileName == null)
            if (action.equals(ACTION_EXPORT)) {
                String packageName = null;
                if (uids.length == 1)
                    try {
                        ApplicationInfoEx appInfo = new ApplicationInfoEx(this, uids[0]);
                        packageName = appInfo.getPackageName().get(0);
                    } catch (Throwable ex) {
                        Util.bug(null, ex);
                    }
                mFileName = getFileName(this, hasIntent, packageName);
            } else
                mFileName = (hasIntent ? null : getFileName(this, false, null));

        if (mFileName == null)
            fileChooser();
        else
            showFileName();

        if (action.equals(ACTION_IMPORT))
            cbClear.setVisibility(View.VISIBLE);

    } else if (action.equals(ACTION_FETCH)) {
        tvDescription.setText(getBaseURL());
        cbClear.setVisibility(View.VISIBLE);

    } else if (action.equals(ACTION_TOGGLE)) {
        tvDescription.setText(R.string.menu_toggle);
        spRestriction.setVisibility(View.VISIBLE);
        svToggle.setVisibility(View.VISIBLE);

        // Listen for radio button
        rgToggle.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                btnOk.setEnabled(checkedId >= 0);
                spRestriction.setVisibility(
                        checkedId == R.id.rbEnableOndemand || checkedId == R.id.rbDisableOndemand ? View.GONE
                                : View.VISIBLE);

                spTemplate.setVisibility(checkedId == R.id.rbTemplateCategory
                        || checkedId == R.id.rbTemplateFull || checkedId == R.id.rbTemplateMergeSet
                        || checkedId == R.id.rbTemplateMergeReset ? View.VISIBLE : View.GONE);
            }
        });

        boolean ondemand = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingOnDemand, true);
        rbODEnable.setVisibility(ondemand ? View.VISIBLE : View.GONE);
        rbODDisable.setVisibility(ondemand ? View.VISIBLE : View.GONE);

        if (choice == CHOICE_CLEAR)
            rbClear.setChecked(true);
        else if (choice == CHOICE_TEMPLATE)
            rbTemplateFull.setChecked(true);

    } else
        tvDescription.setText(getBaseURL());

    if (mInteractive) {
        // Enable ok
        // (showFileName does this for export/import)
        if (action.equals(ACTION_SUBMIT) || action.equals(ACTION_FETCH))
            btnOk.setEnabled(true);

        // Listen for ok
        btnOk.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View v) {
                btnOk.setEnabled(false);

                // Toggle
                if (action.equals(ACTION_TOGGLE)) {
                    mRunning = true;
                    for (int i = 0; i < rgToggle.getChildCount(); i++)
                        ((RadioButton) rgToggle.getChildAt(i)).setEnabled(false);
                    int pos = spRestriction.getSelectedItemPosition();
                    String restrictionName = (pos == 0 ? null
                            : (String) PrivacyManager.getRestrictions(ActivityShare.this).values().toArray()[pos
                                    - 1]);
                    new ToggleTask().executeOnExecutor(mExecutor, restrictionName);

                    // Import
                } else if (action.equals(ACTION_IMPORT)) {
                    mRunning = true;
                    cbClear.setEnabled(false);
                    new ImportTask().executeOnExecutor(mExecutor, new File(mFileName), cbClear.isChecked());
                }

                // Export
                else if (action.equals(ACTION_EXPORT)) {
                    mRunning = true;
                    new ExportTask().executeOnExecutor(mExecutor, new File(mFileName));

                    // Fetch
                } else if (action.equals(ACTION_FETCH)) {
                    if (uids.length > 0) {
                        mRunning = true;
                        cbClear.setEnabled(false);
                        new FetchTask().executeOnExecutor(mExecutor, cbClear.isChecked());
                    }
                }

                // Submit
                else if (action.equals(ACTION_SUBMIT)) {
                    if (uids.length > 0) {
                        if (uids.length <= cSubmitLimit) {
                            mRunning = true;
                            new SubmitTask().executeOnExecutor(mExecutor);
                        } else {
                            String message = getString(R.string.msg_limit, cSubmitLimit + 1);
                            Toast.makeText(ActivityShare.this, message, Toast.LENGTH_LONG).show();
                            btnOk.setEnabled(false);
                        }
                    }
                }
            }
        });

    } else
        btnOk.setEnabled(false);

    // Listen for cancel
    btnCancel.setOnClickListener(new Button.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mRunning) {
                mAbort = true;
                Toast.makeText(ActivityShare.this, getString(R.string.msg_abort), Toast.LENGTH_LONG).show();
            } else
                finish();
        }
    });
}

From source file:biz.bokhorst.xprivacy.ActivityShare.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Check privacy service client
    if (!PrivacyService.checkClient())
        return;/* w w w  .j  av a2  s . c  o  m*/

    // Get data
    int userId = Util.getUserId(Process.myUid());
    final Bundle extras = getIntent().getExtras();
    final String action = getIntent().getAction();
    final int[] uids = (extras != null && extras.containsKey(cUidList) ? extras.getIntArray(cUidList)
            : new int[0]);
    final String restrictionName = (extras != null ? extras.getString(cRestriction) : null);
    int choice = (extras != null && extras.containsKey(cChoice) ? extras.getInt(cChoice) : -1);
    if (action.equals(ACTION_EXPORT))
        mFileName = (extras != null && extras.containsKey(cFileName) ? extras.getString(cFileName) : null);

    // License check
    if (action.equals(ACTION_IMPORT) || action.equals(ACTION_EXPORT)) {
        if (!Util.isProEnabled() && Util.hasProLicense(this) == null) {
            Util.viewUri(this, ActivityMain.cProUri);
            finish();
            return;
        }
    } else if (action.equals(ACTION_FETCH) || (action.equals(ACTION_TOGGLE) && uids.length > 1)) {
        if (Util.hasProLicense(this) == null) {
            Util.viewUri(this, ActivityMain.cProUri);
            finish();
            return;
        }
    }

    // Registration check
    if (action.equals(ACTION_SUBMIT) && !registerDevice(this)) {
        finish();
        return;
    }

    // Check whether we need a user interface
    if (extras != null && extras.containsKey(cInteractive) && extras.getBoolean(cInteractive, false))
        mInteractive = true;

    // Set layout
    setContentView(R.layout.sharelist);
    setSupportActionBar((Toolbar) findViewById(R.id.widgetToolbar));

    // Reference controls
    final TextView tvDescription = (TextView) findViewById(R.id.tvDescription);
    final ScrollView svToggle = (ScrollView) findViewById(R.id.svToggle);
    final RadioGroup rgToggle = (RadioGroup) findViewById(R.id.rgToggle);
    final Spinner spRestriction = (Spinner) findViewById(R.id.spRestriction);
    RadioButton rbClear = (RadioButton) findViewById(R.id.rbClear);
    RadioButton rbTemplateFull = (RadioButton) findViewById(R.id.rbTemplateFull);
    RadioButton rbODEnable = (RadioButton) findViewById(R.id.rbEnableOndemand);
    RadioButton rbODDisable = (RadioButton) findViewById(R.id.rbDisableOndemand);
    final Spinner spTemplate = (Spinner) findViewById(R.id.spTemplate);
    final CheckBox cbClear = (CheckBox) findViewById(R.id.cbClear);
    final Button btnOk = (Button) findViewById(R.id.btnOk);
    final Button btnCancel = (Button) findViewById(R.id.btnCancel);

    // Set title
    if (action.equals(ACTION_TOGGLE)) {
        mActionId = R.string.menu_toggle;
        getSupportActionBar().setSubtitle(R.string.menu_toggle);
    } else if (action.equals(ACTION_IMPORT)) {
        mActionId = R.string.menu_import;
        getSupportActionBar().setSubtitle(R.string.menu_import);
    } else if (action.equals(ACTION_EXPORT)) {
        mActionId = R.string.menu_export;
        getSupportActionBar().setSubtitle(R.string.menu_export);
    } else if (action.equals(ACTION_FETCH)) {
        mActionId = R.string.menu_fetch;
        getSupportActionBar().setSubtitle(R.string.menu_fetch);
    } else if (action.equals(ACTION_SUBMIT)) {
        mActionId = R.string.menu_submit;
        getSupportActionBar().setSubtitle(R.string.menu_submit);
    } else {
        finish();
        return;
    }

    // Get localized restriction name
    List<String> listRestrictionName = new ArrayList<String>(
            PrivacyManager.getRestrictions(this).navigableKeySet());
    listRestrictionName.add(0, getString(R.string.menu_all));

    // Build restriction adapter
    SpinnerAdapter saRestriction = new SpinnerAdapter(this, android.R.layout.simple_spinner_item);
    saRestriction.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    saRestriction.addAll(listRestrictionName);

    // Setup restriction spinner
    int pos = 0;
    if (restrictionName != null)
        for (String restriction : PrivacyManager.getRestrictions(this).values()) {
            pos++;
            if (restrictionName.equals(restriction))
                break;
        }

    spRestriction.setAdapter(saRestriction);
    spRestriction.setSelection(pos);

    // Build template adapter
    SpinnerAdapter spAdapter = new SpinnerAdapter(this, android.R.layout.simple_spinner_item);
    spAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    String defaultName = PrivacyManager.getSetting(userId, Meta.cTypeTemplateName, "0",
            getString(R.string.title_default));
    spAdapter.add(defaultName);
    for (int i = 1; i <= 4; i++) {
        String alternateName = PrivacyManager.getSetting(userId, Meta.cTypeTemplateName, Integer.toString(i),
                getString(R.string.title_alternate) + " " + i);
        spAdapter.add(alternateName);
    }
    spTemplate.setAdapter(spAdapter);

    // Build application list
    AppListTask appListTask = new AppListTask();
    appListTask.executeOnExecutor(mExecutor, uids);

    // Import/export filename
    if (action.equals(ACTION_EXPORT) || action.equals(ACTION_IMPORT)) {
        // Check for availability of sharing intent
        Intent file = new Intent(Intent.ACTION_GET_CONTENT);
        file.setType("file/*");
        boolean hasIntent = Util.isIntentAvailable(ActivityShare.this, file);

        // Get file name
        if (mFileName == null)
            if (action.equals(ACTION_EXPORT)) {
                String packageName = null;
                if (uids.length == 1)
                    try {
                        ApplicationInfoEx appInfo = new ApplicationInfoEx(this, uids[0]);
                        packageName = appInfo.getPackageName().get(0);
                    } catch (Throwable ex) {
                        Util.bug(null, ex);
                    }
                mFileName = getFileName(this, hasIntent, packageName);
            } else
                mFileName = (hasIntent ? null : getFileName(this, false, null));

        if (mFileName == null)
            fileChooser();
        else
            showFileName();

        if (action.equals(ACTION_IMPORT))
            cbClear.setVisibility(View.VISIBLE);

    } else if (action.equals(ACTION_FETCH)) {
        tvDescription.setText(getBaseURL());
        cbClear.setVisibility(View.VISIBLE);

    } else if (action.equals(ACTION_TOGGLE)) {
        tvDescription.setVisibility(View.GONE);
        spRestriction.setVisibility(View.VISIBLE);
        svToggle.setVisibility(View.VISIBLE);

        // Listen for radio button
        rgToggle.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                btnOk.setEnabled(checkedId >= 0);
                spRestriction.setVisibility(
                        checkedId == R.id.rbEnableOndemand || checkedId == R.id.rbDisableOndemand ? View.GONE
                                : View.VISIBLE);

                spTemplate.setVisibility(checkedId == R.id.rbTemplateCategory
                        || checkedId == R.id.rbTemplateFull || checkedId == R.id.rbTemplateMergeSet
                        || checkedId == R.id.rbTemplateMergeReset ? View.VISIBLE : View.GONE);
            }
        });

        boolean ondemand = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingOnDemand, true);
        rbODEnable.setVisibility(ondemand ? View.VISIBLE : View.GONE);
        rbODDisable.setVisibility(ondemand ? View.VISIBLE : View.GONE);

        if (choice == CHOICE_CLEAR)
            rbClear.setChecked(true);
        else if (choice == CHOICE_TEMPLATE)
            rbTemplateFull.setChecked(true);

    } else
        tvDescription.setText(getBaseURL());

    if (mInteractive) {
        // Enable ok
        // (showFileName does this for export/import)
        if (action.equals(ACTION_SUBMIT) || action.equals(ACTION_FETCH))
            btnOk.setEnabled(true);

        // Listen for ok
        btnOk.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View v) {
                btnOk.setEnabled(false);

                // Toggle
                if (action.equals(ACTION_TOGGLE)) {
                    mRunning = true;
                    for (int i = 0; i < rgToggle.getChildCount(); i++)
                        ((RadioButton) rgToggle.getChildAt(i)).setEnabled(false);
                    int pos = spRestriction.getSelectedItemPosition();
                    String restrictionName = (pos == 0 ? null
                            : (String) PrivacyManager.getRestrictions(ActivityShare.this).values().toArray()[pos
                                    - 1]);
                    new ToggleTask().executeOnExecutor(mExecutor, restrictionName);

                    // Import
                } else if (action.equals(ACTION_IMPORT)) {
                    mRunning = true;
                    cbClear.setEnabled(false);
                    new ImportTask().executeOnExecutor(mExecutor, new File(mFileName), cbClear.isChecked());
                }

                // Export
                else if (action.equals(ACTION_EXPORT)) {
                    mRunning = true;
                    new ExportTask().executeOnExecutor(mExecutor, new File(mFileName));

                    // Fetch
                } else if (action.equals(ACTION_FETCH)) {
                    if (uids.length > 0) {
                        mRunning = true;
                        cbClear.setEnabled(false);
                        new FetchTask().executeOnExecutor(mExecutor, cbClear.isChecked());
                    }
                }

                // Submit
                else if (action.equals(ACTION_SUBMIT)) {
                    if (uids.length > 0) {
                        if (uids.length <= cSubmitLimit) {
                            mRunning = true;
                            new SubmitTask().executeOnExecutor(mExecutor);
                        } else {
                            String message = getString(R.string.msg_limit, cSubmitLimit + 1);
                            Toast.makeText(ActivityShare.this, message, Toast.LENGTH_LONG).show();
                            btnOk.setEnabled(false);
                        }
                    }
                }
            }
        });

    } else
        btnOk.setEnabled(false);

    // Listen for cancel
    btnCancel.setOnClickListener(new Button.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mRunning) {
                mAbort = true;
                Toast.makeText(ActivityShare.this, getString(R.string.msg_abort), Toast.LENGTH_LONG).show();
            } else
                finish();
        }
    });
}