Example usage for android.widget TextView setVisibility

List of usage examples for android.widget TextView setVisibility

Introduction

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

Prototype

@RemotableViewMethod
public void setVisibility(@Visibility int visibility) 

Source Link

Document

Set the visibility state of this view.

Usage

From source file:com.closedevice.fastapp.view.tab.SlidingTabLayout.java

public void setMessageTipVisible(int visible) {
    int size = mTabStrip.getChildCount();
    for (int i = 0; i < size; i++) {
        TextView mTvMessageCount = (TextView) mTabStrip.getChildAt(i).findViewById(R.id.tv_unread_count);
        if (mTvMessageCount == null)
            continue;
        if (visible == View.VISIBLE) {// try to show num
            String count = mTvMessageCount.getText().toString();
            if (!TextUtils.isEmpty(count)) {
                int num = Integer.parseInt(count);
                if (num > 0) {
                    mTvMessageCount.setVisibility(View.VISIBLE);
                    continue;
                }/*from   w  ww.  ja va 2s .c  o m*/
            }
            mTvMessageCount.setVisibility(View.INVISIBLE);
        } else {
            mTvMessageCount.setVisibility(visible);
        }
    }
}

From source file:com.codingspezis.android.metalonly.player.LicenseActivity.java

@SuppressLint("DefaultLocale")
@Override//from  w w w .ja va 2  s.  c o m
public void onCreate(Bundle savedInstanceState) {
    // TODO refactor
    super.onCreate(savedInstanceState);

    getSupportActionBar().setHomeButtonEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    String license = "";
    Bundle bundle = getIntent().getExtras();
    if (bundle != null) {
        license = bundle.getString(KEY_BU_LICENSE_NAME);
    }
    setContentView(R.layout.activity_licensing);
    setTitle(license.toUpperCase());
    final TextView textView = (TextView) findViewById(R.id.license);
    final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress);
    final ThreadedLicenseReader reader = new ThreadedLicenseReader(this, license);
    reader.setOnLicenseReadListener(new OnLicenseReadListener() {
        @Override
        public void onLicenseRead() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    String license = reader.getLicense();
                    if (license != null) {
                        textView.setText(license);
                    }
                    progressBar.setVisibility(View.INVISIBLE);
                    textView.setVisibility(View.VISIBLE);
                }
            });
        }
    });
    reader.start();
}

From source file:org.nasa.openspace.gc.geolocation.LocationActivity.java

/**
 * This sample demonstrates how to incorporate location based services in your app and
 * process location updates.  The app also shows how to convert lat/long coordinates to
 * human-readable addresses.//from w  ww. ja  v a2  s  . co  m
 */
//@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.geolocation);

    // Restore apps state (if exists) after rotation.
    if (savedInstanceState != null) {
        mUseFine = savedInstanceState.getBoolean(KEY_FINE);
        mUseBoth = savedInstanceState.getBoolean(KEY_BOTH);
    } else {
        mUseFine = false;
        mUseBoth = false;
    }
    TextView tv1 = (TextView) findViewById(R.id.textView1);
    TextView tv2 = (TextView) findViewById(R.id.textView2);
    TextView tv3 = (TextView) findViewById(R.id.fileLocation);
    ImageView iv1 = (ImageView) findViewById(R.id.imageView1);
    btnUpload = (Button) findViewById(R.id.btnUpload);
    tv1.setText("Name : " + Session.name);
    tv2.setText("Caption :" + Session.caption);
    iv1.setImageBitmap(Session.image);
    tv3.setVisibility(View.GONE);
    //tv3.setText(Session.fileLocation2);
    mLatLng = (TextView) findViewById(R.id.latlng);
    mAddress = (TextView) findViewById(R.id.address);
    // Receive location updates from the fine location provider (gps) only.
    mFineProviderButton = (Button) findViewById(R.id.provider_fine);
    // Receive location updates from both the fine (gps) and coarse (network) location
    // providers.
    mBothProviderButton = (Button) findViewById(R.id.provider_both);

    // The isPresent() helper method is only available on Gingerbread or above.
    mGeocoderAvailable = Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD && Geocoder.isPresent();

    // Handler for updating text fields on the UI like the lat/long and address.
    mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case UPDATE_ADDRESS:
                mAddress.setText((String) msg.obj);
                break;
            case UPDATE_LATLNG:
                mLatLng.setText((String) msg.obj);
                String[] res = ((String) msg.obj).split(",");
                lat = res[0];
                longt = res[1];
                break;
            }
        }
    };
    // Get a reference to the LocationManager object.
    mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    mBothProviderButton.performClick();
    btnUpload.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            try {
                executeMultipartPost();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });
}

From source file:com.android.contacts.activities.ContactSelectionActivity.java

private void updateAddContactsButton(int count) {
    final TextView textView = (TextView) mActionBarAdapter.getSelectionContainer()
            .findViewById(R.id.add_contacts);
    if (count > 0) {
        textView.setVisibility(View.VISIBLE);
        textView.setAllCaps(true);/*w ww . j a va2  s .  c  o m*/
        textView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                final long[] contactIds = getMultiSelectListFragment().getSelectedContactIdsArray();
                returnSelectedContacts(contactIds);
            }
        });
    } else {
        textView.setVisibility(View.GONE);
    }
}

From source file:com.firebase.ui.auth.ui.phone.SubmitConfirmationCodeFragment.java

private CustomCountDownTimer createCountDownTimer(final TextView timerText, final TextView resendCode,
        final SubmitConfirmationCodeFragment fragment, final long startTimeMillis) {
    return new CustomCountDownTimer(startTimeMillis, 500) {
        SubmitConfirmationCodeFragment mSubmitConfirmationCodeFragment = fragment;

        public void onTick(long millisUntilFinished) {
            mMillisUntilFinished = millisUntilFinished;
            mSubmitConfirmationCodeFragment.setTimer(millisUntilFinished);
        }/* w  w  w .  ja  v a2 s  .co m*/

        public void onFinish() {
            timerText.setText("");
            timerText.setVisibility(View.GONE);
            resendCode.setVisibility(View.VISIBLE);
        }
    };
}

From source file:com.glanznig.beepme.view.ExportActivity.java

private void populateFields() {
    BeeperApp app = (BeeperApp) getApplication();

    if (app.getPreferences().exportRunningSince() == 0L || (Calendar.getInstance().getTimeInMillis()
            - app.getPreferences().exportRunningSince()) >= 120000) { //2 min

        enableDisableView(findViewById(R.id.export_settings), true);

        CheckBox rawExp = (CheckBox) findViewById(R.id.export_raw);
        rawExp.setChecked(rawExport);//from  w w w  .j a  v  a  2 s. c om
        rawExp.setOnClickListener(this);

        CheckBox photoExp = (CheckBox) findViewById(R.id.export_photos);
        View photoExpGroup = findViewById(R.id.export_photos_group);

        if (PhotoUtils.isEnabled(ExportActivity.this)) {
            photoExp.setVisibility(View.VISIBLE);
            photoExpGroup.setVisibility(View.VISIBLE);

            File[] photos = PhotoUtils.getPhotos(ExportActivity.this);
            if (photos != null && photos.length > 0) {
                photoExp.setEnabled(true);
                photoExp.setChecked(photoExport);
                photoExp.setOnClickListener(this);

                enableDisableView(photoExpGroup, photoExport);
            } else {
                photoExp.setChecked(false);
                photoExp.setEnabled(false);
                enableDisableView(photoExpGroup, false);
            }

            downscalePhotos = (Spinner) findViewById(R.id.export_downscale_photos);
            downscaleAdapter = new ArrayAdapter<CharSequence>(ExportActivity.this,
                    android.R.layout.simple_spinner_item, new ArrayList<CharSequence>());
            downscaleAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            downscalePhotos.setAdapter(downscaleAdapter);
            downscalePhotos.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    densityItem = position;
                    Bundle opts = new Bundle();
                    opts.putBoolean("photoExport", photoExport);
                    opts.putBoolean("rawExport", rawExport);
                    estimatedSize.setText(String.format(getString(R.string.export_archive_estimated_size),
                            exporter.getReadableArchiveSize(opts,
                                    densityFactors.get(downscalePhotos.getSelectedItemPosition()).intValue())));
                }

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

                }
            });

            if (photoAvgSize == 0) {
                File[] photoFiles = PhotoUtils.getPhotos(ExportActivity.this);
                int count;
                int overallSize = 0;
                for (count = 0; count < photoFiles.length; count++) {
                    overallSize += photoFiles[count].length();
                }
                if (count > 0) {
                    photoAvgSize = overallSize / count;
                }
            }

            if (photoAvgDensity == 0) {
                new Thread(new PhotoDimRunnable(ExportActivity.this, new PhotoDimHandler(ExportActivity.this)))
                        .start();
            } else {
                TextView density = (TextView) findViewById(R.id.export_photos_avg_size);
                density.setText(
                        getString(R.string.export_photos_avg_size, String.format("%.1f", photoAvgDensity)));

                downscaleAdapter.add(String.format(getString(R.string.export_downscale_original_size),
                        DataExporter.getReadableFileSize(photoAvgSize, 0)));
                densityFactors.add(Integer.valueOf(1));
                int densityFactor = 2;

                for (; (Math.round((photoAvgDensity / densityFactor) * 2) / 2f) > 1; densityFactor *= 2) {
                    downscaleAdapter.add(String.format(getString(R.string.export_downscale),
                            String.format("%.1f", Math.round((photoAvgDensity / densityFactor) * 2) / 2f),
                            DataExporter.getReadableFileSize(photoAvgSize / densityFactor, 0)));
                    densityFactors.add(Integer.valueOf(densityFactor));
                }

                downscaleAdapter.add(String.format(getString(R.string.export_downscale), String.valueOf(1),
                        DataExporter.getReadableFileSize(photoAvgSize / densityFactor, 0)));
                densityFactors.add(Integer.valueOf(densityFactor));

                if (densityItem != -1) {
                    downscalePhotos.setSelection(densityItem);
                }
            }

        } else {
            photoExp.setVisibility(View.GONE);
            photoExpGroup.setVisibility(View.GONE);
        }

        postActions = (Spinner) findViewById(R.id.export_post_actions);
        ArrayAdapter<CharSequence> actionsAdapter = ArrayAdapter.createFromResource(this,
                R.array.post_export_actions, android.R.layout.simple_spinner_item);
        actionsAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        postActions.setAdapter(actionsAdapter);

        if (postActionItem != -1) {
            postActions.setSelection(postActionItem);
        }

        estimatedSize = (TextView) findViewById(R.id.export_estimated_size);
        int densityFactor = 1;

        if (densityFactors.size() > 0 && downscalePhotos.getSelectedItemPosition() >= 0) {
            densityFactor = densityFactors.get(downscalePhotos.getSelectedItemPosition()).intValue();
        }

        Bundle opts = new Bundle();
        opts.putBoolean("photoExport", photoExport);
        opts.putBoolean("rawExport", rawExport);
        estimatedSize.setText(String.format(getString(R.string.export_archive_estimated_size),
                exporter.getReadableArchiveSize(opts, densityFactor)));

        Button start = (Button) findViewById(R.id.export_start_button);
        ProgressBar progress = (ProgressBar) findViewById(R.id.export_progress_bar);
        TextView runningText = (TextView) findViewById(R.id.export_running_text);

        start.setVisibility(View.VISIBLE);
        progress.setVisibility(View.GONE);
        runningText.setVisibility(View.GONE);
    } else {
        Button start = (Button) findViewById(R.id.export_start_button);
        ProgressBar progress = (ProgressBar) findViewById(R.id.export_progress_bar);
        TextView runningText = (TextView) findViewById(R.id.export_running_text);

        start.setVisibility(View.GONE);
        progress.setVisibility(View.VISIBLE);
        runningText.setVisibility(View.VISIBLE);

        enableDisableView(findViewById(R.id.export_settings), false);
    }
}

From source file:gr.scify.newsum.ui.SearchViewActivity.java

private void initTopicSpinner() {
    // Get topics in category. Null accepts all user sources. Modify
    // according to user selection
    final String[] saTopicIDs = SearchTopicActivity.saTopicIDs;
    final String[] saTitles = SearchTopicActivity.saTopicTitles;
    final String[] saDates = SearchTopicActivity.saTopicDates;
    // TODO add TopicInfo for SearchResults as well and parse accordingly

    // final String[] saTopicIDs = extras.getStringArray("searchresults");
    final TextView title = (TextView) findViewById(R.id.title);
    // Fill topic spinner
    ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(this,
            android.R.layout.simple_spinner_item, saTitles);

    final TextView tx = (TextView) findViewById(R.id.textView1);
    // tx.setMovementMethod(LinkMovementMethod.getInstance());
    //      final float minm = tx.getTextSize();
    //      final float maxm = (minm + 24);

    // create an invisible spinner just to control the summaries of the
    // category (i will use it later on Swipe)
    Spinner spinner = (Spinner) findViewById(R.id.spinner1);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);//from ww  w .j  av  a 2 s. com

    // Scroll view init
    final ScrollView scroll = (ScrollView) findViewById(R.id.scrollView1);
    // Add selection event
    spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

            // Show waiting dialog
            showWaitingDialog();

            // Changing summary
            loading = true;
            // Update visibility of rating bar
            final RatingBar rb = (RatingBar) findViewById(R.id.ratingBar);
            rb.setRating(0.0f);
            rb.setVisibility(View.VISIBLE);
            final TextView rateLbl = (TextView) findViewById(R.id.rateLbl);
            rateLbl.setVisibility(View.VISIBLE);

            scroll.scrollTo(0, 0);
            //            String[] saTopicIDs = sTopicIds.split(sSeparator);

            SharedPreferences settings = getSharedPreferences("urls", 0);
            // get user settings for sources
            String UserSources = settings.getString("UserLinks", "All");
            String[] Summary = NewSumServiceClient.getSummary(saTopicIDs[arg2], UserSources);
            if (Summary.length == 0) { // WORK. Updated: CHECK
                // Close waiting dialog
                closeWaitingDialog();

                AlertDialog.Builder alert = new AlertDialog.Builder(SearchViewActivity.this);
                alert.setMessage(R.string.shouldReloadSummaries);
                alert.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface arg0, int arg1) {
                        startActivity(new Intent(getApplicationContext(), NewSumUiActivity.class)
                                .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
                    }
                });
                alert.setCancelable(false);
                alert.show();
                loading = false;
                return;
            }
            // track summary views per Search and topic title
            if (getAnalyticsPref()) {
                EasyTracker.getTracker().sendEvent(VIEW_SUMMARY_ACTION, "From Search",
                        saTitles[arg2] + ": " + saDates[arg2], 0l);
            }
            // Generate summary text
            sText = ViewActivity.generateSummaryText(Summary, SearchViewActivity.this);
            pText = ViewActivity.generatesummarypost(Summary, SearchViewActivity.this);
            tx.setText(Html.fromHtml(sText));
            tx.setMovementMethod(LinkMovementMethod.getInstance());
            title.setText(saTitles[arg2] + ": " + saDates[arg2]);
            float defSize = tx.getTextSize();
            SharedPreferences usersize = getSharedPreferences("textS", 0);
            float newSize = usersize.getFloat("size", defSize);
            tx.setTextSize(TypedValue.COMPLEX_UNIT_PX, newSize);
            // update the TopicActivity with viewed item
            TopicActivity.addVisitedTopicID(saTopicIDs[arg2]);

            // Close waiting dialog
            closeWaitingDialog();

        }

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

    });

}

From source file:com.cw.litenote.note.Note_adapter.java

@SuppressLint("SetJavaScriptEnabled")
@Override/*from  ww  w  .  j ava2s  . c  o m*/
public Object instantiateItem(ViewGroup container, final int position) {
    System.out.println("Note_adapter / instantiateItem / position = " + position);
    // Inflate the layout containing 
    // 1. picture group: image,video, thumb nail, control buttons
    // 2. text group: title, body, time 
    View pagerView = inflater.inflate(R.layout.note_view_adapter, container, false);
    int style = Note.getStyle();
    pagerView.setBackgroundColor(ColorSet.mBG_ColorArray[style]);

    // Picture group
    ViewGroup pictureGroup = (ViewGroup) pagerView.findViewById(R.id.pictureContent);
    String tagPictureStr = "current" + position + "pictureView";
    pictureGroup.setTag(tagPictureStr);

    // image view
    TouchImageView imageView = ((TouchImageView) pagerView.findViewById(R.id.image_view));
    String tagImageStr = "current" + position + "imageView";
    imageView.setTag(tagImageStr);

    // video view
    VideoViewCustom videoView = ((VideoViewCustom) pagerView.findViewById(R.id.video_view));
    String tagVideoStr = "current" + position + "videoView";
    videoView.setTag(tagVideoStr);

    ProgressBar spinner = (ProgressBar) pagerView.findViewById(R.id.loading);

    // link web view
    CustomWebView linkWebView = ((CustomWebView) pagerView.findViewById(R.id.link_web_view));
    String tagStr = "current" + position + "linkWebView";
    linkWebView.setTag(tagStr);

    // line view
    View line_view = pagerView.findViewById(R.id.line_view);

    // text group
    ViewGroup textGroup = (ViewGroup) pagerView.findViewById(R.id.textGroup);

    // Set tag for text web view
    CustomWebView textWebView = ((CustomWebView) textGroup.findViewById(R.id.textBody));

    // set accessibility
    textGroup.setContentDescription(act.getResources().getString(R.string.note_text));
    textWebView.getRootView().setContentDescription(act.getResources().getString(R.string.note_text));

    tagStr = "current" + position + "textWebView";
    textWebView.setTag(tagStr);

    // set text web view
    setWebView(textWebView, spinner, CustomWebView.TEXT_VIEW);

    String linkUri = db_page.getNoteLinkUri(position, true);
    String strTitle = db_page.getNoteTitle(position, true);
    String strBody = db_page.getNoteBody(position, true);

    // View mode
    // picture only
    if (Note.isPictureMode()) {
        System.out.println("Note_adapter / _instantiateItem / isPictureMode ");
        pictureGroup.setVisibility(View.VISIBLE);
        showPictureView(position, imageView, videoView, linkWebView, spinner);

        line_view.setVisibility(View.GONE);
        textGroup.setVisibility(View.GONE);
    }
    // text only
    else if (Note.isTextMode()) {
        System.out.println("Note_adapter / _instantiateItem / isTextMode ");
        pictureGroup.setVisibility(View.GONE);

        line_view.setVisibility(View.VISIBLE);
        textGroup.setVisibility(View.VISIBLE);

        if (Util.isYouTubeLink(linkUri) || !Util.isEmptyString(strTitle) || !Util.isEmptyString(strBody)
                || linkUri.startsWith("http")) {
            showTextWebView(position, textWebView);
        }
    }
    // picture and text
    else if (Note.isViewAllMode()) {
        System.out.println("Note_adapter / _instantiateItem / isViewAllMode ");

        // picture
        pictureGroup.setVisibility(View.VISIBLE);
        showPictureView(position, imageView, videoView, linkWebView, spinner);

        line_view.setVisibility(View.VISIBLE);
        textGroup.setVisibility(View.VISIBLE);

        // text
        if (!Util.isEmptyString(strTitle) || !Util.isEmptyString(strBody) || Util.isYouTubeLink(linkUri)
                || linkUri.startsWith("http")) {
            showTextWebView(position, textWebView);
        } else {
            textGroup.setVisibility(View.GONE);
        }
    }

    // footer of note view
    TextView footerText = (TextView) pagerView.findViewById(R.id.note_view_footer);
    if (!Note.isPictureMode()) {
        footerText.setVisibility(View.VISIBLE);
        footerText.setText(String.valueOf(position + 1) + "/" + pager.getAdapter().getCount());
        footerText.setTextColor(ColorSet.mText_ColorArray[Note.mStyle]);
        footerText.setBackgroundColor(ColorSet.mBG_ColorArray[Note.mStyle]);
    } else
        footerText.setVisibility(View.GONE);

    container.addView(pagerView, 0);

    return pagerView;
}

From source file:com.cachirulop.moneybox.activity.MovementDetailActivity.java

/**
 * Change the visibility of the amount fields, including the title.
 * //from w w w . j  ava 2s .c  o m
 * @param visible
 *            Tells if the fields should be visible (true) or not (false)
 */
private void setVisibleAmount(boolean visible) {
    TextView txt;
    Spinner spn;
    int visibility;

    if (visible) {
        visibility = View.VISIBLE;
    } else {
        visibility = View.GONE;
    }

    txt = (TextView) findViewById(R.id.AmountDesc);
    txt.setVisibility(visibility);

    spn = (Spinner) findViewById(R.id.sAmount);
    spn.setVisibility(visibility);
}

From source file:android_network.hetnet.vpn_service.ActivityLog.java

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

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

    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);
    boolean log = prefs.getBoolean("log", false);

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

    // Set enabled switch
    swEnabled.setChecked(log);
    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);

    // -- the adapter holds rows of data entries -> AdapterLog class
    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));
    }

    // -- when clicking the log items
    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, MainActivity.class);
                        main.putExtra(MainActivity.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:
                        if (true) {
                            DatabaseHelper.getInstance(ActivityLog.this).updateAccess(packet, dname, 0);
                            ServiceSinkhole.reload("allow host", ActivityLog.this);
                            Intent main = new Intent(ActivityLog.this, MainActivity.class);
                            main.putExtra(MainActivity.EXTRA_SEARCH, Integer.toString(uid));
                            startActivity(main);
                        }

                        return true;

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

                    default:
                        return false;
                    }
                }
            });

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

    live = true;
}