Example usage for android.widget ArrayAdapter ArrayAdapter

List of usage examples for android.widget ArrayAdapter ArrayAdapter

Introduction

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

Prototype

public ArrayAdapter(@NonNull Context context, @LayoutRes int resource, @NonNull List<T> objects) 

Source Link

Document

Constructor

Usage

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.
 * /*from  w w w  .  j av a  2  s .co 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:com.mifos.mifosxdroid.online.grouploanaccount.GroupLoanAccountFragment.java

@Override
public void showLoanPurposeSpinner(ResponseBody result) {

    mResponse = result;/* w  w w  . j a v a 2s.  co  m*/

    inflateFrequencyPeriodSpinner(mResponse);
    inflateAmortizationSpinner(mResponse);
    inflateInterestCalculationPeriodSpinner(mResponse);
    //inflaterepaymentFrequencyTypeOptionsSpinner();
    inflatetransactionProcessingStrategySpinner(mResponse);

    final List<LoanPurposeOptions> loanPurposeOptionsType = new ArrayList<>();
    // you can use this array to populate your spinner
    final ArrayList<String> loanPurposeOptionsTypeNames = new ArrayList<String>();
    //Try to get response body
    BufferedReader reader = null;
    StringBuilder sb = new StringBuilder();
    try {
        reader = new BufferedReader(new InputStreamReader(result.byteStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        JSONObject obj = new JSONObject(sb.toString());
        if (obj.has("loanPurposeOptions")) {
            JSONArray loanPurposeOptionsTypes = obj.getJSONArray("loanPurposeOptions");
            for (int i = 0; i < loanPurposeOptionsTypes.length(); i++) {
                JSONObject loanPurposeOptionsTypesObject = loanPurposeOptionsTypes.getJSONObject(i);
                LoanPurposeOptions loanpurpose = new LoanPurposeOptions();
                loanpurpose.setId(loanPurposeOptionsTypesObject.optInt("id"));
                loanpurpose.setName(loanPurposeOptionsTypesObject.optString("name"));
                loanPurposeOptionsType.add(loanpurpose);
                loanPurposeOptionsTypeNames.add(loanPurposeOptionsTypesObject.optString("name"));
                loanPurposeNameIdHashMap.put(loanpurpose.getName(), loanpurpose.getId());
            }

        }
        String stringResult = sb.toString();
    } catch (Exception e) {
        Log.e(LOG_TAG, "", e);
    }
    final ArrayAdapter<String> loanPTypeAdapter = new ArrayAdapter<>(getActivity(), layout.simple_spinner_item,
            loanPurposeOptionsTypeNames);

    loanPTypeAdapter.setDropDownViewResource(layout.simple_spinner_dropdown_item);
    sp_loan_purpose.setAdapter(loanPTypeAdapter);
    sp_loan_purpose.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            loanPurposeId = loanPurposeNameIdHashMap.get(loanPurposeOptionsTypeNames.get(i));
            Log.d("loanpurpose" + loanPurposeOptionsTypeNames.get(i), String.valueOf(loanPurposeId));
            if (loanPurposeId != -1) {

            } else {

                Toast.makeText(getActivity(), getString(R.string.error_select_fund), Toast.LENGTH_SHORT).show();

            }

        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });
}

From source file:com.mifos.mifosxdroid.online.GroupLoanAccountFragment.java

private void inflatetransactionProcessingStrategySpinner() {
    showProgress(true);/*w ww  .jav a2s  . c  o m*/
    App.apiManager.getGroupLoansAccountTemplate(groupId, productId, new Callback<Response>() {
        @Override
        public void success(final Response result, Response response) {
            /* Activity is null - Fragment has been detached; no need to do anything. */
            if (getActivity() == null)
                return;

            Log.d(LOG_TAG, "");

            final List<TransactionProcessingStrategy> transactionProcessingStrategyType = new ArrayList<>();
            // you can use this array to populate your spinner
            final ArrayList<String> transactionProcessingStrategyTypeNames = new ArrayList<String>();
            //Try to get response body
            BufferedReader reader = null;
            StringBuilder sb = new StringBuilder();
            try {
                reader = new BufferedReader(new InputStreamReader(result.getBody().in()));
                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
                JSONObject obj = new JSONObject(sb.toString());
                if (obj.has("transactionProcessingStrategyOptions")) {
                    JSONArray transactionProcessingStrategyTypes = obj
                            .getJSONArray("transactionProcessingStrategyOptions");
                    for (int i = 0; i < transactionProcessingStrategyTypes.length(); i++) {
                        JSONObject transactionProcessingStrategyTypeObject = transactionProcessingStrategyTypes
                                .getJSONObject(i);
                        TransactionProcessingStrategy transactionProcessingStrategy = new TransactionProcessingStrategy();
                        transactionProcessingStrategy
                                .setId(transactionProcessingStrategyTypeObject.optInt("id"));
                        transactionProcessingStrategy
                                .setName(transactionProcessingStrategyTypeObject.optString("name"));
                        transactionProcessingStrategyType.add(transactionProcessingStrategy);
                        transactionProcessingStrategyTypeNames
                                .add(transactionProcessingStrategyTypeObject.optString("name"));
                        transactionProcessingStrategyTypeIdHashMap.put(transactionProcessingStrategy.getName(),
                                transactionProcessingStrategy.getId());
                    }

                }
                String stringResult = sb.toString();
            } catch (Exception e) {
                Log.e(LOG_TAG, "", e);
            }
            final ArrayAdapter<String> transactionProcessingStrategyAdapter = new ArrayAdapter<>(getActivity(),
                    layout.simple_spinner_item, transactionProcessingStrategyTypeNames);

            transactionProcessingStrategyAdapter.setDropDownViewResource(layout.simple_spinner_dropdown_item);

            sp_repaymentstrategy.setAdapter(transactionProcessingStrategyAdapter);
            sp_repaymentstrategy.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                    transactionProcessingStrategyId = transactionProcessingStrategyTypeIdHashMap
                            .get(transactionProcessingStrategyTypeNames.get(i));
                    Log.d("transactionProcessing " + transactionProcessingStrategyTypeNames.get(i),
                            String.valueOf(transactionProcessingStrategyId));
                    if (transactionProcessingStrategyId != -1) {

                    } else {

                        Toast.makeText(getActivity(),
                                getString(R.string.error_select_transactionProcessingStrategy),
                                Toast.LENGTH_SHORT).show();

                    }

                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });

            showProgress(false);

        }

        @Override
        public void failure(RetrofitError retrofitError) {

            Log.d(LOG_TAG, retrofitError.getLocalizedMessage());

            showProgress(false);
        }
    });
}

From source file:com.zira.registration.VehicleInformationActivity.java

@Override
public void processFinish(String output, String methodName) {

    /*try {                  
       new Timer().schedule(new TimerTask() {          
     @Override/* ww  w .  java  2 s.  c  om*/
     public void run() {
         // this code will be executed after 4 seconds    
        Log.e("Inside","timer");
         value=0;
     }
       }, 10000);
               
    } catch (Exception e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
    }*/

    if (methodName.equals(fetchCountry)) {
        Log.e("fetchCountry", output);
        mainModal = parser.parseCountries(output);
        countryList = mainModal.getCountryList();

        if (SingleTon.getInstance().isEdited()) {
            value = 1;
            if (countryList.size() > 0) {
                //edit
                //gettingCountry=mProfileInfoModel.getLicenseplatecountry();//getLicenseplatecountry();
                gettingCountry = mProfileInfoModel.getLicenseplatecountryID();

                //               if(gettingCountry.equals("0"))
                //               {
                //                  gettingCountry=prefs3.getString("countryid", "");
                //                  }
                int i = 0;
                for (Country country : countryList) {
                    //edit
                    //String countryName=country.getCountryName();
                    String countryName = country.getCountryID();
                    //Log.e("", countryName);
                    if (gettingCountry.equals(countryName)) {
                        gettingCountryPosition = i;
                        System.err.println("CountryIndex=" + i);
                    }
                    i++;
                }
            }
        }

        setApapterForCountry();

    } else if (methodName.equals(fetchVehicleModals)) {
        Log.e("fetchVehicleModals", output);
        mainModal = parser.parseVehicles(output);
        vehicleArrayList = mainModal.getVehicleList();
        Log.e("fetchVehicleModals", output);
        /******************************/
        if (vehicleArrayList.size() > 0) {
            if (SingleTon.getInstance().isEdited()) {
                String gettingVehicleMake = mProfileInfoModel.getVechile_make();//"Tata";//
                //               if(gettingVehicleMake.equals(""))
                //               {
                //                  gettingVehicleMake=prefs3.getString("makename", "");
                //               }
                int i = 0;
                for (Vehicle vehicle : vehicleArrayList) {
                    String vehilmake = vehicle.getVehicleMakeName();
                    if (gettingVehicleMake.equals(vehilmake)) {
                        gettingVehicleMakePosition = i;
                    }
                    i++;
                }
            }
        }
        //*******************************Adapter to set make vehicle********************//
        ArrayAdapter<Vehicle> dataAdapter = new ArrayAdapter<Vehicle>(this, R.layout.spinner_list,
                vehicleArrayList);
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //TextView tv=(TextView)findViewById(R.id.text1);
        vehicleMakeNameSpinner.setAdapter(dataAdapter);
        vehicleMakeNameSpinner.setSelection(gettingVehicleMakePosition);

        setApapterForVehicleModel(vehicleArrayList.get(gettingVehicleMakePosition).getListModalData());

        State dummyState = new State();
        stateList.clear();
        dummyState.setStateName("Licence Plate State");
        stateList.add(dummyState);
        setApapterForState();

    } else if (methodName.equals(fetchStates)) {
        Log.e("fetchStates", output);
        stateList.clear();
        mainModal = parser.parseStates(output);
        stateList = mainModal.getStateList();
        /*********************************************************/
        if (stateList.size() > 0) {
            if (value == 1) {
                //edit
                //String gettingLicenceState = mProfileInfoModel.getLicenseplatestate();
                String gettingLicenceState = mProfileInfoModel.getLicenseplatestateID();
                //               if(gettingLicenceState.equals("0"))
                //               {
                //                  gettingLicenceState=prefs3.getString("stateid","");
                //                  }
                //               
                int i = 0;
                for (State state : stateList) {
                    //edit
                    //String licenseState = state.getStateName();
                    String licenseState = state.getStateId();

                    if (gettingLicenceState.equals(licenseState)) {
                        gettingStatePosition = i;
                        System.err.println("Stateindex=" + i);
                    }
                    i++;
                }
            }
        }

        /***********************************************************/
        SingleTon.getInstance().setSelectedStates(stateList);
        setApapterForState();
    }

}

From source file:com.nps.micro.view.TestsSectionFragment.java

private void createDeviceChooser(View rootView, final Button runButton) {
    availableDevicesListView = (ListView) rootView.findViewById(R.id.availableDevicesListView);
    availableDevicesAdapter = new ArrayAdapter<String>(getActivity(), R.layout.text_view, devicesList);
    availableDevicesListView.setAdapter(availableDevicesAdapter);
    availableDevicesListView.setTextFilterEnabled(true);
    availableDevicesListView.setOnItemClickListener(new OnItemClickListener() {
        @Override//from  w  w w.  j a  va2 s  . com
        public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
            String item = (String) parent.getItemAtPosition(position);
            selectedDevices.add(ensureUniqueItem(item));
            selectedDevicesAdapter = new StableArrayAdapter(getActivity(), R.layout.text_view, selectedDevices);
            selectedDevicesListView.setAdapter(selectedDevicesAdapter);
            setListViewHeightBasedOnChildren(selectedDevicesListView);
            updateModelSelectedDevices();
        }

        private String ensureUniqueItem(String item) {
            if (selectedDevices.contains(item)) {
                return ensureUniqueItem(item + "'");
            } else {
                return item;
            }
        }
    });
    availableDevicesListView.setOnItemLongClickListener(new OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, final View view, int position, long id) {
            view.setBackgroundColor(Color.CYAN);
            final String item = (String) parent.getItemAtPosition(position);
            final String msg = getResources().getString(R.string.ping_device_info);
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setTitle(R.string.ping_device_title).setMessage(String.format(msg, item))
                    .setPositiveButton(R.string.ping, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            view.setBackgroundColor(Color.BLACK);
                            if (listener != null) {
                                listener.pingDevice(item);
                            }
                            dialog.dismiss();
                        }
                    }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            view.setBackgroundColor(Color.BLACK);
                            dialog.dismiss();
                        }
                    });
            builder.create().show();
            return true;
        }
    });
    setListViewHeightBasedOnChildren(availableDevicesListView);

    selectedDevicesListView = (DynamicListView) rootView.findViewById(R.id.selectedDevicesListView);
    selectedDevicesListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    selectedDevicesAdapter = new StableArrayAdapter(getActivity(), R.layout.text_view, selectedDevices);
    selectedDevicesListView.setListItems(selectedDevices);
    selectedDevicesListView.setAdapter(selectedDevicesAdapter);
    selectedDevicesListView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
            final String item = (String) parent.getItemAtPosition(position);
            selectedDevices.remove(item);
            selectedDevicesAdapter = new StableArrayAdapter(getActivity(), R.layout.text_view, selectedDevices);
            selectedDevicesListView.setAdapter(selectedDevicesAdapter);
            setListViewHeightBasedOnChildren(selectedDevicesListView);
            updateModelSelectedDevices();
        }
    });
    selectedDevicesListView.setOnTouchListener(new ListView.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            int action = event.getAction();
            switch (action) {
            case MotionEvent.ACTION_DOWN:
                v.getParent().requestDisallowInterceptTouchEvent(true);
                break;
            case MotionEvent.ACTION_UP:
                v.getParent().requestDisallowInterceptTouchEvent(false);
                break;
            }
            v.onTouchEvent(event);
            return true;
        }
    });
    setListViewHeightBasedOnChildren(selectedDevicesListView);
}

From source file:com.dsna.android.main.MainActivity.java

private void _initMenu() {
    mDrawerList = (ListView) findViewById(R.id.drawer);

    if (mDrawerList != null) {
        mDrawerList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, options));

        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
    }/*  w ww  .  j a va  2s .  c  o m*/

}

From source file:com.mifos.mifosxdroid.online.LoanAccountFragment.java

private void inflatetransactionProcessingStrategySpinner() {
    showProgress(true);/*from  w ww  .  j a v  a  2s .co m*/
    App.apiManager.getLoansAccountTemplate(clientId, productId, new Callback<Response>() {
        @Override

        public void success(final Response result, Response response) {
            /* Activity is null - Fragment has been detached; no need to do anything. */
            if (getActivity() == null)
                return;

            Log.d(LOG_TAG, "");

            final List<TransactionProcessingStrategy> transactionProcessingStrategyType = new ArrayList<>();
            // you can use this array to populate your spinner
            final ArrayList<String> transactionProcessingStrategyTypeNames = new ArrayList<String>();
            //Try to get response body
            BufferedReader reader = null;
            StringBuilder sb = new StringBuilder();
            try {
                reader = new BufferedReader(new InputStreamReader(result.getBody().in()));
                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
                JSONObject obj = new JSONObject(sb.toString());
                if (obj.has("transactionProcessingStrategyOptions")) {
                    JSONArray transactionProcessingStrategyTypes = obj
                            .getJSONArray("transactionProcessingStrategyOptions");
                    for (int i = 0; i < transactionProcessingStrategyTypes.length(); i++) {
                        JSONObject transactionProcessingStrategyTypeObject = transactionProcessingStrategyTypes
                                .getJSONObject(i);
                        TransactionProcessingStrategy transactionProcessingStrategy = new TransactionProcessingStrategy();
                        transactionProcessingStrategy
                                .setId(transactionProcessingStrategyTypeObject.optInt("id"));
                        transactionProcessingStrategy
                                .setName(transactionProcessingStrategyTypeObject.optString("name"));
                        transactionProcessingStrategyType.add(transactionProcessingStrategy);
                        transactionProcessingStrategyTypeNames
                                .add(transactionProcessingStrategyTypeObject.optString("name"));
                        transactionProcessingStrategyTypeIdHashMap.put(transactionProcessingStrategy.getName(),
                                transactionProcessingStrategy.getId());
                    }

                }
                String stringResult = sb.toString();
            } catch (Exception e) {
                Log.e(LOG_TAG, "", e);
            }
            final ArrayAdapter<String> transactionProcessingStrategyAdapter = new ArrayAdapter<>(getActivity(),
                    layout.simple_spinner_item, transactionProcessingStrategyTypeNames);
            transactionProcessingStrategyAdapter.setDropDownViewResource(layout.simple_spinner_dropdown_item);
            sp_repaymentstrategy.setAdapter(transactionProcessingStrategyAdapter);
            sp_repaymentstrategy.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                    transactionProcessingStrategyId = transactionProcessingStrategyTypeIdHashMap
                            .get(transactionProcessingStrategyTypeNames.get(i));
                    Log.d("transactionProcessing " + transactionProcessingStrategyTypeNames.get(i),
                            String.valueOf(transactionProcessingStrategyId));
                    if (transactionProcessingStrategyId != -1) {

                    } else {

                        Toast.makeText(getActivity(),
                                getString(R.string.error_select_transactionProcessingStrategy),
                                Toast.LENGTH_SHORT).show();

                    }

                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });

            showProgress(false);

        }

        @Override
        public void failure(RetrofitError retrofitError) {

            Log.d(LOG_TAG, retrofitError.getLocalizedMessage());

            showProgress(false);
        }
    });
}

From source file:com.cssweb.android.trade.stock.StockTrading.java

protected void handlerData() {
    try {/*from  w ww  . java 2  s. c  om*/
        String res = TradeUtil.checkResult(quoteData);
        if (res != null) {
            if (res.equals("-1")) {
                toast("??");
            } else if ("stock not found".equals(res)) {
                toast("????");
            } else {
                toast(res);
            }
            clear();
            hiddenProgress();
            return;
        }

        JSONArray jarr = quoteData.getJSONArray("item");
        JSONObject jA = (JSONObject) jarr.get(0);
        if (jA == null) {
            return;
        }

        stkname.setText(jA.getString("zqjc"));
        //         zjcj = jA.getString("zjcj");
        String zqlb = jA.getString("zqlb");
        zqlb = zqlb.substring(0, zqlb.indexOf("."));
        lblNumberUnit.setText(NameRule.getStockUnit(zqlb));
        priceFormatNum = NameRule.getStockFormatNum(zqlb);

        market = NameRule.getMarketFromZqlb(jA.getString("zqlb"), jA.getString("zqdm"));

        String[] arrayOfString = null;

        this.exchange = NameRule.getExchange(String.valueOf(market));
        this.stockcode = jA.getString("zqdm");
        this.stockname = jA.getString("zqjc");
        JSONObject stockAccountData = null;
        JSONArray jsonArr = null;
        String filedate = ActivityUtil.getPreference(StockTrading.this, "openholdersListDate", "");
        if (!(filedate).equals(DateTool.getToday())) { //?????
            stockAccountData = ConnPool.sendReq("GET_STOCKACCOUNT", "304001", "");
        } else {
            String jsonObject = CssIniFile.loadIni(StockTrading.this, 9, "ShareholdersList");
            if (null != jsonObject && !jsonObject.equals("")) {
                stockAccountData = new JSONObject(jsonObject);
            }
        }
        res = TradeUtil.checkResult(stockAccountData);
        if (res == null) {
            jsonArr = (JSONArray) stockAccountData.getJSONArray("item");
        }
        //??
        for (int i = 0, size = jsonArr.length() - 1; i < size; i++) {
            JSONObject jsonObj = (JSONObject) jsonArr.get(i);
            if (jsonObj.getString("FID_JYS").equals(market)) {
                stockHolder.setSelection(i);
            }
        }
        if (TradeUtil.MARKET_SHB.equals(market) || TradeUtil.MARKET_SZB.equals(market)) {
            arrayOfString = getResources().getStringArray(R.array.other_market_bs_methods);
            quoteMethodVal = getResources().getStringArray(R.array.other_market_bs_methods_val);
        } else if (TradeUtil.MARKET_SHA.equals(market)) {
            arrayOfString = getResources().getStringArray(R.array.sh_market_bs_methods);
            quoteMethodVal = getResources().getStringArray(R.array.sh_market_buy_methods_val);
        } else if (TradeUtil.MARKET_SZA.equals(market)) {
            arrayOfString = getResources().getStringArray(R.array.sz_market_bs_methods);
            quoteMethodVal = getResources().getStringArray(R.array.sz_market_bs_methods_val);
        }
        queryMethodAdapter = new ArrayAdapter<String>(StockTrading.this, android.R.layout.simple_spinner_item,
                arrayOfString);
        queryMethodAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        queryMethod.setAdapter(queryMethodAdapter);
        if (type == 1) {//?
            if (!"0.0".equals(jA.getString("bjw1"))) {
                price.setText(TradeUtil.formatNum(jA.getString("bjw1"), priceFormatNum));
            } else if (!"0.0".equals(jA.getString("zjcj"))) {
                price.setText(TradeUtil.formatNum(jA.getString("zjcj"), priceFormatNum));
            } else {
                price.setText(TradeUtil.formatNum(jA.getString("zrsp"), priceFormatNum));
            }
            number.setText("0");

            StringBuffer sb = new StringBuffer();
            sb.append("FID_GDH=" + holder.get(stockHolder.getSelectedItemPosition()) + TradeUtil.SPLIT);
            sb.append("FID_ZQDM=" + stkcode.getText().toString().trim() + TradeUtil.SPLIT);
            sb.append("FID_EXFLG=1" + TradeUtil.SPLIT);
            JSONObject tradeData = ConnPool.sendReq("GET_STOCK_POSITION", "304101", sb.toString());
            res = TradeUtil.checkResult(tradeData);
            if (res != null) {
                if (res.equals("-1")) {
                    Toast.makeText(StockTrading.this,
                            "???", Toast.LENGTH_LONG)
                            .show();
                    //openDialog(R.string.network_error);
                } else {
                    Toast.makeText(StockTrading.this, res, Toast.LENGTH_LONG).show();
                }
                hiddenProgress();
                return;
            } else {
                JSONArray jArr = (JSONArray) tradeData.getJSONArray("item");
                if (jArr.length() > 0) {
                    JSONObject j = (JSONObject) jArr.get(0);
                    number.setText(j.getString("FID_KMCSL"));
                }
            }
        } else {
            if ("1".equals(jA.getString("xgsg")) && !"0.0".equals(jA.getString("zrsp"))) {
                price.setText(TradeUtil.formatNum(jA.getString("zrsp"), priceFormatNum));
            } else if (!"0.0".equals(jA.getString("sjw1"))) {
                price.setText(TradeUtil.formatNum(jA.getString("sjw1"), priceFormatNum));
            } else if (!"0.0".equals(jA.getString("zjcj"))) {
                price.setText(TradeUtil.formatNum(jA.getString("zjcj"), priceFormatNum));
            } else {
                price.setText(TradeUtil.formatNum(jA.getString("zrsp"), priceFormatNum));
            }
            JSONObject maxQtyJson = null;
            String orderType = "";
            //?
            String maxQty = "0";
            if (queryMethod.getSelectedItemPosition() != 0) {
                orderType = quoteMethodVal[queryMethod.getSelectedItemPosition()];
            }
            maxQtyJson = TradeService.getMaxQtyBuy(market, holder.get(stockHolder.getSelectedItemPosition()),
                    stkcode.getText().toString().trim(), "1", price.getText().toString().trim(), orderType);
            String resmaxQtyJson = TradeUtil.checkResult(maxQtyJson);
            if (resmaxQtyJson != null) {
                if (resmaxQtyJson.equals("-1")) {
                    Toast.makeText(StockTrading.this,
                            "???", Toast.LENGTH_LONG)
                            .show();
                } else {
                    toast(resmaxQtyJson);
                }
                number.setText("0");
                hiddenProgress();
                return;
            }
            JSONArray maxQtyjArr = maxQtyJson.getJSONArray("item");
            if (maxQtyjArr.length() > 0) {
                JSONObject maxQtyjA = (JSONObject) maxQtyjArr.get(0);
                maxQty = maxQtyjA.getString("FID_WTSL");
            }
            number.setText(maxQty);
            //?
            TradeUtil.getFundavl();
            if (TradeUtil.MARKET_SHB.equals(market) || TradeUtil.MARKET_TU.equals(market))
                avaiAsset.setText(TradeUser.getInstance().getEnablefundavlUS());
            else if (TradeUtil.MARKET_SZB.equals(market))
                avaiAsset.setText(TradeUser.getInstance().getEnablefundavlHK());
            else
                avaiAsset.setText(TradeUser.getInstance().getEnablefundavlRMB());
        }

        //???         

        List<String> list = TradeUser.getInstance().getHolderBak();

        for (int i = 0; i < list.size(); i++) {
            String st = (String) list.get(i);
            String key = st.split("-")[0];
            if (key.equals(market)) {
                stockHolder.setSelection(i);
                break;
            }
        }
        //initFivePrive(jA);

        initView(this.exchange, this.stockcode, this.stockname);
    } catch (JSONException e) {
        e.printStackTrace();
        CssLog.e(TAG, e.toString());
    }
    //hiddenProgress();
}

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

/**
 * Auto discovery servers and add them in a list view.
 * Click a list item and make it as current server.
 * /*from w w w  .  java 2 s  . c om*/
 * @return the list view
 */
private ListView constructAutoServersView() {
    final ListView lv = new ListView(this);
    lv.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 200));
    lv.setPadding(20, 5, 5, 10);
    lv.setBackgroundColor(0);
    lv.setCacheColorHint(0);
    lv.setItemsCanFocus(true);
    lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    final ArrayAdapter<String> serverListAdapter = new ArrayAdapter<String>(appSettingsView.getContext(),
            R.layout.server_list_item, new ArrayList<String>());
    lv.setAdapter(serverListAdapter);

    new IPAutoDiscoveryServer() {
        @Override
        protected void onProgressUpdate(Void... values) {
            if (progressLayout != null) {
                progressLayout.setVisibility(View.VISIBLE);
            }
        }

        @Override
        protected void onPostExecute(List<String> result) {
            int length = result.size();
            for (int i = 0; i < length; i++) {
                serverListAdapter.add(result.get(i));
            }
            if (length > 0) {
                lv.setItemChecked(0, true);
                currentServer = serverListAdapter.getItem(0);
                AppSettingsModel.setCurrentServer(AppSettingsActivity.this, currentServer);
            }
            if (progressLayout != null) {
                progressLayout.setVisibility(View.INVISIBLE);
            }
            requestPanelList();
            checkAuthentication();
            requestAccess();
        }
    }.execute((Void) null);

    lv.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);
            requestPanelList();
            checkAuthentication();
            requestAccess();
        }
    });

    return lv;
}

From source file:com.mifos.mifosxdroid.online.GroupLoanAccountFragment.java

private void inflateFrequencyPeriodSpinner() {
    showProgress(true);/*w w w .j a v a2  s  . c om*/
    App.apiManager.getGroupLoansAccountTemplate(groupId, productId, new Callback<Response>() {
        @Override
        public void success(final Response result, Response response) {
            /* Activity is null - Fragment has been detached; no need to do anything. */
            if (getActivity() == null)
                return;

            Log.d(LOG_TAG, "");

            final List<TermFrequencyTypeOptions> termFrequencyType = new ArrayList<>();
            // you can use this array to populate your spinner
            final ArrayList<String> termFrequencyTypeNames = new ArrayList<String>();
            //Try to get response body
            BufferedReader reader = null;
            StringBuilder sb = new StringBuilder();
            try {
                reader = new BufferedReader(new InputStreamReader(result.getBody().in()));
                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
                JSONObject obj = new JSONObject(sb.toString());
                if (obj.has("termFrequencyTypeOptions")) {
                    JSONArray termFrequencyTypes = obj.getJSONArray("termFrequencyTypeOptions");
                    for (int i = 0; i < termFrequencyTypes.length(); i++) {
                        JSONObject termFrequencyTypeObject = termFrequencyTypes.getJSONObject(i);
                        TermFrequencyTypeOptions termFrequency = new TermFrequencyTypeOptions();
                        termFrequency.setId(termFrequencyTypeObject.optInt("id"));
                        termFrequency.setValue(termFrequencyTypeObject.optString("value"));
                        termFrequencyType.add(termFrequency);
                        termFrequencyTypeNames.add(termFrequencyTypeObject.optString("value"));
                        termFrequencyTypeIdHashMap.put(termFrequency.getValue(), termFrequency.getId());
                    }

                }
                String stringResult = sb.toString();
            } catch (Exception e) {
                Log.e(LOG_TAG, "", e);
            }
            final ArrayAdapter<String> termFrequencyTypeAdapter = new ArrayAdapter<>(getActivity(),
                    layout.simple_spinner_item, termFrequencyTypeNames);
            termFrequencyTypeAdapter.setDropDownViewResource(layout.simple_spinner_dropdown_item);
            sp_payment_periods.setAdapter(termFrequencyTypeAdapter);
            sp_payment_periods.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {

                    loanTermFrequency = termFrequencyTypeIdHashMap.get(termFrequencyTypeNames.get(i));
                    Log.d("termFrequencyTypeId" + termFrequencyTypeNames.get(i),
                            String.valueOf(loanTermFrequency));
                    if (loanTermFrequency != -1) {

                    } else {

                        Toast.makeText(getActivity(), getString(R.string.error_select_fund), Toast.LENGTH_SHORT)
                                .show();

                    }

                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });

            showProgress(false);

        }

        @Override
        public void failure(RetrofitError retrofitError) {

            Log.d(LOG_TAG, retrofitError.getLocalizedMessage());

            showProgress(false);
        }
    });
}