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:fiskinfoo.no.sintef.fiskinfoo.MapFragment.java

private void createSearchDialog() {
    final Dialog dialog = dialogInterface.getDialog(getActivity(), R.layout.dialog_search_tools,
            R.string.search_tools_title);

    final ScrollView scrollView = (ScrollView) dialog.findViewById(R.id.search_tools_dialog_scroll_view);
    final AutoCompleteTextView inputField = (AutoCompleteTextView) dialog
            .findViewById(R.id.search_tools_input_field);
    final LinearLayout rowsContainer = (LinearLayout) dialog.findViewById(R.id.search_tools_row_container);
    final Button viewInMapButton = (Button) dialog.findViewById(R.id.search_tools_view_in_map_button);
    final Button jumpToBottomButton = (Button) dialog.findViewById(R.id.search_tools_jump_to_bottom_button);
    Button dismissButton = (Button) dialog.findViewById(R.id.search_tools_dismiss_button);

    List<PropertyDescription> subscribables;
    PropertyDescription newestSubscribable = null;
    final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss",
            Locale.getDefault());
    Date cachedUpdateDateTime;/*from  www.j  av a  2s.c  om*/
    Date newestUpdateDateTime;
    SubscriptionEntry cachedEntry;
    Response response;
    final JSONArray toolsArray;
    ArrayAdapter<String> adapter;
    String format = "JSON";
    String downloadPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
            .toString() + "/FiskInfo/Offline/";
    final JSONObject tools;
    final List<String> vesselNames;
    final Map<String, List<Integer>> toolIdMap = new HashMap<>();
    byte[] data = new byte[0];

    cachedEntry = user.getSubscriptionCacheEntry(getString(R.string.fishing_facility_api_name));

    if (fiskInfoUtility.isNetworkAvailable(getActivity())) {
        subscribables = barentswatchApi.getApi().getSubscribable();
        for (PropertyDescription subscribable : subscribables) {
            if (subscribable.ApiName.equals(getString(R.string.fishing_facility_api_name))) {
                newestSubscribable = subscribable;
                break;
            }
        }
    } else if (cachedEntry == null) {
        Dialog infoDialog = dialogInterface.getAlertDialog(getActivity(), R.string.tools_search_no_data_title,
                R.string.tools_search_no_data, -1);

        infoDialog.show();
        return;
    }

    if (cachedEntry != null) {
        try {
            cachedUpdateDateTime = simpleDateFormat
                    .parse(cachedEntry.mLastUpdated.equals(getActivity().getString(R.string.abbreviation_na))
                            ? "2000-00-00T00:00:00"
                            : cachedEntry.mLastUpdated);
            newestUpdateDateTime = simpleDateFormat
                    .parse(newestSubscribable != null ? newestSubscribable.LastUpdated : "2000-00-00T00:00:00");

            if (cachedUpdateDateTime.getTime() - newestUpdateDateTime.getTime() < 0) {
                response = barentswatchApi.getApi().geoDataDownload(newestSubscribable.ApiName, format);
                try {
                    data = FiskInfoUtility.toByteArray(response.getBody().in());
                } catch (IOException e) {
                    e.printStackTrace();
                }

                if (new FiskInfoUtility().writeMapLayerToExternalStorage(getActivity(), data,
                        newestSubscribable.Name.replace(",", "").replace(" ", "_"), format, downloadPath,
                        false)) {
                    SubscriptionEntry entry = new SubscriptionEntry(newestSubscribable, true);
                    entry.mLastUpdated = newestSubscribable.LastUpdated;
                    user.setSubscriptionCacheEntry(newestSubscribable.ApiName, entry);
                    user.writeToSharedPref(getActivity());
                }
            } else {
                String directoryFilePath = Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()
                        + "/FiskInfo/Offline/";

                File file = new File(directoryFilePath + newestSubscribable.Name + ".JSON");
                StringBuilder jsonString = new StringBuilder();
                BufferedReader bufferReader = null;

                try {
                    bufferReader = new BufferedReader(new FileReader(file));
                    String line;

                    while ((line = bufferReader.readLine()) != null) {
                        jsonString.append(line);
                        jsonString.append('\n');
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (bufferReader != null) {
                        try {
                            bufferReader.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

                data = jsonString.toString().getBytes();
            }

        } catch (ParseException e) {
            e.printStackTrace();
            Log.e(TAG, "Invalid datetime provided");
        }
    } else {
        response = barentswatchApi.getApi().geoDataDownload(newestSubscribable.ApiName, format);
        try {
            data = FiskInfoUtility.toByteArray(response.getBody().in());
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (new FiskInfoUtility().writeMapLayerToExternalStorage(getActivity(), data,
                newestSubscribable.Name.replace(",", "").replace(" ", "_"), format, downloadPath, false)) {
            SubscriptionEntry entry = new SubscriptionEntry(newestSubscribable, true);
            entry.mLastUpdated = newestSubscribable.LastUpdated;
            user.setSubscriptionCacheEntry(newestSubscribable.ApiName, entry);
        }
    }

    try {
        tools = new JSONObject(new String(data));
        toolsArray = tools.getJSONArray("features");
        vesselNames = new ArrayList<>();
        adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_dropdown_item_1line, vesselNames);

        for (int i = 0; i < toolsArray.length(); i++) {
            JSONObject feature = toolsArray.getJSONObject(i);
            String vesselName = (feature.getJSONObject("properties").getString("vesselname") != null
                    && !feature.getJSONObject("properties").getString("vesselname").equals("null"))
                            ? feature.getJSONObject("properties").getString("vesselname")
                            : getString(R.string.vessel_name_unknown);
            List<Integer> toolsIdList = toolIdMap.get(vesselName) != null ? toolIdMap.get(vesselName)
                    : new ArrayList<Integer>();

            if (vesselName != null && !vesselNames.contains(vesselName)) {
                vesselNames.add(vesselName);
            }

            toolsIdList.add(i);
            toolIdMap.put(vesselName, toolsIdList);
        }

        inputField.setAdapter(adapter);
    } catch (JSONException e) {
        dialogInterface.getAlertDialog(getActivity(), R.string.search_tools_init_error,
                R.string.search_tools_init_info, -1).show();
        Log.e(TAG, "JSON parse error");
        e.printStackTrace();

        return;
    }

    if (searchToolsButton.getTag() != null) {
        inputField.requestFocus();
        inputField.setText(searchToolsButton.getTag().toString());
        inputField.selectAll();
    }

    inputField.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String selectedVesselName = ((TextView) view).getText().toString();
            List<Integer> selectedTools = toolIdMap.get(selectedVesselName);
            Gson gson = new Gson();
            String toolSetDateString;
            Date toolSetDate;

            rowsContainer.removeAllViews();

            for (int toolId : selectedTools) {
                JSONObject feature;
                Feature toolFeature;

                try {
                    feature = toolsArray.getJSONObject(toolId);

                    if (feature.getJSONObject("geometry").getString("type").equals("LineString")) {
                        toolFeature = gson.fromJson(feature.toString(), LineFeature.class);
                    } else {
                        toolFeature = gson.fromJson(feature.toString(), PointFeature.class);
                    }

                    toolSetDateString = toolFeature.properties.setupdatetime != null
                            ? toolFeature.properties.setupdatetime
                            : "2038-00-00T00:00:00";
                    toolSetDate = simpleDateFormat.parse(toolSetDateString);

                } catch (JSONException | ParseException e) {
                    dialogInterface.getAlertDialog(getActivity(), R.string.search_tools_init_error,
                            R.string.search_tools_init_info, -1).show();
                    e.printStackTrace();

                    return;
                }

                ToolSearchResultRow row = rowsInterface.getToolSearchResultRow(getActivity(),
                        R.drawable.ikon_kystfiske, toolFeature);
                long toolTime = System.currentTimeMillis() - toolSetDate.getTime();
                long highlightCutoff = ((long) getResources().getInteger(R.integer.milliseconds_in_a_day))
                        * ((long) getResources().getInteger(R.integer.days_to_highlight_active_tool));

                if (toolTime > highlightCutoff) {
                    int colorId = ContextCompat.getColor(getActivity(), R.color.error_red);
                    row.setDateTextViewTextColor(colorId);
                }

                rowsContainer.addView(row.getView());
            }

            viewInMapButton.setEnabled(true);
            inputField.setTag(selectedVesselName);
            searchToolsButton.setTag(selectedVesselName);
            jumpToBottomButton.setVisibility(View.VISIBLE);
            jumpToBottomButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    new Handler().post(new Runnable() {
                        @Override
                        public void run() {
                            scrollView.scrollTo(0, rowsContainer.getBottom());
                        }
                    });
                }
            });

        }
    });

    viewInMapButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String vesselName = inputField.getTag().toString();
            highlightToolsInMap(vesselName);

            dialog.dismiss();
        }
    });

    dismissButton.setOnClickListener(onClickListenerInterface.getDismissDialogListener(dialog));
    dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
    dialog.show();
}

From source file:com.piusvelte.taplock.client.core.TapLockSettings.java

@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
    if (key.equals(KEY_DEVICES)) {
        mDevices.clear();/*  w  w w .j a v  a 2s  . c o  m*/
        Set<String> devices = sharedPreferences.getStringSet(KEY_DEVICES, null);
        if (devices != null) {
            for (String device : devices) {
                try {
                    mDevices.add(new JSONObject(device));
                } catch (JSONException e) {
                    Log.e(TAG, e.toString());
                }
            }
        }
        String[] deviceNames = TapLock.getDeviceNames(mDevices);
        setListAdapter(new ArrayAdapter<String>(TapLockSettings.this, android.R.layout.simple_list_item_1,
                deviceNames));
    }
}

From source file:com.piusvelte.taplock.client.core.TapLockSettings.java

private void storeDevices() {
    TapLock.storeDevices(this, getSharedPreferences(KEY_PREFS, MODE_PRIVATE), mDevices);
    String[] deviceNames = TapLock.getDeviceNames(mDevices);
    setListAdapter(//from w  w w  . java 2  s .  c o m
            new ArrayAdapter<String>(TapLockSettings.this, android.R.layout.simple_list_item_1, deviceNames));
}

From source file:com.vkassin.mtrade.Common.java

public static void putOrder(final Context ctx, Quote quote) {

    final Instrument it = Common.selectedInstrument;// adapter.getItem(selectedRowId);

    final Dialog dialog = new Dialog(ctx);
    dialog.setContentView(R.layout.order_dialog);
    dialog.setTitle(R.string.OrderDialogTitle);

    datetxt = (EditText) dialog.findViewById(R.id.expdateedit);
    SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
    Date dat1 = new Date();
    datetxt.setText(sdf.format(dat1));//from   www.  java2s .c o m
    mYear = dat1.getYear() + 1900;
    mMonth = dat1.getMonth();
    mDay = dat1.getDate();
    final Date dat = new GregorianCalendar(mYear, mMonth, mDay).getTime();

    datetxt.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Log.i(TAG, "Show DatePickerDialog");
            DatePickerDialog dpd = new DatePickerDialog(ctx, mDateSetListener, mYear, mMonth, mDay);
            dpd.show();
        }
    });

    TextView itext = (TextView) dialog.findViewById(R.id.instrtext);
    itext.setText(it.symbol);

    final Spinner aspinner = (Spinner) dialog.findViewById(R.id.acc_spinner);
    List<String> list = new ArrayList<String>(Common.getAccountList());
    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(Common.app_ctx,
            android.R.layout.simple_spinner_item, list);
    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
    aspinner.setAdapter(dataAdapter);

    final EditText pricetxt = (EditText) dialog.findViewById(R.id.priceedit);
    final EditText quanttxt = (EditText) dialog.findViewById(R.id.quantedit);

    final Button buttonpm = (Button) dialog.findViewById(R.id.buttonPriceMinus);
    buttonpm.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            try {

                double price = Double.valueOf(pricetxt.getText().toString());
                price -= 0.01;
                if (price < 0)
                    price = 0;
                pricetxt.setText(twoDForm.format(price));

            } catch (Exception e) {

                Toast.makeText(ctx, R.string.CorrectPrice, Toast.LENGTH_SHORT).show();
            }
        }
    });

    final Button buttonpp = (Button) dialog.findViewById(R.id.buttonPricePlus);
    buttonpp.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            try {

                double price = Double.valueOf(pricetxt.getText().toString());
                price += 0.01;
                pricetxt.setText(twoDForm.format(price));

            } catch (Exception e) {

                Toast.makeText(ctx, R.string.CorrectPrice, Toast.LENGTH_SHORT).show();
            }
        }
    });

    final Button buttonqm = (Button) dialog.findViewById(R.id.buttonQtyMinus);
    buttonqm.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            try {

                long qty = Long.valueOf(quanttxt.getText().toString());
                qty -= 1;
                if (qty < 0)
                    qty = 0;
                quanttxt.setText(String.valueOf(qty));

            } catch (Exception e) {

                Toast.makeText(ctx, R.string.CorrectQty, Toast.LENGTH_SHORT).show();
            }
        }
    });

    final Button buttonqp = (Button) dialog.findViewById(R.id.buttonQtyPlus);
    buttonqp.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            try {

                long qty = Long.valueOf(quanttxt.getText().toString());
                qty += 1;
                quanttxt.setText(String.valueOf(qty));

            } catch (Exception e) {

                Toast.makeText(ctx, R.string.CorrectQty, Toast.LENGTH_SHORT).show();
            }
        }
    });

    final RadioButton bu0 = (RadioButton) dialog.findViewById(R.id.radio0);
    final RadioButton bu1 = (RadioButton) dialog.findViewById(R.id.radio1);

    if (quote != null) {

        // pricetxt.setText(quote.price.toString());
        pricetxt.setText(quote.getPriceS());
        if (quote.qtyBuy > 0) {

            quanttxt.setText(quote.qtyBuy.toString());
            bu1.setChecked(true);
            bu0.setChecked(false);

        } else {

            quanttxt.setText(quote.qtySell.toString());
            bu1.setChecked(false);
            bu0.setChecked(true);

        }
    }

    Button customDialog_Cancel = (Button) dialog.findViewById(R.id.cancelbutt);
    customDialog_Cancel.setOnClickListener(new Button.OnClickListener() {
        public void onClick(View arg0) {

            dialog.dismiss();
        }

    });

    Button customDialog_Put = (Button) dialog.findViewById(R.id.putorder);
    customDialog_Put.setOnClickListener(new Button.OnClickListener() {
        public void onClick(View arg0) {

            Double price = new Double(0);
            Long qval = new Long(0);

            try {

                price = Double.valueOf(pricetxt.getText().toString());
            } catch (Exception e) {

                Toast.makeText(ctx, R.string.CorrectPrice, Toast.LENGTH_SHORT).show();
                return;
            }
            try {

                qval = Long.valueOf(quanttxt.getText().toString());
            } catch (Exception e) {

                Toast.makeText(ctx, R.string.CorrectQty, Toast.LENGTH_SHORT).show();
                return;
            }

            if (dat.compareTo(new GregorianCalendar(mYear, mMonth, mDay).getTime()) > 0) {

                Toast.makeText(ctx, R.string.CorrectDate, Toast.LENGTH_SHORT).show();

                return;

            }

            JSONObject msg = new JSONObject();
            try {

                msg.put("objType", Common.CREATE_REMOVE_ORDER);
                msg.put("time", Calendar.getInstance().getTimeInMillis());
                msg.put("version", Common.PROTOCOL_VERSION);
                msg.put("device", "Android");
                msg.put("instrumId", Long.valueOf(it.id));
                msg.put("price", price);
                msg.put("qty", qval);
                msg.put("ordType", 1);
                msg.put("side", bu0.isChecked() ? 0 : 1);
                msg.put("code", String.valueOf(aspinner.getSelectedItem()));
                msg.put("orderNum", ++ordernum);
                msg.put("action", "CREATE");
                boolean b = (((mYear - 1900) == dat.getYear()) && (mMonth == dat.getMonth())
                        && (mDay == dat.getDate()));
                if (!b)
                    msg.put("expired", String.format("%02d.%02d.%04d", mDay, mMonth + 1, mYear));

                if (isSSL) {

                    //                ? ?:    newOrder-orderNum-instrumId-side-price-qty-code-ordType
                    //               :                  newOrder-16807-20594623-0-1150-13-1027700451-1
                    String forsign = "newOrder-" + ordernum + "-" + msg.getString("instrumId") + "-"
                            + msg.getString("side") + "-"
                            + JSONObject.numberToString(Double.valueOf(msg.getDouble("price"))) + "-"
                            + msg.getString("qty") + "-" + msg.getString("code") + "-"
                            + msg.getString("ordType");
                    byte[] signed = Common.signText(Common.signProfile, forsign.getBytes(), true);
                    String gsign = Base64.encodeToString(signed, Base64.DEFAULT);
                    msg.put("gostSign", gsign);
                }
                mainActivity.writeJSONMsg(msg);

            } catch (Exception e) {

                e.printStackTrace();
                Log.e(TAG, "Error! Cannot create JSON order object", e);
            }

            dialog.dismiss();
        }

    });

    dialog.show();

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

}

From source file:com.entertailion.android.launcher.Dialogs.java

/**
 * Display dialog to allow user to select which row to add the shortcut. For
 * TV channels let the user change the channel name.
 * //from w  ww .j a va  2 s  . c  o  m
 * @see InstallShortcutReceiver
 * 
 * @param context
 * @param name
 * @param icon
 * @param uri
 */
public static void displayShortcutsRowSelection(final Launcher context, final String name, final String icon,
        final String uri) {
    if (uri == null) {
        return;
    }
    final Dialog dialog = new Dialog(context);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    final boolean isChannel = uri.startsWith("tv");
    dialog.setContentView(R.layout.select_row);

    final TextView channelTextView = (TextView) dialog.findViewById(R.id.channelText);
    final EditText channelNameEditText = (EditText) dialog.findViewById(R.id.channelName);
    if (isChannel) {
        channelTextView.setVisibility(View.VISIBLE);
        channelNameEditText.setVisibility(View.VISIBLE);
        channelNameEditText.setText(name);
    }

    final TextView selectTextView = (TextView) dialog.findViewById(R.id.selectText);
    selectTextView.setText(context.getString(R.string.dialog_select_row, name));

    final Spinner spinner = (Spinner) dialog.findViewById(R.id.spinner);

    final EditText nameEditText = (EditText) dialog.findViewById(R.id.rowName);
    final RadioButton currentRadioButton = (RadioButton) dialog.findViewById(R.id.currentRadio);
    currentRadioButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // hide the row name edit field if the current row radio button
            // is selected
            nameEditText.setVisibility(View.GONE);
            spinner.setVisibility(View.VISIBLE);
        }

    });
    final RadioButton newRadioButton = (RadioButton) dialog.findViewById(R.id.newRadio);
    newRadioButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // show the row name edit field if the new radio button is
            // selected
            nameEditText.setVisibility(View.VISIBLE);
            nameEditText.requestFocus();
            spinner.setVisibility(View.GONE);
        }

    });

    List<String> list = new ArrayList<String>();
    final ArrayList<RowInfo> rows = RowsTable.getRows(context);
    if (rows != null) {
        for (RowInfo row : rows) {
            list.add(row.getTitle());
        }
    }
    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(context, R.layout.simple_spinner_item, list);
    dataAdapter.setDropDownViewResource(R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(dataAdapter);

    Button buttonYes = (Button) dialog.findViewById(R.id.buttonOk);
    buttonYes.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            String shortcutName = name;
            try {
                if (isChannel) {
                    String channelName = channelNameEditText.getText().toString().trim();
                    if (channelName.length() == 0) {
                        channelNameEditText.requestFocus();
                        displayAlert(context, context.getString(R.string.dialog_channel_name_alert));
                        return;
                    }
                    shortcutName = channelName;
                }
                // if the new row radio button is selected, the user must
                // enter a name for the new row
                String rowName = nameEditText.getText().toString().trim();
                if (newRadioButton.isChecked() && rowName.length() == 0) {
                    nameEditText.requestFocus();
                    displayAlert(context, context.getString(R.string.dialog_new_row_name_alert));
                    return;
                }
                boolean currentRow = !newRadioButton.isChecked();
                int rowId = 0;
                int rowPosition = 0;
                if (currentRow) {
                    if (rows != null) {
                        String selectedRow = (String) spinner.getSelectedItem();
                        for (RowInfo row : rows) {
                            if (row.getTitle().equals(selectedRow)) {
                                rowId = row.getId();
                                ArrayList<ItemInfo> items = ItemsTable.getItems(context, rowId);
                                rowPosition = items.size(); // in last
                                // position
                                // for selected
                                // row
                                break;
                            }
                        }
                    }
                } else {
                    rowId = (int) RowsTable.insertRow(context, rowName, 0, RowInfo.FAVORITE_TYPE);
                    rowPosition = 0;
                }

                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(uri));
                ItemsTable.insertItem(context, rowId, rowPosition, shortcutName, intent, icon,
                        DatabaseHelper.SHORTCUT_TYPE);
                Toast.makeText(context, context.getString(R.string.shortcut_installed, shortcutName),
                        Toast.LENGTH_SHORT).show();
                context.reloadAllGalleries();

                if (currentRow) {
                    Analytics.logEvent(Analytics.ADD_SHORTCUT);
                } else {
                    Analytics.logEvent(Analytics.ADD_SHORTCUT_WITH_ROW);
                }

            } catch (Exception e) {
                Log.d(LOG_TAG, "onClick", e);
            }

            context.showCover(false);
            dialog.dismiss();
        }

    });
    Button buttonNo = (Button) dialog.findViewById(R.id.buttonCancel);
    buttonNo.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            context.showCover(false);
            dialog.dismiss();
        }

    });
    dialog.setOnDismissListener(new OnDismissListener() {

        @Override
        public void onDismiss(DialogInterface dialog) {
            context.showCover(false);
        }

    });
    context.showCover(true);
    dialog.show();
    Analytics.logEvent(Analytics.DIALOG_ADD_SHORTCUT);
}

From source file:foam.jellyfish.StarwispBuilder.java

public void Update(final StarwispActivity ctx, final String ctxname, JSONArray arr) {
    try {/*from  ww  w  . j a va2s .  co m*/

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

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

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

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

            ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);

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

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

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

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

            dialog.setContentView(inner);

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

            dialog.show();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            final String name = arr.getString(3);

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

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

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

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

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

            return;
        }

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

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

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

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

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

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

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

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

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

        if (type.equals("button-grid")) {
            Log.i("starwisp", "button-grid update");
            LinearLayout horiz = (LinearLayout) vv;
            if (token.equals("grid-buttons")) {
                Log.i("starwisp", "button-grid contents");
                horiz.removeAllViews();

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

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

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

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

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

                }
            }
        }

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

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

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

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

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

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

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

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

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

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

        /*
                    if (type.equals("canvas")) {
        StarwispCanvas v = (StarwispCanvas)vv;
        if (token.equals("drawlist")) {
            v.SetDrawList(arr.getJSONArray(3));
        }
        return;
                    }
                
                    if (type.equals("camera-preview")) {
        final CameraPreview v = (CameraPreview)vv;
                
        if (token.equals("take-picture")) {
            final String path = ((StarwispActivity)ctx).m_AppDir+arr.getString(3);
                
            v.TakePicture(
                new PictureCallback() {
                    public void onPictureTaken(byte[] data, Camera camera) {
                        String datetime = getDateTime();
                        String filename = path+datetime + ".jpg";
                        SaveData(filename,data);
                        v.Shutdown();
                        ctx.finish();
                    }
                });
        }
                
        if (token.equals("shutdown")) {
            v.Shutdown();
        }
                
        return;
                    }
        */
        if (type.equals("seek-bar")) {
            SeekBar v = new SeekBar(ctx);
            if (token.equals("max")) {
                // android seekbar bug workaround
                int p = v.getProgress();
                v.setMax(0);
                v.setProgress(0);
                v.setMax(arr.getInt(3));
                v.setProgress(1000);

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

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

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

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

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

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

                v.setAdapter(spinnerArrayAdapter);

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

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

            }
            return;
        }

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

From source file:com.df.dfcarchecker.CarCheck.CarCheckBasicInfoFragment.java

private void setCountrySpinner(final VehicleModel vehicleModel) {
    ArrayAdapter<String> adapter;

    if (vehicleModel == null) {
        adapter = new ArrayAdapter<String>(rootView.getContext(), android.R.layout.simple_spinner_item,
                Helper.getEmptyStringList());
    } else {/*w  w w. j  a va  2s .co  m*/
        adapter = new ArrayAdapter<String>(rootView.getContext(), android.R.layout.simple_spinner_item,
                vehicleModel.getCountryNames());
    }

    countrySpinner.setAdapter(adapter);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    // ?Spinner Adapter
    countrySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            if (i == 0) {
                setBrandSpinner(null);
            } else if (i >= 1) {
                setBrandSpinner(vehicleModel.countries.get(i - 1));
            }
        }

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

        }
    });

    countrySpinner.setSelection(lastCountryIndex);
    lastCountryIndex = 0;
}

From source file:com.df.dfcarchecker.CarCheck.CarCheckBasicInfoFragment.java

private void setBrandSpinner(final Country country) {
    ArrayAdapter<String> adapter;
    if (country == null) {
        adapter = new ArrayAdapter<String>(rootView.getContext(), android.R.layout.simple_spinner_item,
                Helper.getEmptyStringList());
    } else {/*from w  w w .ja va  2 s .  c  om*/
        adapter = new ArrayAdapter<String>(rootView.getContext(), android.R.layout.simple_spinner_item,
                country.getBrandNames());
    }

    brandSpinner.setAdapter(adapter);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    // ?Spinner Adapter
    brandSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            if (country == null || i == 0) {
                setManufacturerSpinner(null);
            } else if (i >= 1) {
                setManufacturerSpinner(country.brands.get(i - 1));
            }
        }

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

        }
    });

    // ???
    if (country != null && country.getBrandNames().size() == 2) {
        brandSpinner.setSelection(1);
    } else {
        brandSpinner.setSelection(lastBrandIndex);
    }

    lastBrandIndex = 0;
}

From source file:com.df.dfcarchecker.CarCheck.CarCheckBasicInfoFragment.java

private void setManufacturerSpinner(final Brand brand) {
    ArrayAdapter<String> adapter;

    if (brand == null) {
        adapter = new ArrayAdapter<String>(rootView.getContext(), android.R.layout.simple_spinner_item,
                Helper.getEmptyStringList());
    } else {/*  www.jav a 2  s.  c  om*/
        adapter = new ArrayAdapter<String>(rootView.getContext(), android.R.layout.simple_spinner_item,
                brand.getManufacturerNames());
    }

    manufacturerSpinner.setAdapter(adapter);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    // Spinner Adapter
    manufacturerSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            if (brand == null || i == 0) {
                setSeriesSpinner(null);
            } else if (i >= 1) {
                setSeriesSpinner(brand.manufacturers.get(i - 1));
            }
        }

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

        }
    });

    // ???
    if (brand != null && brand.getManufacturerNames().size() == 2) {
        manufacturerSpinner.setSelection(1);
    } else {
        manufacturerSpinner.setSelection(lastManufacturerIndex);
    }

    lastManufacturerIndex = 0;
}

From source file:com.df.dfcarchecker.CarCheck.CarCheckBasicInfoFragment.java

private void setSeriesSpinner(final Manufacturer manufacturer) {
    ArrayAdapter<String> adapter;

    if (manufacturer == null) {
        adapter = new ArrayAdapter<String>(rootView.getContext(), android.R.layout.simple_spinner_item,
                Helper.getEmptyStringList());
    } else {/*from   w  w w . j  a  v  a2s  .com*/
        adapter = new ArrayAdapter<String>(rootView.getContext(), android.R.layout.simple_spinner_item,
                manufacturer.getSerialNames());
    }

    seriesSpinner.setAdapter(adapter);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    // ?Spinner Adapter
    seriesSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            if (manufacturer == null || i == 0) {
                setModelSpinner(null);
            } else if (i >= 1) {
                setModelSpinner(manufacturer.serieses.get(i - 1));
            }

        }

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

        }
    });

    // ???
    if (manufacturer != null && manufacturer.getSerialNames().size() == 2) {
        seriesSpinner.setSelection(1);
    } else {
        seriesSpinner.setSelection(lastSeriesIndex);
    }

    lastSeriesIndex = 0;
}