Example usage for android.text TextUtils join

List of usage examples for android.text TextUtils join

Introduction

In this page you can find the example usage for android.text TextUtils join.

Prototype

public static String join(@NonNull CharSequence delimiter, @NonNull Iterable tokens) 

Source Link

Document

Returns a string containing the tokens joined by delimiters.

Usage

From source file:de.azapps.mirakel.model.query_builder.MirakelQueryBuilder.java

/**
 * Builds the query and returns it/*w ww  . jav  a2  s . c  o m*/
 * <p/>
 * This is currently just a very primitive function and is not suitable for
 * production use
 *
 * @return
 */
public String getQuery(final Uri uri) {
    final StringBuilder query = new StringBuilder(
            this.selection.length() + (this.projection.size() * 15) + (this.selectionArgs.size() * 15) + 100);
    query.append("SELECT ");
    if (this.distinct) {
        query.append("DISTINCT ");
    }
    query.append(TextUtils.join(", ", this.projection));
    query.append(" FROM ");
    query.append(MirakelInternalContentProvider.getTableName(uri));
    if (this.selection.length() > 0) {
        final String where = this.selection.toString();
        query.append(" WHERE ").append(where);
    }
    if (this.sortOrder.length() != 0) {
        query.append(" ORDER BY ").append(this.sortOrder);
    }
    return query.toString();
}

From source file:com.tbruyelle.rxpermissions.RxPermissions.java

void startShadowActivity(String[] permissions) {
    log("startShadowActivity " + TextUtils.join(", ", permissions));
    Intent intent = new Intent(mCtx, ShadowActivity.class);
    intent.putExtra("permissions", permissions);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    mCtx.startActivity(intent);//from ww w . jav a  2  s.co  m
}

From source file:org.totschnig.myexpenses.fragment.PlanList.java

@Override
public Loader<Cursor> onCreateLoader(int id, Bundle bundle) {
    switch (id) {
    case TEMPLATES_CURSOR:
        return new CursorLoader(getActivity(), TransactionProvider.TEMPLATES_URI, null,
                KEY_PLANID + " is not null", null, null);
    case PLANS_CURSOR:
        return new CursorLoader(getActivity(), Events.CONTENT_URI,
                new String[] { Events._ID, Events.DTSTART, Events.RRULE, }, Events._ID + " IN ("
                        + TextUtils.join(",", (ArrayList<Long>) bundle.getSerializable("plans")) + ")",
                null, null);/*from   w  ww.  ja  v a 2 s .  c  om*/
    default:
        if (id % 2 == 0) {
            // The ID of the recurring event whose instances you are searching
            // for in the Instances table
            String selection = Instances.EVENT_ID + " = " + bundle.getLong("plan_id");
            // Construct the query with the desired date range.
            Uri.Builder builder = Instances.CONTENT_URI.buildUpon();
            long now = System.currentTimeMillis();
            ContentUris.appendId(builder, now);
            ContentUris.appendId(builder, now + 7776000000L); //90 days
            return new CursorLoader(getActivity(), builder.build(),
                    new String[] { Instances._ID, Instances.BEGIN }, selection, null, null);
        } else {
            return new CursorLoader(getActivity(), TransactionProvider.PLAN_INSTANCE_STATUS_URI,
                    new String[] { KEY_TEMPLATEID, KEY_INSTANCEID, KEY_TRANSACTIONID }, KEY_TEMPLATEID + " = ?",
                    new String[] { String.valueOf(bundle.getLong("template_id")) }, null);
        }
    }
}

From source file:com.openerp.addons.messages.Message.java

public void setupListView(List<OEListViewRows> message_list) {
    // Destroying pre-loaded instance and going to create new one
    lstview = null;//from ww w  .j a v  a2s . c o  m

    // Fetching required messages for listview by filtering of requrement
    if (list != null && list.size() <= 0) {
        list = message_list;// getMessages(message_list);
    } else {
        rootView.findViewById(R.id.messageSyncWaiter).setVisibility(View.GONE);
        rootView.findViewById(R.id.txvMessageAllReadMessage).setVisibility(View.GONE);
    }

    // Handling List View controls and keys
    String[] from = new String[] { "subject|type", "body", "starred", "author_id|email_from", "date",
            "model|type" };
    int[] to = new int[] { R.id.txvMessageSubject, R.id.txvMessageBody, R.id.imgMessageStarred,
            R.id.txvMessageFrom, R.id.txvMessageDate, R.id.txvMessageTag };

    // Creating instance for listAdapter
    listAdapter = new OEListViewAdapter(scope.context(), R.layout.message_listview_items, list, from, to, db,
            true, new int[] { R.drawable.message_listview_bg_toread_selector,
                    R.drawable.message_listview_bg_tonotread_selector },
            "to_read");
    // Telling adapter to clean HTML text for key value
    listAdapter.cleanHtmlToTextOn("body");
    listAdapter.cleanDate("date", scope.User().getTimezone());
    // Setting callback handler for boolean field value change.
    listAdapter.setBooleanEventOperation("starred", R.drawable.ic_action_starred,
            R.drawable.ic_action_unstarred, updateStarred);
    listAdapter.addViewListener(new OEListViewOnCreateListener() {

        @Override
        public View listViewOnCreateListener(int position, View row_view, OEListViewRows row_data) {
            String model_name = row_data.getRow_data().get("model").toString();
            String model = model_name;
            String res_id = row_data.getRow_data().get("res_id").toString();
            if (model_name.equals("false")) {
                model_name = capitalizeString(row_data.getRow_data().get("type").toString());
            } else {
                String[] model_parts = TextUtils.split(model_name, "\\.");
                HashSet unique_parts = new HashSet(Arrays.asList(model_parts));
                model_name = capitalizeString(TextUtils.join(" ", unique_parts.toArray()));

            }
            TextView msgTag = (TextView) row_view.findViewById(R.id.txvMessageTag);
            int tag_color = 0;
            if (message_model_colors.containsKey(model_name)) {
                tag_color = message_model_colors.get(model_name);
            } else {
                tag_color = Color.parseColor(tag_colors[tag_color_count]);
                message_model_colors.put(model_name, tag_color);
                tag_color_count++;
                if (tag_color_count > tag_colors.length) {
                    tag_color_count = 0;
                }
            }
            if (model.equals("mail.group")) {
                if (UserGroups.group_names.containsKey("group_" + res_id)) {
                    model_name = UserGroups.group_names.get("group_" + res_id);
                    tag_color = UserGroups.menu_color.get("group_" + res_id);
                }
            }
            msgTag.setBackgroundColor(tag_color);
            msgTag.setText(model_name);
            TextView txvSubject = (TextView) row_view.findViewById(R.id.txvMessageSubject);
            TextView txvAuthor = (TextView) row_view.findViewById(R.id.txvMessageFrom);
            if (row_data.getRow_data().get("to_read").toString().equals("false")) {
                txvSubject.setTypeface(null, Typeface.NORMAL);
                txvSubject.setTextColor(Color.BLACK);

                txvAuthor.setTypeface(null, Typeface.NORMAL);
                txvAuthor.setTextColor(Color.BLACK);
            } else {
                txvSubject.setTypeface(null, Typeface.BOLD);
                txvSubject.setTextColor(Color.parseColor("#414141"));
                txvAuthor.setTypeface(null, Typeface.BOLD);
                txvAuthor.setTextColor(Color.parseColor("#414141"));
            }

            return row_view;
        }
    });

    // Creating instance for listview control
    lstview = (ListView) rootView.findViewById(R.id.lstMessages);
    // Providing adapter to listview
    scope.context().runOnUiThread(new Runnable() {

        @Override
        public void run() {
            lstview.setAdapter(listAdapter);

        }
    });

    // Setting listview choice mode to multiple model
    lstview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);

    // Seeting item long click listern to activate action mode.
    lstview.setOnItemLongClickListener(new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View view, int index, long arg3) {
            // TODO Auto-generated method stub

            OEListViewRows data = (OEListViewRows) lstview.getAdapter().getItem(index);

            Toast.makeText(scope.context(), data.getRow_id() + " id clicked", Toast.LENGTH_LONG).show();
            view.setSelected(true);
            if (mActionMode != null) {
                return false;
            }
            // Start the CAB using the ActionMode.Callback defined above
            mActionMode = scope.context().startActionMode(mActionModeCallback);
            selectedCounter++;
            view.setBackgroundResource(R.drawable.listitem_pressed);
            // lstview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
            return true;

        }
    });

    // Setting multi choice selection listener
    lstview.setMultiChoiceModeListener(new MultiChoiceModeListener() {
        HashMap<Integer, Boolean> selectedList = new HashMap<Integer, Boolean>();

        @Override
        public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
            // Here you can do something when items are
            // selected/de-selected,
            // such as update the title in the CAB
            selectedList.put(position, checked);
            if (checked) {
                selectedCounter++;
            } else {
                selectedCounter--;
            }
            if (selectedCounter != 0) {
                mode.setTitle(selectedCounter + "");
            }

        }

        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            // Respond to clicks on the actions in the CAB
            HashMap<Integer, Integer> msg_pos = new HashMap<Integer, Integer>();
            OEDialog dialog = null;
            switch (item.getItemId()) {
            case R.id.menu_message_mark_unread_selected:
                Log.e("menu_message_context", "Mark as Unread");
                for (int pos : selectedList.keySet()) {
                    msg_pos.put(list.get(pos).getRow_id(), pos);
                }
                readunreadoperation = new PerformReadUnreadArchiveOperation(msg_pos, false);
                readunreadoperation.execute((Void) null);
                mode.finish();
                return true;
            case R.id.menu_message_mark_read_selected:
                Log.e("menu_message_context", "Mark as Read");
                for (int pos : selectedList.keySet()) {
                    msg_pos.put(list.get(pos).getRow_id(), pos);
                }
                readunreadoperation = new PerformReadUnreadArchiveOperation(msg_pos, true);
                readunreadoperation.execute((Void) null);
                mode.finish();
                return true;
            case R.id.menu_message_more_move_to_archive_selected:
                Log.e("menu_message_context", "Archive");
                for (int pos : selectedList.keySet()) {
                    msg_pos.put(list.get(pos).getRow_id(), pos);
                }
                readunreadoperation = new PerformReadUnreadArchiveOperation(msg_pos, false);
                readunreadoperation.execute((Void) null);
                mode.finish();
                return true;
            case R.id.menu_message_more_add_star_selected:
                for (int pos : selectedList.keySet()) {
                    msg_pos.put(list.get(pos).getRow_id(), pos);
                }

                markasTodoTask = new PerformOperation(msg_pos, true);
                markasTodoTask.execute((Void) null);

                mode.finish();

                return true;
            case R.id.menu_message_more_remove_star_selected:
                for (int pos : selectedList.keySet()) {
                    msg_pos.put(list.get(pos).getRow_id(), pos);
                }

                markasTodoTask = new PerformOperation(msg_pos, false);
                markasTodoTask.execute((Void) null);
                mode.finish();
                return true;
            default:
                return false;
            }
        }

        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            // Inflate the menu for the CAB
            MenuInflater inflater = mode.getMenuInflater();
            inflater.inflate(R.menu.menu_fragment_message_context, menu);
            return true;
        }

        @Override
        public void onDestroyActionMode(ActionMode mode) {
            // Here you can make any necessary updates to the activity when
            // the CAB is removed. By default, selected items are
            // deselected/unchecked.

            /*
             * Perform Operation on Selected Ids.
             * 
             * row_ids are list of selected message Ids.
             */

            selectedList.clear();
            selectedCounter = 0;
            lstview.clearChoices();

        }

        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            // Here you can perform updates to the CAB due to
            // an invalidate() request
            return false;
        }
    });
    lstview.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View view, int index, long id) {
            // TODO Auto-generated method stub
            MessageDetail messageDetail = new MessageDetail();
            Bundle bundle = new Bundle();
            bundle.putInt("message_id", list.get(index).getRow_id());
            bundle.putInt("position", index);
            messageDetail.setArguments(bundle);
            scope.context().fragmentHandler.setBackStack(true, null);
            scope.context().fragmentHandler.replaceFragmnet(messageDetail);
            if (!type.equals("archive")) {
                list.remove(index);
            }
            listAdapter.refresh(list);
        }
    });

    // Getting Pull To Refresh Attacher from Main Activity
    mPullToRefreshAttacher = scope.context().getPullToRefreshAttacher();

    // Set the Refreshable View to be the ListView and the refresh listener
    // to be this.
    if (mPullToRefreshAttacher != null & lstview != null) {
        mPullToRefreshAttacher.setRefreshableView(lstview, this);
    }
}

From source file:info.wncwaterfalls.app.InformationListFragment.java

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
    if (cursor.moveToFirst()) {
        String name = cursor.getString(AttrDatabase.COLUMNS.indexOf("name"));

        // Update the Activity's title
        getActivity().setTitle(name);/*from   w  ww  .  j  ava2s . c om*/

        // Load up the views
        // First load the image view by using the ImageLoader class
        // Determine the photo's file name
        mWaterfallId = cursor.getLong(AttrDatabase.COLUMNS.indexOf("_id"));
        mWaterfallName = cursor.getString(AttrDatabase.COLUMNS.indexOf("name"));
        String fileName = cursor.getString(AttrDatabase.COLUMNS.indexOf("photo_filename"));
        String[] fnParts = fileName.split("\\.(?=[^\\.]+$)");

        final String image_fn = fnParts[0];
        final String wf_name = mWaterfallName;
        final Long wf_id = mWaterfallId;

        // Display image in the image view.
        ImageView mainImageContainer = (ImageView) getView().findViewById(R.id.information_waterfall_image);
        mImgLoader.displayImage(fnParts[0], mainImageContainer, getActivity(), mImageHeight, mImageHeight);

        // Add click listener for fullscreen view
        mainImageContainer.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                Intent fullScreenIntent = new Intent(v.getContext(), FullScreenImageActivity.class);
                fullScreenIntent.putExtra(IMAGE_FN, image_fn);
                fullScreenIntent.putExtra(WF_NAME, wf_name);
                fullScreenIntent.putExtra(WF_ID, wf_id);
                InformationListFragment.this.startActivity(fullScreenIntent);
            }
        });

        // Next load the text view containing attributes.
        TextView description = (TextView) getView().findViewById(R.id.information_content_description);
        description.setText(
                Html.fromHtml(cursor.getString(AttrDatabase.COLUMNS.indexOf("description"))).toString());

        // Prefix, db key, suffix
        String[][] hikeDetailElements = new String[][] { new String[] { " ", "trail_difficulty", "" },
                new String[] { " ", "trail_tread", "" }, new String[] { " ", "trail_climb", "" },
                new String[] { " Length: ", "trail_length", " mi" },
                new String[] { " Lowest Elevation: ", "trail_elevationlow", " ft" },
                new String[] { " Highest Elevation: ", "trail_elevationhigh", " ft" },
                new String[] { " Total Climb: ", "trail_elevationgain", " ft" },
                new String[] { " Configuration: ", "trail_configuration", "" } };

        // Filter out blank values in the db
        ArrayList<String> hikeDetailList = new ArrayList<String>();
        for (String[] element : hikeDetailElements) {
            String elementValue = cursor.getString(AttrDatabase.COLUMNS.indexOf(element[1]));
            if (elementValue != null && elementValue.length() > 0) {
                hikeDetailList.add(element[0] + elementValue + element[2]);
            }
        }

        // Stringifiy the ones that made it through
        String hikeDetailTxt = TextUtils.join("\n", hikeDetailList);
        TextView hikeDetails = (TextView) getView().findViewById(R.id.information_content_hike_details);
        hikeDetails.setText(hikeDetailTxt);

        TextView hikeDescription = (TextView) getView().findViewById(R.id.information_content_hike_description);
        hikeDescription.setText(
                Html.fromHtml(cursor.getString(AttrDatabase.COLUMNS.indexOf("trail_directions"))).toString());

        // Repeat for waterfall attributes...
        String[][] detailElements = new String[][] { new String[] { " Height: ", "height", "" },
                new String[] { " Stream: ", "stream", "" },
                new String[] { " Landowner: ", "landowner", "" },
                new String[] { " Bottom Elevation: ", "elevation", " ft" } };

        // Filter out blank values in the db
        ArrayList<String> detailList = new ArrayList<String>();
        for (String[] element : detailElements) {
            String elementValue = cursor.getString(AttrDatabase.COLUMNS.indexOf(element[1]));
            if (elementValue != null && elementValue.length() > 0) {
                detailList.add(element[0] + elementValue + element[2]);
            }
        }

        String detailTxt = TextUtils.join("\n", detailList);

        TextView waterfallDetails = (TextView) getView().findViewById(R.id.information_content_details);
        waterfallDetails.setText(detailTxt);

        TextView drivingDirections = (TextView) getView().findViewById(R.id.information_content_directions);
        drivingDirections.setText(
                Html.fromHtml(cursor.getString(AttrDatabase.COLUMNS.indexOf("directions"))).toString());

        setupShareIntent(); // In case the options menu is already created

    }
}

From source file:comp3111h.anytaxi.driver.Register_FormFragment.java

private String nameBeautifier(String name) {
    String[] partialNames = TextUtils.split(name.trim().toUpperCase(Locale.getDefault()), " +");
    for (int i = 0; i < partialNames.length; i++)
        partialNames[i] = partialNames[i].charAt(0)
                + partialNames[i].substring(1).toLowerCase(Locale.getDefault());

    name = TextUtils.join(" ", partialNames);

    return name;//from   w  w  w .ja v a 2  s  . c  om
}

From source file:li.barter.http.HttpResponseParser.java

/**
 * Parses the good reads API response for fetching a book
 *
 * @param response//w  w w.j  a  v  a2s  . c om
 * @return
 * @throws XmlPullParserException
 * @throws IOException
 */
private ResponseInfo parseGoogleBooksBookInfo(String response) throws JSONException {

    final ResponseInfo responseInfo = new ResponseInfo();
    Logger.d(TAG, "Request Id Test \nResponse %s", response);

    final Bundle responseBundle = new Bundle(1);

    final JSONObject bookInfoObject = new JSONObject(response);
    final JSONArray searchResults = JsonUtils.readJSONArray(bookInfoObject, HttpConstants.ITEMS, true, true);
    for (int i = 0; i < searchResults.length(); i++) {

        JSONObject bookInfo = JsonUtils.readJSONObject(searchResults, i, false, false);

        JSONObject volumeInfo = JsonUtils.readJSONObject(bookInfo, HttpConstants.VOLUMEINFO, false, false);
        responseBundle.putString(HttpConstants.TITLE,
                JsonUtils.readString(volumeInfo, HttpConstants.TITLE, false, false));
        JSONArray authors = JsonUtils.readJSONArray(volumeInfo, HttpConstants.AUTHORS, false, false);
        ArrayList<String> authorName = new ArrayList<String>();

        if (authors != null && authors.length() > 0) {

            if (authors.length() == 1) {
                authorName.add(authors.get(0).toString());

            } else {
                for (int k = 0; k < authors.length(); k++) {

                    authorName.add(authors.get(k).toString());

                }
            }
        }

        String author = TextUtils.join(", ", authorName);
        responseBundle.putString(HttpConstants.AUTHOR, author);

        responseBundle.putString(HttpConstants.PUBLICATION_YEAR,
                JsonUtils.readString(volumeInfo, HttpConstants.PUBLISHED_DATE, false, false));

        responseBundle.putString(HttpConstants.DESCRIPTION,
                JsonUtils.readString(volumeInfo, HttpConstants.DESCRIPTION, false, false));

        JSONArray identifiers = JsonUtils.readJSONArray(volumeInfo, HttpConstants.INDUSTRY_IDENTIFIERS, false,
                false);
        JSONObject identifierObject = null;
        //TODO might change the true flag
        if (identifiers != null) {
            for (int j = 0; j < identifiers.length(); j++) {
                identifierObject = JsonUtils.readJSONObject(identifiers, j, true, true);
                final String type = JsonUtils.readString(identifierObject, HttpConstants.TYPE, true, true);

                if (type.equals(GoogleBookSearchKey.ISBN_13)) {
                    responseBundle.putString(HttpConstants.ISBN_13,
                            JsonUtils.readString(identifierObject, HttpConstants.IDENTIFIER, true, true));
                } else if (type.equals(GoogleBookSearchKey.ISBN_10)) {
                    responseBundle.putString(HttpConstants.ISBN_10,
                            JsonUtils.readString(identifierObject, HttpConstants.IDENTIFIER, true, true));
                }
            }
        }

        JSONObject imageLinks = null;

        try {
            imageLinks = JsonUtils.readJSONObject(volumeInfo, HttpConstants.IMAGELINKS, false, false);
            responseBundle.putString(HttpConstants.IMAGE_URL,
                    JsonUtils.readString(imageLinks, HttpConstants.THUMBNAIL, false, false));
        } catch (Exception e) {
            responseBundle.putString(HttpConstants.IMAGE_URL, "");
        }

    }
    responseInfo.responseBundle = responseBundle;
    return responseInfo;
}

From source file:com.zhengde163.netguard.ActivityLog.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    //        Util.setTheme(this);
    setTheme(R.style.AppThemeBlue);/*from   w w  w. j  a  va  2 s  .  c o m*/
    super.onCreate(savedInstanceState);
    setContentView(R.layout.logging);
    running = true;

    // Action bar
    View actionView = getLayoutInflater().inflate(R.layout.actionlog, null, false);
    //        SwitchCompat swEnabled = (SwitchCompat) actionView.findViewById(R.id.swEnabled);
    ImageView ivEnabled = (ImageView) actionView.findViewById(R.id.ivEnabled);

    getSupportActionBar().setDisplayShowCustomEnabled(true);
    getSupportActionBar().setCustomView(actionView);

    getSupportActionBar().setTitle(R.string.menu_log);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    // Get settings
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    resolve = prefs.getBoolean("resolve", false);
    organization = prefs.getBoolean("organization", false);
    log = prefs.getBoolean("log", false);

    // Show disabled message
    //        TextView tvDisabled = (TextView) findViewById(R.id.tvDisabled);
    //        tvDisabled.setVisibility(log ? View.GONE : View.VISIBLE);
    final LinearLayout ly = (LinearLayout) findViewById(R.id.lldisable);
    ly.setVisibility(log ? View.GONE : View.VISIBLE);

    ImageView ivClose = (ImageView) findViewById(R.id.ivClose);
    ivClose.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ly.setVisibility(View.GONE);
        }
    });
    // Set enabled switch
    //        swEnabled.setChecked(log);
    if (ivEnabled != null) {
        if (log) {
            ivEnabled.setImageResource(R.drawable.on);
        } else {
            ivEnabled.setImageResource(R.drawable.off);
        }
        ivEnabled.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                log = !log;
                boolean isChecked = log;
                prefs.edit().putBoolean("log", isChecked).apply();

            }
        });
    }
    //        swEnabled.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    //            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    //                prefs.edit().putBoolean("log", isChecked).apply();
    //            }
    //        });

    // Listen for preference changes
    prefs.registerOnSharedPreferenceChangeListener(this);

    lvLog = (ListView) findViewById(R.id.lvLog);

    boolean udp = prefs.getBoolean("proto_udp", true);
    boolean tcp = prefs.getBoolean("proto_tcp", true);
    boolean other = prefs.getBoolean("proto_other", true);
    boolean allowed = prefs.getBoolean("traffic_allowed", true);
    boolean blocked = prefs.getBoolean("traffic_blocked", true);

    adapter = new AdapterLog(this, DatabaseHelper.getInstance(this).getLog(udp, tcp, other, allowed, blocked),
            resolve, organization);
    adapter.setFilterQueryProvider(new FilterQueryProvider() {
        public Cursor runQuery(CharSequence constraint) {
            return DatabaseHelper.getInstance(ActivityLog.this).searchLog(constraint.toString());
        }
    });

    lvLog.setAdapter(adapter);

    try {
        vpn4 = InetAddress.getByName(prefs.getString("vpn4", "10.1.10.1"));
        vpn6 = InetAddress.getByName(prefs.getString("vpn6", "fd00:1:fd00:1:fd00:1:fd00:1"));
    } catch (UnknownHostException ex) {
        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
    }

    lvLog.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            PackageManager pm = getPackageManager();
            Cursor cursor = (Cursor) adapter.getItem(position);
            long time = cursor.getLong(cursor.getColumnIndex("time"));
            int version = cursor.getInt(cursor.getColumnIndex("version"));
            int protocol = cursor.getInt(cursor.getColumnIndex("protocol"));
            final String saddr = cursor.getString(cursor.getColumnIndex("saddr"));
            final int sport = (cursor.isNull(cursor.getColumnIndex("sport")) ? -1
                    : cursor.getInt(cursor.getColumnIndex("sport")));
            final String daddr = cursor.getString(cursor.getColumnIndex("daddr"));
            final int dport = (cursor.isNull(cursor.getColumnIndex("dport")) ? -1
                    : cursor.getInt(cursor.getColumnIndex("dport")));
            final String dname = cursor.getString(cursor.getColumnIndex("dname"));
            final int uid = (cursor.isNull(cursor.getColumnIndex("uid")) ? -1
                    : cursor.getInt(cursor.getColumnIndex("uid")));
            int allowed = (cursor.isNull(cursor.getColumnIndex("allowed")) ? -1
                    : cursor.getInt(cursor.getColumnIndex("allowed")));

            // Get external address
            InetAddress addr = null;
            try {
                addr = InetAddress.getByName(daddr);
            } catch (UnknownHostException ex) {
                Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
            }

            String ip;
            int port;
            if (addr.equals(vpn4) || addr.equals(vpn6)) {
                ip = saddr;
                port = sport;
            } else {
                ip = daddr;
                port = dport;
            }

            // Build popup menu
            PopupMenu popup = new PopupMenu(ActivityLog.this, findViewById(R.id.vwPopupAnchor));
            popup.inflate(R.menu.log);

            // Application name
            if (uid >= 0)
                popup.getMenu().findItem(R.id.menu_application)
                        .setTitle(TextUtils.join(", ", Util.getApplicationNames(uid, ActivityLog.this)));
            else
                popup.getMenu().removeItem(R.id.menu_application);

            // Destination IP
            popup.getMenu().findItem(R.id.menu_protocol)
                    .setTitle(Util.getProtocolName(protocol, version, false));

            // Whois
            final Intent lookupIP = new Intent(Intent.ACTION_VIEW,
                    Uri.parse("http://www.tcpiputils.com/whois-lookup/" + ip));
            if (pm.resolveActivity(lookupIP, 0) == null)
                popup.getMenu().removeItem(R.id.menu_whois);
            else
                popup.getMenu().findItem(R.id.menu_whois).setTitle(getString(R.string.title_log_whois, ip));

            // Lookup port
            final Intent lookupPort = new Intent(Intent.ACTION_VIEW,
                    Uri.parse("http://www.speedguide.net/port.php?port=" + port));
            if (port <= 0 || pm.resolveActivity(lookupPort, 0) == null)
                popup.getMenu().removeItem(R.id.menu_port);
            else
                popup.getMenu().findItem(R.id.menu_port).setTitle(getString(R.string.title_log_port, port));

            if (!prefs.getBoolean("filter", false)) {
                popup.getMenu().removeItem(R.id.menu_allow);
                popup.getMenu().removeItem(R.id.menu_block);
            }

            final Packet packet = new Packet();
            packet.version = version;
            packet.protocol = protocol;
            packet.daddr = daddr;
            packet.dport = dport;
            packet.time = time;
            packet.uid = uid;
            packet.allowed = (allowed > 0);

            // Time
            popup.getMenu().findItem(R.id.menu_time)
                    .setTitle(SimpleDateFormat.getDateTimeInstance().format(time));

            // Handle click
            popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem menuItem) {
                    switch (menuItem.getItemId()) {
                    case R.id.menu_application: {
                        Intent main = new Intent(ActivityLog.this, ActivityMain.class);
                        main.putExtra(ActivityMain.EXTRA_SEARCH, Integer.toString(uid));
                        startActivity(main);
                        return true;
                    }

                    case R.id.menu_whois:
                        startActivity(lookupIP);
                        return true;

                    case R.id.menu_port:
                        startActivity(lookupPort);
                        return true;

                    case R.id.menu_allow:
                        DatabaseHelper.getInstance(ActivityLog.this).updateAccess(packet, dname, 0);
                        ServiceSinkhole.reload("allow host", ActivityLog.this);
                        Intent main = new Intent(ActivityLog.this, ActivityMain.class);
                        main.putExtra(ActivityMain.EXTRA_SEARCH, Integer.toString(uid));
                        startActivity(main);
                        return true;

                    case R.id.menu_block:
                        DatabaseHelper.getInstance(ActivityLog.this).updateAccess(packet, dname, 1);
                        ServiceSinkhole.reload("block host", ActivityLog.this);
                        Intent main1 = new Intent(ActivityLog.this, ActivityMain.class);
                        main1.putExtra(ActivityMain.EXTRA_SEARCH, Integer.toString(uid));
                        startActivity(main1);
                        return true;

                    default:
                        return false;
                    }
                }
            });

            // Show
            popup.show();
        }
    });

    live = true;
}

From source file:com.example.android.apprestrictionenforcer.AppRestrictionEnforcerFragment.java

/**
 * Loads the restrictions for the AppRestrictionSchema sample.
 *
 * @param activity The activity/*from w  ww. j  av a 2  s .  c o m*/
 */
private void loadRestrictions(Activity activity) {
    RestrictionsManager manager = (RestrictionsManager) activity.getSystemService(Context.RESTRICTIONS_SERVICE);
    List<RestrictionEntry> restrictions = manager
            .getManifestRestrictions(Constants.PACKAGE_NAME_APP_RESTRICTION_SCHEMA);
    SharedPreferences prefs = activity.getSharedPreferences(PREFS_KEY, Context.MODE_PRIVATE);
    for (RestrictionEntry restriction : restrictions) {
        String key = restriction.getKey();
        if (RESTRICTION_KEY_SAY_HELLO.equals(key)) {
            updateCanSayHello(prefs.getBoolean(RESTRICTION_KEY_SAY_HELLO, restriction.getSelectedState()));
        } else if (RESTRICTION_KEY_MESSAGE.equals(key)) {
            updateMessage(prefs.getString(RESTRICTION_KEY_MESSAGE, restriction.getSelectedString()));
        } else if (RESTRICTION_KEY_NUMBER.equals(key)) {
            updateNumber(prefs.getInt(RESTRICTION_KEY_NUMBER, restriction.getIntValue()));
        } else if (RESTRICTION_KEY_RANK.equals(key)) {
            updateRank(activity, restriction.getChoiceValues(),
                    prefs.getString(RESTRICTION_KEY_RANK, restriction.getSelectedString()));
        } else if (RESTRICTION_KEY_APPROVALS.equals(key)) {
            updateApprovals(activity, restriction.getChoiceValues(),
                    TextUtils.split(
                            prefs.getString(RESTRICTION_KEY_APPROVALS,
                                    TextUtils.join(DELIMETER, restriction.getAllSelectedStrings())),
                            DELIMETER));
        } else if (BUNDLE_SUPPORTED && RESTRICTION_KEY_ITEMS.equals(key)) {
            String itemsString = prefs.getString(RESTRICTION_KEY_ITEMS, "");
            HashMap<String, String> items = new HashMap<>();
            for (String itemString : TextUtils.split(itemsString, DELIMETER)) {
                String[] strings = itemString.split(SEPARATOR, 2);
                items.put(strings[0], strings[1]);
            }
            updateItems(activity, items);
        }
    }
}

From source file:info.wncwaterfalls.app.ResultsMapFragment.java

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
    int count = cursor.getCount();
    if (count == 0) {
        Context context = getActivity();
        CharSequence text = "No results found for your search.";
        int duration = Toast.LENGTH_LONG;
        Toast toast = Toast.makeText(context, text, duration);
        toast.show();/*from  ww  w.ja v  a  2  s.co  m*/
    } else {
        // Put the results on a map!
        GoogleMap googleMap = mMapView.getMap();
        double searchLocationDistanceM = 0;
        LatLngBounds.Builder boundsBuilder = new LatLngBounds.Builder();
        if (cursor.moveToFirst()) {
            // First, add the "searched for" location, if it was a location search.
            Location originLocation = new Location("");
            Address originAddress = sLocationQueryListener.getOriginAddress();
            if (originAddress != null) {
                // Get searched-for distance and convert to meters.
                short searchLocationDistance = sLocationQueryListener.getSearchLocationDistance();
                searchLocationDistanceM = searchLocationDistance * 1609.34;

                // Build up a list of Address1, Address2, Address3, if present.
                ArrayList<String> addressList = new ArrayList<String>();
                for (int i = 0; i <= 3; i++) {
                    String line = originAddress.getAddressLine(i);
                    if (line != null && line.length() > 0) {
                        addressList.add(line);
                    }
                }

                String addressDesc = TextUtils.join("\n", addressList);
                if (addressDesc == "") {
                    addressDesc = originAddress.getFeatureName();
                }
                if (addressDesc == "") {
                    addressDesc = "Searched Location";
                }

                // Create the LatLng and the map marker.
                LatLng originLatLng = new LatLng(originAddress.getLatitude(), originAddress.getLongitude());
                googleMap.addMarker(new MarkerOptions().position(originLatLng)
                        .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED))
                        .title(addressDesc));

                boundsBuilder.include(originLatLng); // In case only one result :)

                // Translate into a Location for distance comparison.
                originLocation.setLatitude(originAddress.getLatitude());
                originLocation.setLongitude(originAddress.getLongitude());
            } else {
                // Not a location search; don't add point for searched-for location
                // and don't check radius from that point.
                //Log.d(TAG, "Skipped adding origin address to map.");
            }

            // Next, add the results waterfalls.
            // Use do...while since we're already at the first result.
            do {
                // Get some data from the db
                Long waterfallId = cursor.getLong(AttrDatabase.COLUMNS.indexOf("_id"));
                double lat = cursor.getDouble(AttrDatabase.COLUMNS.indexOf("geo_lat"));
                double lon = cursor.getDouble(AttrDatabase.COLUMNS.indexOf("geo_lon"));

                // Make sure this one's actually within our search radius. SQL only checked
                // the bounding box.
                Location waterfallLocation = new Location("");
                waterfallLocation.setLatitude(lat);
                waterfallLocation.setLongitude(lon);

                if (originAddress == null
                        || (originLocation.distanceTo(waterfallLocation) <= searchLocationDistanceM)) {
                    // Not a location search (originAddress is null: show all) or within radius.
                    // Display on map.
                    String name = cursor.getString(AttrDatabase.COLUMNS.indexOf("name"));

                    LatLng waterfallLatLng = new LatLng(lat, lon);
                    Marker waterfallMarker = googleMap.addMarker(new MarkerOptions().position(waterfallLatLng)
                            .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
                            .title(name));

                    // Save the id so we can retrieve it when clicked
                    mMarkersToIds.put(waterfallMarker, waterfallId);
                    boundsBuilder.include(waterfallLatLng);
                }

            } while (cursor.moveToNext());

            // Zoom and center the map to bounds
            mResultBounds = boundsBuilder.build();
            zoomToBounds();
        }
    }
}