Example usage for android.widget TextView setTag

List of usage examples for android.widget TextView setTag

Introduction

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

Prototype

public void setTag(final Object tag) 

Source Link

Document

Sets the tag associated with this view.

Usage

From source file:pro.dbro.bart.TheActivity.java

public void displayRouteResponse(routeResponse routeResponse) {
    // Log.d("displayRouteResponse","Is this real?: "+routeResponse.toString());
    // Previously, if the device's locale wasn't in Pacific Standard Time
    // Responses with all expired routes could present, causing a looping refresh cycle
    // This is now remedied by coercing response dates into PST
    boolean expiredResponse = false;
    if (routeResponse.routes.size() == 0) {
        Log.d("displayRouteResponse", "no routes to display");
        expiredResponse = true;//from w ww  . java2  s .com
    }

    if (timer != null)
        timer.cancel(); // cancel previous timer
    timerViews = new ArrayList(); // release old ETA text views
    maxTimer = 0;
    try {
        tableLayout.removeAllViews();
        //Log.v("DATE",new Date().toString());
        long now = new Date().getTime();

        if (!expiredResponse) {
            fareTv.setVisibility(0);
            fareTv.setText("$" + routeResponse.routes.get(0).fare);
            for (int x = 0; x < routeResponse.routes.size(); x++) {
                route thisRoute = routeResponse.routes.get(x);

                TableRow tr = (TableRow) View.inflate(c, R.layout.tablerow, null);
                tr.setPadding(0, 20, 0, 0);
                LinearLayout legLayout = (LinearLayout) View.inflate(c, R.layout.routelinearlayout, null);

                for (int y = 0; y < thisRoute.legs.size(); y++) {
                    TextView trainTv = (TextView) View.inflate(c, R.layout.tabletext, null);
                    trainTv.setPadding(0, 0, 0, 0);
                    trainTv.setTextSize(20);
                    trainTv.setGravity(3); // set left gravity
                    // If route has multiple legs, generate "Transfer At [station name]" and "To [train name] " rows for each leg after the first
                    if (y > 0) {
                        trainTv.setText("transfer at " + BART.REVERSE_STATION_MAP
                                .get(((leg) thisRoute.legs.get(y - 1)).disembarkStation.toLowerCase()));
                        trainTv.setPadding(0, 0, 0, 0);
                        legLayout.addView(trainTv);
                        trainTv.setTextSize(14);
                        trainTv = (TextView) View.inflate(c, R.layout.tabletext, null);
                        trainTv.setPadding(0, 0, 0, 0);
                        trainTv.setTextSize(20);
                        trainTv.setGravity(3); // set left gravity
                        trainTv.setText("to " + BART.REVERSE_STATION_MAP
                                .get(((leg) thisRoute.legs.get(y)).trainHeadStation.toLowerCase()));
                    } else {
                        // For first route leg, display "Take [train name]" row
                        trainTv.setText("take "
                                + BART.REVERSE_STATION_MAP.get(((leg) thisRoute.legs.get(y)).trainHeadStation));
                    }

                    legLayout.addView(trainTv);

                }

                if (thisRoute.legs.size() == 1) {
                    legLayout.setPadding(0, 10, 0, 0); // Address detination train and ETA not aligning 
                }

                tr.addView(legLayout);

                // Prepare ETA TextView
                TextView arrivalTimeTv = (TextView) View.inflate(c, R.layout.tabletext, null);
                arrivalTimeTv.setPadding(10, 0, 0, 0);

                //Log.v("DEPART_DATE",thisRoute.departureDate.toString());

                // Don't report a train that may JUST be leaving with a negative ETA
                long eta;
                if (thisRoute.departureDate.getTime() - now <= 0) {
                    eta = 0;
                } else {
                    eta = thisRoute.departureDate.getTime() - now;
                }

                if (eta > maxTimer) {
                    maxTimer = eta;
                }
                // Set timeTv Tag to departure date for interpretation by ViewCountDownTimer
                arrivalTimeTv.setTag(thisRoute.departureDate.getTime());

                // Print arrival as time, not eta if greater than BART.ETA_THRESHOLD_MS
                if (thisRoute.departureDate.getTime() - now > BART.ETA_IN_MINUTES_THRESHOLD_MS) {
                    SimpleDateFormat sdf = new SimpleDateFormat("h:mm a");
                    arrivalTimeTv.setText(sdf.format(thisRoute.departureDate));
                    arrivalTimeTv.setTextSize(20);
                }
                // Display ETA as minutes until arrival
                else {
                    arrivalTimeTv.setTextSize(36);
                    // Display eta less than 1m as "<1"
                    if (eta < 60 * 1000)
                        arrivalTimeTv.setText("<1"); // TODO - remove this? Does countdown tick on start
                    else
                        arrivalTimeTv.setText(String.valueOf(eta / (1000 * 60))); // TODO - remove this? Does countdown tick on start
                    // Add the timerView to the list of views to be passed to the ViewCountDownTimer
                    timerViews.add(arrivalTimeTv);
                }

                //new ViewCountDownTimer(arrivalTimeTv, eta, 60*1000).start();
                tr.addView(arrivalTimeTv);
                // Set the Row View (containing train names and times) Tag to the route it represents
                tr.setTag(thisRoute);
                tableLayout.addView(tr);
                tr.setOnLongClickListener(new OnLongClickListener() {

                    @Override
                    public boolean onLongClick(View arg0) {
                        Log.d("RouteViewTag", ((route) arg0.getTag()).toString());
                        usherRoute = (route) arg0.getTag();
                        TextView guidanceTv = (TextView) View.inflate(c, R.layout.tabletext, null);
                        guidanceTv.setText(Html.fromHtml(getString(R.string.service_prompt)));
                        guidanceTv.setTextSize(18);
                        guidanceTv.setPadding(0, 0, 0, 0);
                        new AlertDialog.Builder(c).setTitle("Route Guidance").setIcon(R.drawable.ic_launcher)
                                .setView(guidanceTv).setPositiveButton(R.string.service_start_button,
                                        new DialogInterface.OnClickListener() {

                                            public void onClick(DialogInterface dialog, int which) {
                                                Intent i = new Intent(c, UsherService.class);
                                                //i.putExtra("departure", ((leg)usherRoute.legs.get(0)).boardStation);
                                                //Log.v("SERVICE","Starting");
                                                if (usherServiceIsRunning()) {
                                                    stopService(i);
                                                }
                                                startService(i);
                                            }

                                        })
                                .setNeutralButton("Cancel", null).show();
                        return true; // consumed the long click
                    }

                });
                tr.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        int index = tableLayout.indexOfChild(arg0); // index of clicked view. Expanded view will always be +1
                        route thisRoute = (route) arg0.getTag();
                        if (!thisRoute.isExpanded) { // if route not expanded
                            thisRoute.isExpanded = true;
                            LinearLayout routeDetail = (LinearLayout) View.inflate(c, R.layout.routedetail,
                                    null);
                            TextView arrivalTv = (TextView) View.inflate(c, R.layout.tabletext, null);
                            SimpleDateFormat curFormater = new SimpleDateFormat("h:mm a");
                            //arrivalTv.setTextColor(0xFFC9C7C8);
                            arrivalTv.setText("arrives " + curFormater.format(thisRoute.arrivalDate));
                            arrivalTv.setTextSize(20);
                            routeDetail.addView(arrivalTv);
                            ImageView bikeIv = (ImageView) View.inflate(c, R.layout.bikeimage, null);

                            if (!thisRoute.bikes) {
                                bikeIv.setImageResource(R.drawable.no_bicycle);
                            }
                            routeDetail.addView(bikeIv);
                            tableLayout.addView(routeDetail, index + 1);
                        } else {
                            thisRoute.isExpanded = false;
                            tableLayout.removeViewAt(index + 1);
                        }

                    }
                });
            } // end route iteration
        } // end expiredResponse check
          // expiredResponse == True
          // If a late-night routeResponse includes the next morning's routes, they will be
          // presented with HH:MM ETAs, instead of minutes
          // Else if a late-night routeResponse includes routes from earlier in the evening
          // We will display "This route has stopped for tonight"
        else {
            String message = "This route has stopped for tonight";
            TextView specialScheduleTextView = (TextView) View.inflate(c, R.layout.tabletext, null);
            specialScheduleTextView.setText(message);
            specialScheduleTextView.setPadding(0, 0, 0, 0);
            tableLayout.addView(specialScheduleTextView);
        }
        if (routeResponse.specialSchedule != null) {
            ImageView specialSchedule = (ImageView) View.inflate(c, R.layout.specialschedulelayout, null);
            specialSchedule.setTag(routeResponse.specialSchedule);
            specialSchedule.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    TextView specialScheduleTv = (TextView) View.inflate(c, R.layout.tabletext, null);
                    specialScheduleTv.setPadding(0, 0, 0, 0);
                    specialScheduleTv.setText(Html.fromHtml(arg0.getTag().toString()));
                    specialScheduleTv.setTextSize(16);
                    specialScheduleTv.setMovementMethod(LinkMovementMethod.getInstance());
                    new AlertDialog.Builder(c).setTitle("Route Alerts").setIcon(R.drawable.warning)
                            .setView(specialScheduleTv).setPositiveButton("Okay!", null).show();

                }

            });
            tableLayout.addView(specialSchedule);
        }
        // Don't set timer if response is expired
        if (!expiredResponse) {
            timer = new ViewCountDownTimer(timerViews, "route", maxTimer, 30 * 1000);
            timer.start();
        }
    } catch (Throwable t) {
        Log.d("displayRouteResponseError", t.getStackTrace().toString());
    }
}

From source file:com.github.irshulx.Components.InputExtensions.java

public void UpdateTextStyle(EditorTextStyle style, TextView editText) {
    /// String type = getControlType(getActiveView());
    try {/* www.  j a v a2  s  . co  m*/
        if (editText == null) {
            editText = (EditText) editorCore.getActiveView();
        }
        EditorControl tag = editorCore.getControlTag(editText);

        int pBottom = editText.getPaddingBottom();
        int pRight = editText.getPaddingRight();
        int pTop = editText.getPaddingTop();

        if (isEditorTextStyleHeaders(style)) {
            updateTextStyle(editText, style);
            return;
        }
        if (isEditorTextStyleContentStyles(style)) {
            boolean containsHeadertextStyle = containsHeaderTextStyle(tag);
            if (style == EditorTextStyle.BOLD) {
                boldifyText(tag, editText, containsHeadertextStyle ? HEADING : CONTENT);
            } else if (style == EditorTextStyle.ITALIC) {
                italicizeText(tag, editText, containsHeadertextStyle ? HEADING : CONTENT);
            }
            return;
        }
        if (style == EditorTextStyle.INDENT) {
            if (editorCore.containsStyle(tag.editorTextStyles, EditorTextStyle.INDENT)) {
                tag = editorCore.updateTagStyle(tag, EditorTextStyle.INDENT, Op.Delete);
                editText.setPadding(0, pTop, pRight, pBottom);
                editText.setTag(tag);
            } else {
                tag = editorCore.updateTagStyle(tag, EditorTextStyle.INDENT, Op.Insert);
                editText.setPadding(30, pTop, pRight, pBottom);
                editText.setTag(tag);
            }
        } else if (style == EditorTextStyle.OUTDENT) {
            if (editorCore.containsStyle(tag.editorTextStyles, EditorTextStyle.INDENT)) {
                tag = editorCore.updateTagStyle(tag, EditorTextStyle.INDENT, Op.Delete);
                editText.setPadding(0, pTop, pRight, pBottom);
                editText.setTag(tag);
            }
        } else if (style == EditorTextStyle.BLOCKQUOTE) {
            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) editText.getLayoutParams();
            if (editorCore.containsStyle(tag.editorTextStyles, EditorTextStyle.BLOCKQUOTE)) {
                tag = editorCore.updateTagStyle(tag, EditorTextStyle.BLOCKQUOTE, Op.Delete);
                editText.setPadding(0, pTop, pRight, pBottom);
                editText.setBackgroundDrawable(ContextCompat.getDrawable(this.editorCore.getContext(),
                        R.drawable.invisible_edit_text));
                params.setMargins(0, 0, 0, (int) editorCore.getContext().getResources()
                        .getDimension(R.dimen.edittext_margin_bottom));
            } else {
                float marginExtra = editorCore.getContext().getResources()
                        .getDimension(R.dimen.edittext_margin_bottom) * 1.5f;
                tag = editorCore.updateTagStyle(tag, EditorTextStyle.BLOCKQUOTE, Op.Insert);
                editText.setPadding(30, pTop, 30, pBottom);
                editText.setBackgroundDrawable(
                        editText.getContext().getResources().getDrawable(R.drawable.block_quote_background));
                params.setMargins(0, (int) marginExtra, 0, (int) marginExtra);
            }
            editText.setTag(tag);
        }
    } catch (Exception e) {

    }
}

From source file:com.egloos.hyunyi.musicinfo.LinkPopUp.java

private void displayArtistInfo_bk(JSONObject j) throws JSONException {
    if (imageLoader == null)
        imageLoader = ImageLoader.getInstance();
    if (!imageLoader.isInited())
        imageLoader.init(config);//  w w w. j av a2  s  .  c o  m

    Log.i("musicInfo", "LinkPopUp. displayArtistInfo " + j.toString());

    JSONObject j_artist_info = j.getJSONObject("artist");

    tArtistName.setText(j_artist_info.getString("name"));
    final JSONObject urls = j_artist_info.optJSONObject("urls");
    final JSONArray videos = j_artist_info.optJSONArray("video");
    final JSONArray images = j_artist_info.optJSONArray("images");
    final String fm_image = j.optString("fm_image");
    final JSONArray available_images = new JSONArray();
    ArrayList<String> image_urls = new ArrayList<String>();

    if (fm_image != null) {
        image_urls.add(fm_image);
    }

    Log.i("musicInfo", images.toString());

    if (images != null) {
        for (int i = 0; i < images.length(); i++) {
            JSONObject image = images.getJSONObject(i);
            int width = image.optInt("width", 0);
            int height = image.optInt("height", 0);
            String url = image.optString("url", "");
            Log.i("musicInfo", i + ": " + url);
            if ((width * height > 10000) && (width * height < 100000) && (!url.contains("userserve-ak"))) {
                //if ((width>300&&width<100)&&(height>300&&height<1000)&&(!url.contains("userserve-ak"))) {
                image_urls.add(url);
                Log.i("musicInfo", "Selected: " + url);
                //available_images.put(image);
            }
        }

        int random = (int) (Math.random() * image_urls.size());
        final String f_url = image_urls.get(random);

        //int random = (int) (Math.random() * available_images.length());
        //final JSONObject fImage = available_images.length()>0?available_images.getJSONObject(random > images.length() ? 0 : random):images.getJSONObject(0);

        Log.i("musicInfo",
                "Total image#=" + available_images.length() + " Selected image#=" + random + " " + f_url);

        imageLoader.displayImage(f_url, ArtistImage, new ImageLoadingListener() {
            @Override
            public void onLoadingStarted(String imageUri, View view) {

            }

            @Override
            public void onLoadingFailed(String imageUri, View view, FailReason failReason) {

            }

            @Override
            public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {

                lLinkList.removeAllViews();
                //String attr = fImage.optJSONObject("license").optString("attribution");
                //tAttribution.setText("Credit. " + ((attr == null) || (attr.contains("n/a")) ? "Unknown" : attr));
                if (urls != null) {
                    String[] jsonName = { "wikipedia_url", "mb_url", "lastfm_url", "official_url",
                            "twitter_url" };
                    for (int i = 0; i < jsonName.length; i++) {
                        if ((urls.optString(jsonName[i]) != null) && (urls.optString(jsonName[i]) != "")) {
                            Log.d("musicinfo", "Link URL: " + urls.optString(jsonName[i]));
                            TextView tv = new TextView(getApplicationContext());
                            tv.setTextSize(11);
                            tv.setPadding(16, 16, 16, 16);
                            tv.setTextColor(Color.LTGRAY);
                            tv.setTypeface(Typeface.SANS_SERIF);
                            tv.setGravity(Gravity.CENTER_VERTICAL);
                            tv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                                    ViewGroup.LayoutParams.WRAP_CONTENT));

                            switch (jsonName[i]) {
                            case "official_url":
                                tv.setText("HOME.");
                                break;
                            case "wikipedia_url":
                                tv.setText("WIKI.");
                                break;
                            case "mb_url":
                                tv.setText("Music Brainz.");
                                break;
                            case "lastfm_url":
                                tv.setText("Last FM.");
                                break;
                            case "twitter_url":
                                tv.setText("Twitter.");
                                break;
                            }

                            try {
                                tv.setTag(urls.getString(jsonName[i]));
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                            tv.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Intent intent = new Intent();
                                    intent.setAction(Intent.ACTION_VIEW);
                                    intent.addCategory(Intent.CATEGORY_BROWSABLE);
                                    intent.setData(Uri.parse((String) v.getTag()));
                                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    startActivity(intent);
                                    Toast.makeText(getApplicationContext(), "Open the Link...",
                                            Toast.LENGTH_SHORT).show();
                                    //finish();
                                }
                            });
                            lLinkList.addView(tv);
                        }
                    }
                } else {
                    TextView tv = new TextView(getApplicationContext());
                    tv.setTextSize(11);
                    tv.setPadding(16, 16, 16, 16);
                    tv.setTextColor(Color.LTGRAY);
                    tv.setTypeface(Typeface.SANS_SERIF);
                    tv.setGravity(Gravity.CENTER_VERTICAL);
                    tv.setText("Sorry, No Link Here...");
                    lLinkList.addView(tv);
                }

                if (videos != null) {
                    jVideoArray = videos;
                    mAdapter = new StaggeredViewAdapter(getApplicationContext(),
                            android.R.layout.simple_list_item_1, generateImageData(videos));
                    //if (mData == null) {
                    mData = generateImageData(videos);
                    //}

                    //mAdapter.clear();

                    for (JSONObject data : mData) {
                        mAdapter.add(data);
                    }
                    mGridView.setAdapter(mAdapter);
                } else {

                }

                adjBottomColor(((ImageView) view).getDrawable());
            }

            @Override
            public void onLoadingCancelled(String imageUri, View view) {

            }
        });
    }

}

From source file:group.pals.android.lib.ui.filechooser.FragmentFiles.java

/**
 * As the name means.// ww  w  .  ja v  a  2 s .  c o m
 */
private void buildAddressBar(final Uri path) {
    if (path == null)
        return;

    mViewAddressBar.removeAllViews();

    new LoadingDialog<Void, Cursor, Void>(getActivity(), false) {

        LinearLayout.LayoutParams lpBtnLoc;
        LinearLayout.LayoutParams lpDivider;
        LayoutInflater inflater = getLayoutInflater(null);
        final int dim = getResources().getDimensionPixelSize(R.dimen.afc_5dp);
        int count = 0;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            lpBtnLoc = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);
            lpBtnLoc.gravity = Gravity.CENTER;
        }// onPreExecute()

        @Override
        protected Void doInBackground(Void... params) {
            Cursor cursor = getActivity().getContentResolver().query(path, null, null, null, null);
            while (cursor != null) {
                if (cursor.moveToFirst()) {
                    publishProgress(cursor);
                    cursor.close();
                } else
                    break;

                /*
                 * Process the parent directory.
                 */
                Uri uri = Uri.parse(cursor.getString(cursor.getColumnIndex(BaseFile.COLUMN_URI)));
                cursor = getActivity().getContentResolver()
                        .query(BaseFile.genContentUriApi(uri.getAuthority()).buildUpon()
                                .appendPath(BaseFile.CMD_GET_PARENT)
                                .appendQueryParameter(BaseFile.PARAM_SOURCE, uri.getLastPathSegment()).build(),
                                null, null, null, null);
            } // while

            return null;
        }// doInBackground()

        @Override
        protected void onProgressUpdate(Cursor... progress) {
            /*
             * Add divider.
             */
            if (mViewAddressBar.getChildCount() > 0) {
                View divider = inflater.inflate(R.layout.afc_view_locations_divider, null);

                if (lpDivider == null) {
                    lpDivider = new LinearLayout.LayoutParams(dim, dim);
                    lpDivider.gravity = Gravity.CENTER;
                    lpDivider.setMargins(dim, dim, dim, dim);
                }
                mViewAddressBar.addView(divider, 0, lpDivider);
            }

            Uri lastUri = Uri.parse(progress[0].getString(progress[0].getColumnIndex(BaseFile.COLUMN_URI)));

            TextView btnLoc = (TextView) inflater.inflate(R.layout.afc_button_location, null);
            String name = BaseFileProviderUtils.getFileName(progress[0]);
            btnLoc.setText(TextUtils.isEmpty(name) ? getString(R.string.afc_root) : name);
            btnLoc.setTag(lastUri);
            btnLoc.setOnClickListener(mBtnLocationOnClickListener);
            btnLoc.setOnLongClickListener(mBtnLocationOnLongClickListener);
            mViewAddressBar.addView(btnLoc, 0, lpBtnLoc);

            if (count++ == 0) {
                Rect r = new Rect();
                btnLoc.getPaint().getTextBounds(name, 0, name.length(), r);
                if (r.width() >= getResources().getDimensionPixelSize(R.dimen.afc_button_location_max_width)
                        - btnLoc.getPaddingLeft() - btnLoc.getPaddingRight()) {
                    mTextFullDirName
                            .setText(progress[0].getString(progress[0].getColumnIndex(BaseFile.COLUMN_NAME)));
                    mTextFullDirName.setVisibility(View.VISIBLE);
                } else
                    mTextFullDirName.setVisibility(View.GONE);
            } // if
        }// onProgressUpdate()

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

            /*
             * Sometimes without delay time, it doesn't work...
             */
            mViewLocationsContainer.postDelayed(new Runnable() {

                public void run() {
                    mViewLocationsContainer.fullScroll(HorizontalScrollView.FOCUS_RIGHT);
                }// run()
            }, DisplayPrefs.DELAY_TIME_FOR_VERY_SHORT_ANIMATION);
        }// onPostExecute()

    }.execute();
}

From source file:com.egloos.hyunyi.musicinfo.LinkPopUp.java

private void displayArtistInfo(JSONObject j) throws JSONException {
    if (imageLoader == null)
        imageLoader = ImageLoader.getInstance();
    if (!imageLoader.isInited())
        imageLoader.init(config);/*from  w ww .  jav  a  2 s .  c o m*/

    Log.i("musicInfo", "LinkPopUp. displayArtistInfo " + j.toString());

    //JSONObject j_artist_info = j.getJSONObject("artist");

    final String artist_name = j.getString("name");

    tArtistName.setText(artist_name);
    final JSONObject urls = j.optJSONObject("urls");
    final JSONArray videos = j.optJSONArray("video");
    final JSONArray images = j.optJSONArray("images");

    final String msg = artist_name.replaceAll("\\p{Punct}", " ").replaceAll("\\p{Space}", "+");

    AsyncHttpClient client = new AsyncHttpClient();

    String fmURL = "http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=" + msg
            + "&autocorrect[1]&format=json&api_key=ca4c10f9ae187ebb889b33ba12da7ee9";
    Log.i("musicInfo", fmURL);

    client.get(fmURL, new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            String r = new String(responseBody);
            ArrayList<String> image_urls = new ArrayList<String>();

            try {
                Log.i("musicInfo", "Communicating with LastFM...");

                JSONObject json = new JSONObject(r);
                Log.i("musicInfo", json.toString());

                json = json.getJSONObject("artist");
                Log.i("musicInfo", json.toString());

                JSONArray artist_images = json.optJSONArray("image");
                Log.i("musicInfo", artist_images.toString());

                for (int i = 0; i < artist_images.length(); i++) {
                    JSONObject j = artist_images.getJSONObject(i);
                    Log.i("musicInfo", j.optString("size"));
                    if (j.optString("size").contains("extralarge")) {
                        image_urls.add(j.optString("#text"));
                        //b.putString("fm_image", j.getString("#text"));
                        //Log.i("musicInfo", j.getString("#text"));
                        break;
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            if (images != null) {
                for (int i = 0; i < images.length(); i++) {
                    JSONObject image = null;
                    try {
                        image = images.getJSONObject(i);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    int width = image.optInt("width", 0);
                    int height = image.optInt("height", 0);
                    String url = image.optString("url", "");
                    Log.i("musicInfo", i + ": " + url);
                    if ((width * height > 10000) && (width * height < 100000)
                            && (!url.contains("userserve-ak"))) {
                        //if ((width>300&&width<100)&&(height>300&&height<1000)&&(!url.contains("userserve-ak"))) {
                        image_urls.add(url);
                        Log.i("musicInfo", "Selected: " + url);
                        //available_images.put(image);
                    }
                }
            }

            int random = (int) (Math.random() * image_urls.size());
            final String f_url = image_urls.get(random);

            Log.i("musicInfo",
                    "Total image#=" + image_urls.size() + " Selected image#=" + random + " " + f_url);

            if (image_urls.size() > 0) {
                imageLoader.displayImage(f_url, ArtistImage, new ImageLoadingListener() {
                    @Override
                    public void onLoadingStarted(String imageUri, View view) {

                    }

                    @Override
                    public void onLoadingFailed(String imageUri, View view, FailReason failReason) {

                    }

                    @Override
                    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {

                        lLinkList.removeAllViews();
                        //String attr = fImage.optJSONObject("license").optString("attribution");
                        //tAttribution.setText("Credit. " + ((attr == null) || (attr.contains("n/a")) ? "Unknown" : attr));
                        if (urls != null) {
                            String[] jsonName = { "wikipedia_url", "mb_url", "lastfm_url", "official_url",
                                    "twitter_url" };
                            for (int i = 0; i < jsonName.length; i++) {
                                if ((urls.optString(jsonName[i]) != null)
                                        && (urls.optString(jsonName[i]) != "")) {
                                    Log.d("musicinfo", "Link URL: " + urls.optString(jsonName[i]));
                                    TextView tv = new TextView(getApplicationContext());
                                    tv.setTextSize(11);
                                    tv.setPadding(16, 16, 16, 16);
                                    tv.setTextColor(Color.LTGRAY);
                                    tv.setTypeface(Typeface.SANS_SERIF);
                                    tv.setGravity(Gravity.CENTER_VERTICAL);

                                    switch (jsonName[i]) {
                                    case "official_url":
                                        tv.setText("HOME.");
                                        break;
                                    case "wikipedia_url":
                                        tv.setText("WIKI.");
                                        break;
                                    case "mb_url":
                                        tv.setText("Music Brainz.");
                                        break;
                                    case "lastfm_url":
                                        tv.setText("Last FM.");
                                        break;
                                    case "twitter_url":
                                        tv.setText("Twitter.");
                                        break;
                                    }

                                    try {
                                        tv.setTag(urls.getString(jsonName[i]));
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }

                                    tv.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            Intent intent = new Intent();
                                            intent.setAction(Intent.ACTION_VIEW);
                                            intent.addCategory(Intent.CATEGORY_BROWSABLE);
                                            intent.setData(Uri.parse((String) v.getTag()));
                                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                            startActivity(intent);
                                            Toast.makeText(getApplicationContext(), "Open the Link...",
                                                    Toast.LENGTH_SHORT).show();
                                            //finish();
                                        }
                                    });
                                    lLinkList.addView(tv);
                                }
                            }
                        } else {
                            TextView tv = new TextView(getApplicationContext());
                            tv.setTextSize(11);
                            tv.setPadding(16, 16, 16, 16);
                            tv.setTextColor(Color.LTGRAY);
                            tv.setTypeface(Typeface.SANS_SERIF);
                            tv.setGravity(Gravity.CENTER_VERTICAL);
                            tv.setText("Sorry, No Link Here...");
                            lLinkList.addView(tv);
                        }

                        if (videos != null) {
                            jVideoArray = videos;
                            mAdapter = new StaggeredViewAdapter(getApplicationContext(),
                                    android.R.layout.simple_list_item_1, generateImageData(videos));
                            //if (mData == null) {
                            mData = generateImageData(videos);
                            //}

                            //mAdapter.clear();

                            for (JSONObject data : mData) {
                                mAdapter.add(data);
                            }
                            mGridView.setAdapter(mAdapter);
                        } else {

                        }

                        adjBottomColor(((ImageView) view).getDrawable());
                    }

                    @Override
                    public void onLoadingCancelled(String imageUri, View view) {

                    }
                });
            } else {
                ArtistImage.setImageResource(R.drawable.lamb_no_image_available);
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

        }
    });
}

From source file:com.haibison.android.anhuu.FragmentFiles.java

/**
 * As the name means./*from   ww  w  . j  av a 2s  . c  om*/
 */
private void buildAddressBar(final Uri path) {
    if (path == null)
        return;

    mViewAddressBar.removeAllViews();

    new LoadingDialog<Void, Cursor, Void>(getActivity(), false) {

        LinearLayout.LayoutParams lpBtnLoc;
        LinearLayout.LayoutParams lpDivider;
        LayoutInflater inflater = getLayoutInflater(null);
        final int dim = getResources().getDimensionPixelSize(R.dimen.anhuu_f5be488d_5dp);
        int count = 0;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            lpBtnLoc = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);
            lpBtnLoc.gravity = Gravity.CENTER;
        }// onPreExecute()

        @Override
        protected Void doInBackground(Void... params) {
            Cursor cursor = getActivity().getContentResolver().query(path, null, null, null, null);
            while (cursor != null) {
                if (cursor.moveToFirst()) {
                    publishProgress(cursor);
                    cursor.close();
                } else
                    break;

                /*
                 * Process the parent directory.
                 */
                Uri uri = Uri.parse(cursor.getString(cursor.getColumnIndex(BaseFile.COLUMN_URI)));
                cursor = getActivity().getContentResolver()
                        .query(BaseFile.genContentUriApi(uri.getAuthority()).buildUpon()
                                .appendPath(BaseFile.CMD_GET_PARENT)
                                .appendQueryParameter(BaseFile.PARAM_SOURCE, uri.getLastPathSegment()).build(),
                                null, null, null, null);
            } // while

            return null;
        }// doInBackground()

        @Override
        protected void onProgressUpdate(Cursor... progress) {
            /*
             * Add divider.
             */
            if (mViewAddressBar.getChildCount() > 0) {
                View divider = inflater.inflate(R.layout.anhuu_f5be488d_view_locations_divider, null);

                if (lpDivider == null) {
                    lpDivider = new LinearLayout.LayoutParams(dim, dim);
                    lpDivider.gravity = Gravity.CENTER;
                    lpDivider.setMargins(dim, dim, dim, dim);
                }
                mViewAddressBar.addView(divider, 0, lpDivider);
            }

            Uri lastUri = Uri.parse(progress[0].getString(progress[0].getColumnIndex(BaseFile.COLUMN_URI)));

            TextView btnLoc = (TextView) inflater.inflate(R.layout.anhuu_f5be488d_button_location, null);
            String name = BaseFileProviderUtils.getFileName(progress[0]);
            btnLoc.setText(TextUtils.isEmpty(name) ? getString(R.string.anhuu_f5be488d_root) : name);
            btnLoc.setTag(lastUri);
            btnLoc.setOnClickListener(mBtnLocationOnClickListener);
            btnLoc.setOnLongClickListener(mBtnLocationOnLongClickListener);
            mViewAddressBar.addView(btnLoc, 0, lpBtnLoc);

            if (count++ == 0) {
                Rect r = new Rect();
                btnLoc.getPaint().getTextBounds(name, 0, name.length(), r);
                if (r.width() >= getResources()
                        .getDimensionPixelSize(R.dimen.anhuu_f5be488d_button_location_max_width)
                        - btnLoc.getPaddingLeft() - btnLoc.getPaddingRight()) {
                    mTextFullDirName
                            .setText(progress[0].getString(progress[0].getColumnIndex(BaseFile.COLUMN_NAME)));
                    mTextFullDirName.setVisibility(View.VISIBLE);
                } else
                    mTextFullDirName.setVisibility(View.GONE);
            } // if
        }// onProgressUpdate()

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

            /*
             * Sometimes without delay time, it doesn't work...
             */
            mViewLocationsContainer.postDelayed(new Runnable() {

                public void run() {
                    mViewLocationsContainer.fullScroll(HorizontalScrollView.FOCUS_RIGHT);
                }// run()
            }, Display.DELAY_TIME_FOR_VERY_SHORT_ANIMATION);
        }// onPostExecute()

    }.execute();
}

From source file:org.sirimangalo.meditationplus.AdapterChat.java

@Override
public View getView(final int position, View convertView, ViewGroup parent) {

    View rowView;/* w w w . j  a va  2  s.  c om*/

    if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        rowView = inflater.inflate(R.layout.list_item_chat, parent, false);
    } else {
        rowView = convertView;
    }

    JSONObject p = values.get(position);
    try {
        int then = Integer.parseInt(p.getString("time"));
        long nowL = System.currentTimeMillis() / 1000;
        int now = (int) nowL;

        int ela = now - then;
        int day = 60 * 60 * 24;
        ela = ela > day ? day : ela;
        int intColor = 255 - Math.round((float) ela * 255 / day);
        intColor = intColor > 100 ? intColor : 100;
        String hexTransparency = Integer.toHexString(intColor);
        hexTransparency = hexTransparency.length() > 1 ? hexTransparency : "0" + hexTransparency;
        String hexColor = "#" + hexTransparency + "000000";
        int transparency = Color.parseColor(hexColor);

        TextView time = (TextView) rowView.findViewById(R.id.time);
        if (time != null) {
            String ts = null;
            ts = Utils.time2Ago(then);
            time.setText(ts);
            time.setTextColor(transparency);
        }

        TextView mess = (TextView) rowView.findViewById(R.id.message);
        if (mess != null) {

            final String username = p.getString("username");

            String messageString = p.getString("message");

            messageString = Html.fromHtml(messageString).toString();

            SpannableString messageSpan = Utils.replaceSmilies(context, messageString, intColor);

            if (messageString.contains("@" + loggedUser)) {
                int index = messageString.indexOf("@" + loggedUser);
                messageSpan.setSpan(new StyleSpan(Typeface.BOLD), index, index + loggedUser.length() + 1,
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                messageSpan.setSpan(new ForegroundColorSpan(Color.parseColor("#" + hexTransparency + "990000")),
                        index, index + loggedUser.length() + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }

            for (String user : users) {
                if (!user.equals(loggedUser) && messageString.contains("@" + user)) {
                    int index = messageString.indexOf("@" + user);
                    messageSpan = Utils.createProfileSpan(context, index, index + user.length() + 1, user,
                            messageSpan);
                    messageSpan.setSpan(
                            new ForegroundColorSpan(Color.parseColor("#" + hexTransparency + "009900")), index,
                            index + user.length() + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
            }

            Spannable userSpan = Utils.createProfileSpan(context, 0, username.length(), username,
                    new SpannableString(username + ": "));

            if (p.getString("me").equals("true"))
                userSpan.setSpan(new ForegroundColorSpan(Color.parseColor("#" + hexTransparency + "0000FF")), 0,
                        userSpan.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            else
                userSpan.setSpan(new ForegroundColorSpan(Color.parseColor("#" + hexTransparency + "000000")), 0,
                        userSpan.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

            CharSequence full = TextUtils.concat(userSpan, messageSpan);

            mess.setTextColor(transparency);
            mess.setText(full);
            mess.setMovementMethod(LinkMovementMethod.getInstance());
            Linkify.addLinks(mess, Linkify.ALL);
            mess.setTag(p.getString("cid"));
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }
    return rowView;

}

From source file:com.nachiket.titan.LibraryPagerAdapter.java

@Override
public Object instantiateItem(ViewGroup container, int position) {
    int type = mTabOrder[position];
    ListView view = mLists[type];

    if (view == null) {
        LibraryActivity activity = mActivity;
        LayoutInflater inflater = activity.getLayoutInflater();
        LibraryAdapter adapter;//from   w w  w  . ja v a 2s  . c o m
        TextView header = null;

        switch (type) {
        case MediaUtils.TYPE_ARTIST:
            adapter = mArtistAdapter = new MediaAdapter(activity, MediaUtils.TYPE_ARTIST, null);
            mArtistAdapter.setExpandable(mSongsPosition != -1 || mAlbumsPosition != -1);
            mArtistHeader = header = (TextView) inflater.inflate(R.layout.library_row, null);
            break;
        case MediaUtils.TYPE_ALBUM:
            adapter = mAlbumAdapter = new MediaAdapter(activity, MediaUtils.TYPE_ALBUM, mPendingAlbumLimiter);
            mAlbumAdapter.setExpandable(mSongsPosition != -1);
            mPendingAlbumLimiter = null;
            mAlbumHeader = header = (TextView) inflater.inflate(R.layout.library_row, null);
            break;
        case MediaUtils.TYPE_SONG:
            adapter = mSongAdapter = new MediaAdapter(activity, MediaUtils.TYPE_SONG, mPendingSongLimiter);
            mPendingSongLimiter = null;
            mSongHeader = header = (TextView) inflater.inflate(R.layout.library_row, null);
            break;
        case MediaUtils.TYPE_PLAYLIST:
            adapter = mPlaylistAdapter = new MediaAdapter(activity, MediaUtils.TYPE_PLAYLIST, null);
            break;
        case MediaUtils.TYPE_GENRE:
            adapter = mGenreAdapter = new MediaAdapter(activity, MediaUtils.TYPE_GENRE, null);
            mGenreAdapter.setExpandable(mSongsPosition != -1);
            break;
        case MediaUtils.TYPE_FILE:
            adapter = mFilesAdapter = new FileSystemAdapter(activity, mPendingFileLimiter);
            mPendingFileLimiter = null;
            break;
        default:
            throw new IllegalArgumentException("Invalid media type: " + type);
        }

        view = (ListView) inflater.inflate(R.layout.listview, null);
        view.setOnCreateContextMenuListener(this);
        view.setOnItemClickListener(this);
        view.setTag(type);
        if (header != null) {
            header.setText(mHeaderText);
            header.setTag(type);
            view.addHeaderView(header);
        }
        view.setAdapter(adapter);
        if (type != MediaUtils.TYPE_FILE)
            loadSortOrder((MediaAdapter) adapter);
        enableFastScroll(view);
        adapter.setFilter(mFilter);

        mAdapters[type] = adapter;
        mLists[type] = view;
        mRequeryNeeded[type] = true;
    }

    requeryIfNeeded(type);
    container.addView(view);
    return view;
}

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

@Override
public void bindView(final View view, final Context context, final Cursor cursor) {
    // Get values
    final long id = cursor.getLong(colID);
    long time = cursor.getLong(colTime);
    int version = (cursor.isNull(colVersion) ? -1 : cursor.getInt(colVersion));
    int protocol = (cursor.isNull(colProtocol) ? -1 : cursor.getInt(colProtocol));
    String flags = cursor.getString(colFlags);
    String saddr = cursor.getString(colSAddr);
    int sport = (cursor.isNull(colSPort) ? -1 : cursor.getInt(colSPort));
    String daddr = cursor.getString(colDAddr);
    int dport = (cursor.isNull(colDPort) ? -1 : cursor.getInt(colDPort));
    String dname = (cursor.isNull(colDName) ? null : cursor.getString(colDName));
    int uid = (cursor.isNull(colUid) ? -1 : cursor.getInt(colUid));
    String data = cursor.getString(colData);
    int allowed = (cursor.isNull(colAllowed) ? -1 : cursor.getInt(colAllowed));
    int connection = (cursor.isNull(colConnection) ? -1 : cursor.getInt(colConnection));
    int interactive = (cursor.isNull(colInteractive) ? -1 : cursor.getInt(colInteractive));

    // Get views/*  ww w  . ja v  a2s. c o  m*/
    TextView tvTime = (TextView) view.findViewById(R.id.tvTime);
    TextView tvProtocol = (TextView) view.findViewById(R.id.tvProtocol);
    TextView tvFlags = (TextView) view.findViewById(R.id.tvFlags);
    TextView tvSAddr = (TextView) view.findViewById(R.id.tvSAddr);
    TextView tvSPort = (TextView) view.findViewById(R.id.tvSPort);
    final TextView tvDaddr = (TextView) view.findViewById(R.id.tvDAddr);
    TextView tvDPort = (TextView) view.findViewById(R.id.tvDPort);
    final TextView tvOrganization = (TextView) view.findViewById(R.id.tvOrganization);
    ImageView ivIcon = (ImageView) view.findViewById(R.id.ivIcon);
    TextView tvUid = (TextView) view.findViewById(R.id.tvUid);
    TextView tvData = (TextView) view.findViewById(R.id.tvData);
    ImageView ivConnection = (ImageView) view.findViewById(R.id.ivConnection);
    ImageView ivInteractive = (ImageView) view.findViewById(R.id.ivInteractive);

    // Show time
    tvTime.setText(new SimpleDateFormat("HH:mm:ss").format(time));

    // Show connection type
    if (connection <= 0)
        ivConnection.setImageResource(allowed > 0 ? R.drawable.host_allowed : R.drawable.host_blocked);
    else {
        if (allowed > 0)
            ivConnection.setImageResource(connection == 1 ? R.drawable.wifi_on : R.drawable.other_on);
        else
            ivConnection.setImageResource(connection == 1 ? R.drawable.wifi_off : R.drawable.other_off);
    }
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        Drawable wrap = DrawableCompat.wrap(ivConnection.getDrawable());
        DrawableCompat.setTint(wrap, allowed > 0 ? colorOn : colorOff);
    }

    // Show if screen on
    if (interactive <= 0)
        ivInteractive.setImageDrawable(null);
    else {
        ivInteractive.setImageResource(R.drawable.screen_on);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            Drawable wrap = DrawableCompat.wrap(ivInteractive.getDrawable());
            DrawableCompat.setTint(wrap, colorOn);
        }
    }

    // Show protocol name
    tvProtocol.setText(Util.getProtocolName(protocol, version, false));

    // SHow TCP flags
    tvFlags.setText(flags);
    tvFlags.setVisibility(TextUtils.isEmpty(flags) ? View.GONE : View.VISIBLE);

    // Show source and destination port
    if (protocol == 6 || protocol == 17) {
        tvSPort.setText(sport < 0 ? "" : getKnownPort(sport));
        tvDPort.setText(dport < 0 ? "" : getKnownPort(dport));
    } else {
        tvSPort.setText(sport < 0 ? "" : Integer.toString(sport));
        tvDPort.setText(dport < 0 ? "" : Integer.toString(dport));
    }

    // Application icon
    ApplicationInfo info = null;
    PackageManager pm = context.getPackageManager();
    String[] pkg = pm.getPackagesForUid(uid);
    if (pkg != null && pkg.length > 0)
        try {
            info = pm.getApplicationInfo(pkg[0], 0);
        } catch (PackageManager.NameNotFoundException ignored) {
        }
    if (info == null)
        ivIcon.setImageDrawable(null);
    else if (info.icon == 0)
        Picasso.with(context).load(android.R.drawable.sym_def_app_icon).into(ivIcon);
    else {
        Uri uri = Uri.parse("android.resource://" + info.packageName + "/" + info.icon);
        Picasso.with(context).load(uri).resize(iconSize, iconSize).into(ivIcon);
    }

    // https://android.googlesource.com/platform/system/core/+/master/include/private/android_filesystem_config.h
    uid = uid % 100000; // strip off user ID
    if (uid == -1)
        tvUid.setText("");
    else if (uid == 0)
        tvUid.setText(context.getString(R.string.title_root));
    else if (uid == 9999)
        tvUid.setText("-"); // nobody
    else
        tvUid.setText(Integer.toString(uid));

    // Show source address
    tvSAddr.setText(getKnownAddress(saddr));

    // Show destination address
    if (resolve && !isKnownAddress(daddr))
        if (dname == null) {
            if (tvDaddr.getTag() == null) {
                tvDaddr.setText(daddr);
                new AsyncTask<String, Object, String>() {
                    @Override
                    protected void onPreExecute() {
                        tvDaddr.setTag(id);
                    }

                    @Override
                    protected String doInBackground(String... args) {
                        try {
                            return InetAddress.getByName(args[0]).getHostName();
                        } catch (UnknownHostException ignored) {
                            return args[0];
                        }
                    }

                    @Override
                    protected void onPostExecute(String name) {
                        Object tag = tvDaddr.getTag();
                        if (tag != null && (Long) tag == id)
                            tvDaddr.setText(">" + name);
                        tvDaddr.setTag(null);
                    }
                }.execute(daddr);
            }
        } else
            tvDaddr.setText(dname);
    else
        tvDaddr.setText(getKnownAddress(daddr));

    // Show organization
    tvOrganization.setVisibility(View.GONE);
    if (organization) {
        if (!isKnownAddress(daddr) && tvOrganization.getTag() == null)
            new AsyncTask<String, Object, String>() {
                @Override
                protected void onPreExecute() {
                    tvOrganization.setTag(id);
                }

                @Override
                protected String doInBackground(String... args) {
                    try {
                        return Util.getOrganization(args[0]);
                    } catch (Throwable ex) {
                        Log.w(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                        return null;
                    }
                }

                @Override
                protected void onPostExecute(String organization) {
                    Object tag = tvOrganization.getTag();
                    if (organization != null && tag != null && (Long) tag == id) {
                        tvOrganization.setText(organization);
                        tvOrganization.setVisibility(View.VISIBLE);
                    }
                    tvOrganization.setTag(null);
                }
            }.execute(daddr);
    }

    // Show extra data
    if (TextUtils.isEmpty(data)) {
        tvData.setText("");
        tvData.setVisibility(View.GONE);
    } else {
        tvData.setText(data);
        tvData.setVisibility(View.VISIBLE);
    }
}

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

@Override
public void bindView(final View view, final Context context, final Cursor cursor) {
    // Get values
    final long id = cursor.getLong(colID);
    long time = cursor.getLong(colTime);
    int version = (cursor.isNull(colVersion) ? -1 : cursor.getInt(colVersion));
    int protocol = (cursor.isNull(colProtocol) ? -1 : cursor.getInt(colProtocol));
    String flags = cursor.getString(colFlags);
    String saddr = cursor.getString(colSAddr);
    int sport = (cursor.isNull(colSPort) ? -1 : cursor.getInt(colSPort));
    String daddr = cursor.getString(colDAddr);
    int dport = (cursor.isNull(colDPort) ? -1 : cursor.getInt(colDPort));
    String dname = (cursor.isNull(colDName) ? null : cursor.getString(colDName));
    int uid = (cursor.isNull(colUid) ? -1 : cursor.getInt(colUid));
    String data = cursor.getString(colData);
    int allowed = (cursor.isNull(colAllowed) ? -1 : cursor.getInt(colAllowed));
    int connection = (cursor.isNull(colConnection) ? -1 : cursor.getInt(colConnection));
    int interactive = (cursor.isNull(colInteractive) ? -1 : cursor.getInt(colInteractive));

    // Get views//from   ww  w. j a va 2s  .co m
    TextView tvTime = (TextView) view.findViewById(R.id.tvTime);
    TextView tvProtocol = (TextView) view.findViewById(R.id.tvProtocol);
    //        TextView tvFlags = (TextView) view.findViewById(R.id.tvFlags);
    TextView tvSAddr = (TextView) view.findViewById(R.id.tvSAddr);
    TextView tvSPort = (TextView) view.findViewById(R.id.tvSPort);
    final TextView tvDaddr = (TextView) view.findViewById(R.id.tvDAddr);
    TextView tvDPort = (TextView) view.findViewById(R.id.tvDPort);
    final TextView tvOrganization = (TextView) view.findViewById(R.id.tvOrganization);
    ImageView ivIcon = (ImageView) view.findViewById(R.id.ivIcon);
    TextView tvUid = (TextView) view.findViewById(R.id.tvUid);
    TextView tvData = (TextView) view.findViewById(R.id.tvData);
    ImageView ivConnection = (ImageView) view.findViewById(R.id.ivConnection);
    ImageView ivInteractive = (ImageView) view.findViewById(R.id.ivInteractive);

    // Show time
    tvTime.setText(new SimpleDateFormat("HH:mm:ss").format(time));

    // Show connection type
    if (connection <= 0)
        ivConnection.setImageResource(allowed > 0 ? R.drawable.host_allowed : R.drawable.host_blocked);
    else {
        if (allowed > 0)
            ivConnection.setImageResource(connection == 1 ? R.drawable.wifi_on : R.drawable.other_on);
        else
            ivConnection.setImageResource(connection == 1 ? R.drawable.wifi_off : R.drawable.other_off);
    }
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        Drawable wrap = DrawableCompat.wrap(ivConnection.getDrawable());
        DrawableCompat.setTint(wrap, allowed > 0 ? colorOn : colorOff);
    }

    // Show if screen on
    if (interactive <= 0)
        ivInteractive.setImageDrawable(null);
    else {
        ivInteractive.setImageResource(R.drawable.screen_on);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            Drawable wrap = DrawableCompat.wrap(ivInteractive.getDrawable());
            DrawableCompat.setTint(wrap, colorOn);
        }
    }

    // Show protocol name
    tvProtocol.setText(Util.getProtocolName(protocol, version, false) + flags);

    // SHow TCP flags
    //        tvFlags.setText(flags);
    //        tvFlags.setVisibility(TextUtils.isEmpty(flags) ? View.GONE : View.VISIBLE);

    // Show source and destination port
    if (protocol == 6 || protocol == 17) {
        tvSPort.setText(sport < 0 ? "" : getKnownPort(sport));
        tvDPort.setText(dport < 0 ? "" : getKnownPort(dport));
    } else {
        tvSPort.setText(sport < 0 ? "" : Integer.toString(sport));
        tvDPort.setText(dport < 0 ? "" : Integer.toString(dport));
    }

    // Application icon
    ApplicationInfo info = null;
    PackageManager pm = context.getPackageManager();
    String[] pkg = pm.getPackagesForUid(uid);
    if (pkg != null && pkg.length > 0)
        try {
            info = pm.getApplicationInfo(pkg[0], 0);
        } catch (PackageManager.NameNotFoundException ignored) {
        }
    if (info == null)
        ivIcon.setImageDrawable(null);
    else if (info.icon == 0)
        Picasso.with(context).load(android.R.drawable.sym_def_app_icon).into(ivIcon);
    else {
        Uri uri = Uri.parse("android.resource://" + info.packageName + "/" + info.icon);
        Picasso.with(context).load(uri).resize(iconSize, iconSize).into(ivIcon);
    }

    // https://android.googlesource.com/platform/system/core/+/master/include/private/android_filesystem_config.h
    uid = uid % 100000; // strip off user ID
    if (uid == -1)
        tvUid.setText("");
    else if (uid == 0)
        tvUid.setText(context.getString(R.string.title_root));
    else if (uid == 9999)
        tvUid.setText("-"); // nobody
    else
        tvUid.setText(Integer.toString(uid));

    // Show source address
    tvSAddr.setText(getKnownAddress(saddr));

    // Show destination address
    if (resolve && !isKnownAddress(daddr))
        if (dname == null) {
            if (tvDaddr.getTag() == null) {
                tvDaddr.setText(daddr);
                new AsyncTask<String, Object, String>() {
                    @Override
                    protected void onPreExecute() {
                        tvDaddr.setTag(id);
                    }

                    @Override
                    protected String doInBackground(String... args) {
                        try {
                            return InetAddress.getByName(args[0]).getHostName();
                        } catch (UnknownHostException ignored) {
                            return args[0];
                        }
                    }

                    @Override
                    protected void onPostExecute(String name) {
                        Object tag = tvDaddr.getTag();
                        if (tag != null && (Long) tag == id)
                            tvDaddr.setText(">" + name);
                        tvDaddr.setTag(null);
                    }
                }.execute(daddr);
            }
        } else
            tvDaddr.setText(dname);
    else
        tvDaddr.setText(getKnownAddress(daddr));

    // Show organization
    tvOrganization.setVisibility(View.GONE);
    if (organization) {
        if (!isKnownAddress(daddr) && tvOrganization.getTag() == null)
            new AsyncTask<String, Object, String>() {
                @Override
                protected void onPreExecute() {
                    tvOrganization.setTag(id);
                }

                @Override
                protected String doInBackground(String... args) {
                    try {
                        return Util.getOrganization(args[0]);
                    } catch (Throwable ex) {
                        Log.w(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                        return null;
                    }
                }

                @Override
                protected void onPostExecute(String organization) {
                    Object tag = tvOrganization.getTag();
                    if (organization != null && tag != null && (Long) tag == id) {
                        tvOrganization.setText(organization);
                        tvOrganization.setVisibility(View.VISIBLE);
                    }
                    tvOrganization.setTag(null);
                }
            }.execute(daddr);
    }

    // Show extra data
    if (TextUtils.isEmpty(data)) {
        tvData.setText("");
        tvData.setVisibility(View.GONE);
    } else {
        tvData.setText(data);
        tvData.setVisibility(View.VISIBLE);
    }
}