Example usage for android.database Cursor isNull

List of usage examples for android.database Cursor isNull

Introduction

In this page you can find the example usage for android.database Cursor isNull.

Prototype

boolean isNull(int columnIndex);

Source Link

Document

Returns true if the value in the indicated column is null.

Usage

From source file:org.mozilla.gecko.home.HistoryPanel.java

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    mList = (HomeListView) view.findViewById(R.id.list);
    mList.setTag(HomePager.LIST_TAG_HISTORY);

    mList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override//ww w . j  ava  2  s  .c  o m
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            position -= mAdapter.getMostRecentSectionsCountBefore(position);
            final Cursor c = mAdapter.getCursor(position);
            final String url = c.getString(c.getColumnIndexOrThrow(History.URL));

            Telemetry.sendUIEvent(TelemetryContract.Event.LOAD_URL, TelemetryContract.Method.LIST_ITEM);

            // This item is a TwoLinePageRow, so we allow switch-to-tab.
            mUrlOpenListener.onUrlOpen(url, EnumSet.of(OnUrlOpenListener.Flags.ALLOW_SWITCH_TO_TAB));
        }
    });

    mList.setContextMenuInfoFactory(new HomeContextMenuInfo.Factory() {
        @Override
        public HomeContextMenuInfo makeInfoForCursor(View view, int position, long id, Cursor cursor) {
            final HomeContextMenuInfo info = new HomeContextMenuInfo(view, position, id);
            info.url = cursor.getString(cursor.getColumnIndexOrThrow(Combined.URL));
            info.title = cursor.getString(cursor.getColumnIndexOrThrow(Combined.TITLE));
            info.historyId = cursor.getInt(cursor.getColumnIndexOrThrow(Combined.HISTORY_ID));
            info.itemType = RemoveItemType.HISTORY;
            final int bookmarkIdCol = cursor.getColumnIndexOrThrow(Combined.BOOKMARK_ID);
            if (cursor.isNull(bookmarkIdCol)) {
                // If this is a combined cursor, we may get a history item without a
                // bookmark, in which case the bookmarks ID column value will be null.
                info.bookmarkId = -1;
            } else {
                info.bookmarkId = cursor.getInt(bookmarkIdCol);
            }
            return info;
        }
    });
    registerForContextMenu(mList);

    mClearHistoryButton = view.findViewById(R.id.clear_history_button);
    mClearHistoryButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final Context context = getActivity();

            final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
            dialogBuilder.setMessage(R.string.home_clear_history_confirm);

            dialogBuilder.setNegativeButton(R.string.button_cancel, new AlertDialog.OnClickListener() {
                @Override
                public void onClick(final DialogInterface dialog, final int which) {
                    dialog.dismiss();
                }
            });

            dialogBuilder.setPositiveButton(R.string.button_ok, new AlertDialog.OnClickListener() {
                @Override
                public void onClick(final DialogInterface dialog, final int which) {
                    dialog.dismiss();

                    // Send message to Java to clear history.
                    final JSONObject json = new JSONObject();
                    try {
                        json.put("history", true);
                    } catch (JSONException e) {
                        Log.e(LOGTAG, "JSON error", e);
                    }

                    GeckoAppShell.sendEventToGecko(
                            GeckoEvent.createBroadcastEvent("Sanitize:ClearData", json.toString()));

                    Telemetry.sendUIEvent(TelemetryContract.Event.SANITIZE, TelemetryContract.Method.BUTTON,
                            "history");
                }
            });

            dialogBuilder.show();
        }
    });
}

From source file:ch.berta.fabio.popularmovies.data.repositories.MovieRepositoryImpl.java

@Override
public Movie getMovieFromFavMovieDetailsCursor(@NonNull Cursor cursor) {
    final int dbId = cursor.getInt(COL_INDEX_MOVIE_DETAILS_DB_ID);
    final String title = cursor.getString(COL_INDEX_MOVIE_DETAILS_TITLE);
    final Date releaseDate = new Date(cursor.getLong(COL_INDEX_MOVIE_DETAILS_RELEASE_DATE));
    final String poster = cursor.getString(COL_INDEX_MOVIE_DETAILS_POSTER);
    final String backdrop = cursor.getString(COL_INDEX_MOVIE_DETAILS_BACKDROP);
    final String plot = cursor.getString(COL_INDEX_MOVIE_DETAILS_PLOT);
    final double rating = cursor.getDouble(COL_INDEX_MOVIE_DETAILS_VOTE_AVERAGE);

    List<Review> reviews = new ArrayList<>();
    int reviewIdCounter = 0;
    List<Video> videos = new ArrayList<>();
    int videoIdCounter = 0;
    do {/*from  w ww. j av  a  2  s.  co m*/
        if (!cursor.isNull(COL_INDEX_MOVIE_DETAILS_REVIEW_ID)) {
            final int id = cursor.getInt(COL_INDEX_MOVIE_DETAILS_REVIEW_ID);
            final String author = cursor.getString(COL_INDEX_MOVIE_DETAILS_REVIEW_AUTHOR);
            final String content = cursor.getString(COL_INDEX_MOVIE_DETAILS_REVIEW_CONTENT);
            final String url = cursor.getString(COL_INDEX_MOVIE_DETAILS_REVIEW_URL);

            if (id > reviewIdCounter) {
                reviewIdCounter = id;
                reviews.add(new Review(author, content, url));
            }
        }

        if (!cursor.isNull(COL_INDEX_MOVIE_DETAILS_VIDEO_ID)) {
            final int id = cursor.getInt(COL_INDEX_MOVIE_DETAILS_VIDEO_ID);
            final String name = cursor.getString(COL_INDEX_MOVIE_DETAILS_VIDEO_NAME);
            final String key = cursor.getString(COL_INDEX_MOVIE_DETAILS_VIDEO_KEY);
            final String site = cursor.getString(COL_INDEX_MOVIE_DETAILS_VIDEO_SITE);
            final int size = cursor.getInt(COL_INDEX_MOVIE_DETAILS_VIDEO_SIZE);
            final String type = cursor.getString(COL_INDEX_MOVIE_DETAILS_VIDEO_TYPE);

            if (id > videoIdCounter) {
                videoIdCounter = id;
                videos.add(new Video(name, key, site, size, type));
            }
        }
    } while (cursor.moveToNext());

    return new Movie(videos, backdrop, dbId, plot, releaseDate, poster, title, rating, reviews, true);
}

From source file:org.odk.collect.android.tasks.InstanceSyncTask.java

@Override
protected String doInBackground(Void... params) {
    int instance = ++counter;
    Timber.i("[%d] doInBackground begins!", instance);

    try {//from  w w w . ja v a 2  s  . c  o  m
        List<String> candidateInstances = new LinkedList<String>();
        File instancesPath = new File(Collect.INSTANCES_PATH);
        if (instancesPath.exists() && instancesPath.isDirectory()) {
            File[] instanceFolders = instancesPath.listFiles();
            if (instanceFolders.length == 0) {
                Timber.i("[%d] Empty instance folder. Stopping scan process.", instance);
                Timber.d(Collect.getInstance().getString(R.string.instance_scan_completed));
                return currentStatus;
            }

            // Build the list of potential path that we need to add to the content provider
            for (File instanceDir : instanceFolders) {
                File instanceFile = new File(instanceDir, instanceDir.getName() + ".xml");
                if (!instanceFile.exists()) {
                    // Look for submission file that might have been manually copied from e.g. Briefcase
                    File submissionFile = new File(instanceDir, "submission.xml");
                    if (submissionFile.exists()) {
                        submissionFile.renameTo(instanceFile);
                    }
                }
                if (instanceFile.exists() && instanceFile.canRead()) {
                    candidateInstances.add(instanceFile.getAbsolutePath());
                } else {
                    Timber.i("[%d] Ignoring: %s", instance, instanceDir.getAbsolutePath());
                }
            }
            Collections.sort(candidateInstances);

            List<String> filesToRemove = new ArrayList<>();

            // Remove all the path that's already in the content provider
            Cursor instanceCursor = null;
            InstancesDao instancesDao = new InstancesDao();
            try {
                String sortOrder = InstanceColumns.INSTANCE_FILE_PATH + " ASC ";
                instanceCursor = instancesDao.getSavedInstancesCursor(sortOrder);
                if (instanceCursor == null) {
                    Timber.e("[%d] Instance content provider returned null", instance);
                    return currentStatus;
                }

                instanceCursor.moveToPosition(-1);

                while (instanceCursor.moveToNext()) {
                    String instanceFilename = instanceCursor
                            .getString(instanceCursor.getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH));
                    String instanceStatus = instanceCursor
                            .getString(instanceCursor.getColumnIndex(InstanceColumns.STATUS));
                    if (candidateInstances.contains(instanceFilename)
                            || instanceStatus.equals(InstanceProviderAPI.STATUS_SUBMITTED)) {
                        candidateInstances.remove(instanceFilename);
                    } else {
                        filesToRemove.add(instanceFilename);
                    }
                }

            } finally {
                if (instanceCursor != null) {
                    instanceCursor.close();
                }
            }

            instancesDao.deleteInstancesFromIDs(filesToRemove);

            final boolean instanceSyncFlag = PreferenceManager
                    .getDefaultSharedPreferences(Collect.getInstance().getApplicationContext())
                    .getBoolean(GeneralKeys.KEY_INSTANCE_SYNC, true);

            int counter = 0;
            // Begin parsing and add them to the content provider
            for (String candidateInstance : candidateInstances) {
                String instanceFormId = getFormIdFromInstance(candidateInstance);
                // only process if we can find the id from the instance file
                if (instanceFormId != null) {
                    Cursor formCursor = null;
                    try {
                        String selection = FormsColumns.JR_FORM_ID + " = ? ";
                        String[] selectionArgs = new String[] { instanceFormId };
                        // retrieve the form definition
                        formCursor = new FormsDao().getFormsCursor(selection, selectionArgs);
                        // TODO: optimize this by caching the previously found form definition
                        // TODO: optimize this by caching unavailable form definition to skip
                        if (formCursor != null && formCursor.moveToFirst()) {
                            String submissionUri = null;
                            if (!formCursor.isNull(formCursor.getColumnIndex(FormsColumns.SUBMISSION_URI))) {
                                submissionUri = formCursor
                                        .getString(formCursor.getColumnIndex(FormsColumns.SUBMISSION_URI));
                            }
                            String jrFormId = formCursor
                                    .getString(formCursor.getColumnIndex(FormsColumns.JR_FORM_ID));
                            String jrVersion = formCursor
                                    .getString(formCursor.getColumnIndex(FormsColumns.JR_VERSION));
                            String formName = formCursor
                                    .getString(formCursor.getColumnIndex(FormsColumns.DISPLAY_NAME));

                            // add missing fields into content values
                            ContentValues values = new ContentValues();
                            values.put(InstanceColumns.INSTANCE_FILE_PATH, candidateInstance);
                            values.put(InstanceColumns.SUBMISSION_URI, submissionUri);
                            values.put(InstanceColumns.DISPLAY_NAME, formName);
                            values.put(InstanceColumns.JR_FORM_ID, jrFormId);
                            values.put(InstanceColumns.JR_VERSION, jrVersion);
                            values.put(InstanceColumns.STATUS,
                                    instanceSyncFlag ? InstanceProviderAPI.STATUS_COMPLETE
                                            : InstanceProviderAPI.STATUS_INCOMPLETE);
                            values.put(InstanceColumns.CAN_EDIT_WHEN_COMPLETE, Boolean.toString(true));
                            // save the new instance object

                            instancesDao.saveInstance(values);
                            counter++;

                            encryptInstanceIfNeeded(formCursor, candidateInstance, values, instancesDao);
                        }
                    } catch (IOException | EncryptionException e) {
                        Timber.w(e);
                    } finally {
                        if (formCursor != null) {
                            formCursor.close();
                        }
                    }
                }
            }
            if (counter > 0) {
                currentStatus += String.format(Collect.getInstance().getString(R.string.instance_scan_count),
                        counter);
            }
        }
    } finally {
        Timber.i("[%d] doInBackground ends!", instance);
    }
    return currentStatus;
}

From source file:org.dvbviewer.controller.ui.fragments.ChannelList.java

/**
 * Cursor to timer.//from  w  w  w . j ava  2s  .  co m
 *
 * @param c the c
 * @return the timer
 * @author RayBa
 * @date 07.04.2013
 */
private Timer cursorToTimer(Cursor c) {
    String name = c.getString(c.getColumnIndex(ChannelTbl.NAME));
    long channelID = c.getLong(c.getColumnIndex(ChannelTbl._ID));
    String epgTitle = !c.isNull(c.getColumnIndex(EpgTbl.TITLE)) ? c.getString(c.getColumnIndex(EpgTbl.TITLE))
            : name;
    long epgStart = c.getLong(c.getColumnIndex(EpgTbl.START));
    long epgEnd = c.getLong(c.getColumnIndex(EpgTbl.END));
    DVBViewerPreferences prefs = new DVBViewerPreferences(getSherlockActivity());
    int epgBefore = prefs.getPrefs().getInt(DVBViewerPreferences.KEY_TIMER_TIME_BEFORE, 5);
    int epgAfter = prefs.getPrefs().getInt(DVBViewerPreferences.KEY_TIMER_TIME_AFTER, 5);
    Date start = epgStart > 0 ? new Date(epgStart) : new Date();
    Date end = epgEnd > 0 ? new Date(epgEnd) : new Date(start.getTime() + (1000 * 60 * 120));
    Log.i(ChannelList.class.getSimpleName(), "start: " + start.toString());
    Log.i(ChannelList.class.getSimpleName(), "end: " + end.toString());
    start = DateUtils.addMinutes(start, 0 - epgBefore);
    end = DateUtils.addMinutes(end, epgAfter);
    Timer timer = new Timer();
    timer.setTitle(epgTitle);
    timer.setChannelId(channelID);
    timer.setChannelName(name);
    timer.setStart(start);
    timer.setEnd(end);
    timer.setTimerAction(prefs.getPrefs().getInt(DVBViewerPreferences.KEY_TIMER_DEF_AFTER_RECORD, 0));
    return timer;
}

From source file:org.jamienicol.episodes.EpisodeDetailsFragment.java

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    if (data != null && data.moveToFirst()) {

        final int seasonNumberColumnIndex = data.getColumnIndexOrThrow(EpisodesTable.COLUMN_SEASON_NUMBER);
        final int seasonNumber = data.getInt(seasonNumberColumnIndex);
        final int episodeNumberColumnIndex = data.getColumnIndexOrThrow(EpisodesTable.COLUMN_EPISODE_NUMBER);
        final int episodeNumber = data.getInt(episodeNumberColumnIndex);

        final int titleColumnIndex = data.getColumnIndexOrThrow(EpisodesTable.COLUMN_NAME);
        final String title = data.getString(titleColumnIndex);

        String titleText = "";
        if (seasonNumber != 0) {
            titleText += getActivity().getString(R.string.season_episode_prefix, seasonNumber, episodeNumber);
        }/*from   w ww .ja va2s.c  o m*/
        titleText += title;
        titleView.setText(titleText);

        final int overviewColumnIndex = data.getColumnIndexOrThrow(EpisodesTable.COLUMN_OVERVIEW);
        if (data.isNull(overviewColumnIndex)) {
            overviewView.setText("");
        } else {
            overviewView.setText(data.getString(overviewColumnIndex).trim());
        }

        final int firstAiredColumnIndex = data.getColumnIndexOrThrow(EpisodesTable.COLUMN_FIRST_AIRED);
        if (data.isNull(firstAiredColumnIndex)) {
            dateView.setText("");
        } else {
            final Date date = new Date(data.getLong(firstAiredColumnIndex) * 1000);
            final String dateText = DateFormat.getDateInstance(DateFormat.LONG).format(date);
            dateView.setText(dateText);
        }

        final int watchedColumnIndex = data.getColumnIndexOrThrow(EpisodesTable.COLUMN_WATCHED);
        watched = data.getInt(watchedColumnIndex) > 0 ? true : false;
        watchedCheckBox.setChecked(watched);

        rootView.setVisibility(View.VISIBLE);
    } else {
        rootView.setVisibility(View.INVISIBLE);
    }
}

From source file:org.sufficientlysecure.keychain.ui.adapter.SelectKeyCursorAdapter.java

@Override
public void bindView(View view, Context context, Cursor cursor) {
    Highlighter highlighter = new Highlighter(context, mQuery);
    ViewHolderItem h = (ViewHolderItem) view.getTag();

    String userId = cursor.getString(mIndexUserId);
    String[] userIdSplit = PgpKeyHelper.splitUserId(userId);

    if (userIdSplit[0] != null) {
        h.mainUserId.setText(highlighter.highlight(userIdSplit[0]));
    } else {/*from w w w .  j av a 2s .  co m*/
        h.mainUserId.setText(R.string.user_id_no_name);
    }
    if (userIdSplit[1] != null) {
        h.mainUserIdRest.setVisibility(View.VISIBLE);
        h.mainUserIdRest.setText(highlighter.highlight(userIdSplit[1]));
    } else {
        h.mainUserIdRest.setVisibility(View.GONE);
    }

    long masterKeyId = cursor.getLong(mIndexMasterKeyId);
    h.keyId.setText(PgpKeyHelper.convertKeyIdToHex(masterKeyId));

    boolean enabled = true;
    if (cursor.getInt(mIndexRevoked) != 0) {
        h.status.setText(R.string.revoked);
        enabled = false;
    } else if (!cursor.isNull(mIndexExpiry)
            && new Date(cursor.getLong(mIndexExpiry) * 1000).before(new Date())) {
        h.status.setText(R.string.expired);
        enabled = false;
    } else {
        h.status.setText("");
    }

    h.status.setTag(enabled);
}

From source file:com.android.messaging.datamodel.BugleDatabaseOperations.java

/**
 * Get the thread id for an existing conversation from the local DB.
 *
 * @param dbWrapper The database/*from   ww w  .j a  va 2 s .  c  om*/
 * @param conversationId The conversation to look up thread for
 * @return The thread id. Returns -1 if the conversation was not found or if it was found
 * but the thread column was NULL.
 */
@DoesNotRunOnMainThread
public static long getThreadId(final DatabaseWrapper dbWrapper, final String conversationId) {
    Assert.isNotMainThread();
    long threadId = -1;

    Cursor cursor = null;
    try {
        cursor = dbWrapper.query(DatabaseHelper.CONVERSATIONS_TABLE,
                new String[] { ConversationColumns.SMS_THREAD_ID }, ConversationColumns._ID + " =?",
                new String[] { conversationId }, null, null, null);

        if (cursor.moveToFirst()) {
            Assert.isTrue(cursor.getCount() == 1);
            if (!cursor.isNull(0)) {
                threadId = cursor.getLong(0);
            }
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

    return threadId;
}

From source file:org.m2x.rssreader.service.FetcherService.java

private void downloadAllImages() {
    ContentResolver cr = MainApplication.getContext().getContentResolver();
    Cursor cursor = cr.query(TaskColumns.CONTENT_URI,
            new String[] { TaskColumns._ID, TaskColumns.ENTRY_ID, TaskColumns.IMG_URL_TO_DL,
                    TaskColumns.NUMBER_ATTEMPT },
            TaskColumns.IMG_URL_TO_DL + Constants.DB_IS_NOT_NULL, null, null);

    ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();

    while (cursor.moveToNext()) {
        long taskId = cursor.getLong(0);
        long entryId = cursor.getLong(1);
        String imgPath = cursor.getString(2);
        int nbAttempt = 0;
        if (!cursor.isNull(3)) {
            nbAttempt = cursor.getInt(3);
        }/*www .  ja  v a  2 s  .  c o  m*/

        try {
            NetworkUtils.downloadImage(entryId, imgPath);

            // If we are here, everything is OK
            operations.add(ContentProviderOperation.newDelete(TaskColumns.CONTENT_URI(taskId)).build());
            cr.notifyChange(EntryColumns.CONTENT_URI(entryId), null); // To refresh the view
        } catch (Exception e) {
            if (nbAttempt + 1 > MAX_TASK_ATTEMPT) {
                operations.add(ContentProviderOperation.newDelete(TaskColumns.CONTENT_URI(taskId)).build());
            } else {
                ContentValues values = new ContentValues();
                values.put(TaskColumns.NUMBER_ATTEMPT, nbAttempt + 1);
                operations.add(ContentProviderOperation.newUpdate(TaskColumns.CONTENT_URI(taskId))
                        .withValues(values).build());
            }
        }
    }

    cursor.close();

    if (!operations.isEmpty()) {
        try {
            cr.applyBatch(FeedData.AUTHORITY, operations);
        } catch (Throwable ignored) {
        }
    }
}

From source file:com.master.metehan.filtereagle.ActivityLog.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    Util.setTheme(this);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.logging);/*from   w w w.j a  va  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);

    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:
                        if (IAB.isPurchased(ActivityPro.SKU_FILTER, ActivityLog.this)) {
                            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);
                        } else
                            startActivity(new Intent(ActivityLog.this, ActivityPro.class));
                        return true;

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

                    default:
                        return false;
                    }
                }
            });

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

    live = true;
}

From source file:eu.faircode.adblocker.ActivityLog.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    Util.setTheme(this);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.logging);/*from  w ww .  j  ava2s.  c  o m*/
    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);

    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, dport));

            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:
                        if (IAB.isPurchased(ActivityPro.SKU_FILTER, ActivityLog.this)) {
                            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);
                        } else
                            startActivity(new Intent(ActivityLog.this, ActivityPro.class));
                        return true;

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

                    default:
                        return false;
                    }
                }
            });

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

    live = true;
}