示例#1
0
  /**
   * Extract the text from a HTML based string. This is similar to what HTML.fromHtml(...) does, but
   * this method also removes the embedded images instead of replacing them by a small rectangular
   * representation character.
   *
   * @param html
   * @return
   */
  public static String extractText(CharSequence html) {
    String result = html.toString();

    // recognize images in textview HTML contents
    if (html instanceof Spanned) {
      Spanned text = (Spanned) html;
      Object[] styles = text.getSpans(0, text.length(), Object.class);
      ArrayList<Pair<Integer, Integer>> removals = new ArrayList<Pair<Integer, Integer>>();
      for (Object style : styles) {
        if (style instanceof ImageSpan) {
          int start = text.getSpanStart(style);
          int end = text.getSpanEnd(style);
          removals.add(Pair.of(start, end));
        }
      }

      // sort reversed and delete image spans
      Collections.sort(
          removals,
          new Comparator<Pair<Integer, Integer>>() {

            @Override
            public int compare(Pair<Integer, Integer> lhs, Pair<Integer, Integer> rhs) {
              return rhs.getRight().compareTo(lhs.getRight());
            }
          });
      result = text.toString();
      for (Pair<Integer, Integer> removal : removals) {
        result = result.substring(0, removal.getLeft()) + result.substring(removal.getRight());
      }
    }

    // some line breaks are still in the text, source is unknown
    return StringUtils.replace(result, "<br />", "\n").trim();
  }
示例#2
0
  @Override
  public void onBindViewHolder(ViewHolder holder, Cursor cursor) {
    final boolean isFavorite =
        cursor.getInt(cursor.getColumnIndex(QuotesTableHelper.IS_FAVORITE)) == 1;
    final boolean isAuthorNonNull =
        null != cursor.getString(cursor.getColumnIndex(QuotesTableHelper.AUTHOR));
    final String link = cursor.getString(cursor.getColumnIndex(QuotesTableHelper.LINK));
    holder.setLink(link);
    final String title = cursor.getString(cursor.getColumnIndex(QuotesTableHelper.TITLE));
    final long id = cursor.getLong(cursor.getColumnIndex(QuotesTableHelper.ID));
    holder.tvPubDate.setText(
        DateUtil.getItemPubDate(
            new Date(cursor.getLong(cursor.getColumnIndex(QuotesTableHelper.PUB_DATE)))));
    if (isFavorite) holder.ivFavorite.setImageResource(android.R.drawable.star_big_on);
    else holder.ivFavorite.setImageResource(android.R.drawable.star_big_off);
    holder.ivFavorite.setOnClickListener(
        v -> QuotesTableHelper.makeFavorite(getContext(), id, !isFavorite));

    if (isAuthorNonNull) {
      holder.tvText.setVisibility(View.GONE);
      holder.ivComics.setVisibility(View.VISIBLE);
      final String url = cursor.getString(cursor.getColumnIndex(QuotesTableHelper.DESCRIPTION));
      holder.setText(url, cursor.getString(cursor.getColumnIndex(QuotesTableHelper.AUTHOR)));
      if (mFavorite) holder.makeClick(0, false);
      else holder.makeClick(cursor.getLong(cursor.getColumnIndex(QuotesTableHelper.ID)), true);
      Picasso.with(getContext()).load(url).config(Bitmap.Config.ALPHA_8).into(holder.ivComics);
      holder.tvTitle.setText(cursor.getString(cursor.getColumnIndex(QuotesTableHelper.AUTHOR)));
    } else {
      holder.tvText.setVisibility(View.VISIBLE);
      holder.ivComics.setVisibility(View.GONE);
      String description = cursor.getString(cursor.getColumnIndex(QuotesTableHelper.DESCRIPTION));
      if (!description.contains("\n")) {
        Spanned text = Html.fromHtml(description);
        holder.tvText.setText(highlightTextileNeeded(text.toString()));
        holder.setText(text.toString(), null);
      } else {
        holder.tvText.setText(highlightTextileNeeded(description));
        holder.setText(description, null);
      }
      holder.tvTitle.setText(title);
      holder.tvTitle.setOnClickListener(
          v -> {
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
            getContext().startActivity(intent);
          });
    }
  }
示例#3
0
 private void updateTextView(View bookView, Integer id, String value) {
   TextView textView = (TextView) bookView.findViewById(id);
   if (isBlankOrNull(value)) {
     textView.setVisibility(View.GONE);
   } else {
     textView.setVisibility(View.VISIBLE);
     Spanned markUp = Html.fromHtml(value);
     textView.setText(markUp.toString());
   }
 }
 private static CharSequence removeJumpingBeansSpans(Spanned text) {
   SpannableStringBuilder sbb = new SpannableStringBuilder(text.toString());
   Object[] spans = text.getSpans(0, text.length(), Object.class);
   for (Object span : spans) {
     if (!(span instanceof JumpingBeansSpan)) {
       sbb.setSpan(span, text.getSpanStart(span), text.getSpanEnd(span), text.getSpanFlags(span));
     }
   }
   return sbb;
 }
 @Override
 public CharSequence filter(
     CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
   try {
     int input = Integer.parseInt(dest.toString() + source.toString());
     if (isInRange(min, max, input)) return null;
   } catch (NumberFormatException nfe) {
   }
   return "";
 }
  public CharSequence filter(
      CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {

    Log.d(
        TAG,
        "source:"
            + source
            + " start:"
            + start
            + " end:"
            + end
            + " dest:"
            + dest
            + " dstart:"
            + dstart
            + " dend:"
            + dend);

    String s = source.toString();
    //		for(int i=0;i<s.length();i++){
    //			int c=s.charAt(i);
    //			if(c!=','&&(c<'0'||c>'9')){
    //				return "";
    //			}
    //		}
    int sourceCommaIndex = s.indexOf(',');
    if (sourceCommaIndex >= 0) {
      int destCommaIndex = dest.toString().indexOf(',');
      if (destCommaIndex >= 0) {
        s = s.replace(COMMA, EMPYTY); // delete all ',',because of ',' is alread in dest.
      } else {
        int sourceCommaIndex2 = s.lastIndexOf(',');
        if (sourceCommaIndex2 != sourceCommaIndex) { // more one ',' in source
          s = s.replace(COMMA, EMPYTY);
        }
      }
    }
    source = s;

    //		if(dstart>0){
    //			s=dest.subSequence(0, dstart).toString()+s;
    //		}
    //		if(dend<dest.length()-1){
    //			s+=dest.subSequence(dend, dest.length());
    //		}
    Log.d(TAG, "result:" + source);

    return source;
  }
示例#7
0
  public void setText(String text) {
    Spanned spannedText = Html.fromHtml(text);
    text = spannedText.toString();
    textWidth = (int) textPaint.measureText(text, 0, text.length());

    boolean modifiedText = false;
    while (textWidth > maxX) {
      text = text.substring(0, text.length() - 1);
      textWidth = (int) textPaint.measureText(text, 0, text.length());
      modifiedText = true;
    }

    if (modifiedText) text += "...";
    this.text = text;

    textPaint.getTextBounds(text, 0, text.length(), bounds);
  }
    @Override
    protected void onPostExecute(Spanned spanned) {
      if (mActivity != null && mActivity.getPost() != null && spanned != null) {
        if (mActivity.getPost().isLocalDraft()) {
          mTextView.setVisibility(View.VISIBLE);
          mWebView.setVisibility(View.GONE);
          mTextView.setText(spanned);
        } else {
          mTextView.setVisibility(View.GONE);
          mWebView.setVisibility(View.VISIBLE);

          mWebView.loadDataWithBaseURL(
              "file:///android_asset/", spanned.toString(), "text/html", "utf-8", null);
        }
      }

      mLoadTask = null;
    }
  @Override
  public CharSequence filter(
      CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {

    String destTxt = dest.toString();
    String resultingTxt =
        destTxt.substring(0, dstart) + source.subSequence(start, end) + destTxt.substring(dend);
    if (!resultingTxt.matches("^\\d{1,9}(\\.(\\d{1,2}?)?)?")) {
      return "";
    } else {

      splits = resultingTxt.split("\\.");
      if (splits.length == 1) {
        userinputlistenerpointexception = false;
      } else {
        userinputlistenerpointexception = true;
      }
    }
    return null;
  }
 @Override
 public CharSequence filter(
     CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
   if (end > start) {
     String destTxt = dest.toString();
     String resultingTxt =
         destTxt.substring(0, dstart) + source.subSequence(start, end) + destTxt.substring(dend);
     if (!resultingTxt.matches("^\\d{1,3}(\\.(\\d{1,3}(\\.(\\d{1,3}(\\.(\\d{1,3})?)?)?)?)?)?")) {
       return "";
     } else {
       String[] splits = resultingTxt.split("\\.");
       for (int i = 0; i < splits.length; i++) {
         if (Integer.valueOf(splits[i]) > 255) {
           return "";
         }
       }
     }
   }
   return null;
 }
 public CharSequence filter(
     CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
   int i;
   this.ch_old = dest.toString().toCharArray();
   this.iallnum = 0;
   for (char c : this.ch_old) {
     this.ch_c = c;
     if (SysApplication.isContainsChinese(this.ch_c)) {
       this.iallnum += 3;
     } else {
       this.iallnum++;
     }
   }
   if (this.iallnum >= 30) {
     return "";
   }
   this.ch_new = source.toString().toCharArray();
   int keep = 0;
   for (i = 0; i < this.ch_new.length; i++) {
     this.ch_c = this.ch_new[i];
     if (SysApplication.isContainsChinese(this.ch_c)) {
       this.iallnum += 3;
     } else {
       this.iallnum++;
     }
     if (this.iallnum > 30) {
       keep = i;
       break;
     }
   }
   if (this.iallnum <= 30) {
     return null;
   }
   if (keep == 0) {
     return "";
   }
   return source.subSequence(start, start + keep);
 }
示例#12
0
  /*
   * This method is used to parse the xml file containing
   * the articles.
   *
   * @param InputStream  input stream of the download.
   *
   * @return ArrayList<Article> list of articles parsed from file
   */
  public ArrayList<Article> parseXml(InputStream inputStream) {
    XmlPullParserFactory pullParserFactory;
    ArrayList<Article> articles = null;
    String defaultImage = null;

    try {
      // Create the XmlPullParser factory and parser
      pullParserFactory = XmlPullParserFactory.newInstance();
      XmlPullParser parser = pullParserFactory.newPullParser();

      // Get the xml file and set into the parser.
      parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
      parser.setInput(inputStream, null);

      int eventType = parser.getEventType();
      Article currentItem = null;

      // kluge to take care of html to string issue.
      int decimal = Integer.parseInt("fffc", 16);
      // convert the decimal to character
      char tempChar = (char) decimal;

      // While not at the end of the document continue checking for required
      // items.
      while (eventType != XmlPullParser.END_DOCUMENT) {
        String name = null;
        switch (eventType) {
          case XmlPullParser.START_DOCUMENT:
            articles = new ArrayList<Article>();
            break;
          case XmlPullParser.START_TAG:
            // Found a start tag.  Check if one looking for.  It item
            // then have a new article.  If a title or content then
            // save the data.
            name = parser.getName();
            if (name.equals("item")) {
              currentItem = new Article();
            } else if (name.equals("title") && currentItem == null) {
              // check which feed so can set default image if one
              // isn't found.
              String temp = parser.nextText();
              // Hmmm, intended to access the default image.  However,
              // this would probably mean having to do differently.
              // Should probably save images to internal storage so
              // they can be accessed the same as cached images.
              if (temp.toLowerCase().contains("google")) {
                defaultImage = new String("google");
              } else if (temp.toLowerCase().contains("yahoo")) {
                defaultImage = new String("yahoo");
              }
            } else if (currentItem != null) {
              if (name.equals("title")) {
                currentItem.title = parser.nextText();
              } else if (name.equals("description")) {
                // TODO: This should be where we pull the image from the description
                // and put that into the content image.  Since we are already in
                // an async task we can do here.  If trying to make reusable would
                // need to put into another async task.
                Spanned result = Html.fromHtml(parser.nextText(), null, null);
                currentItem.content = result.toString();
                // Major hack to get rid of "obj" chars.  Need to do different
                // if have time.
                currentItem.content = currentItem.content.replace(tempChar, '\0');
              } else if (name.equals("pubDate")) {
                currentItem.date = parser.nextText();
              } else if (name.equals("media:content")) {
                // Comment out for now since haven't downloaded images.
                // currentItem.imageUri = parser.getAttributeValue(null, "url");
                // currentItem.imageUri = parser.nextText();
              }
            }
            break;
          case XmlPullParser.END_TAG:
            // If this is an end tag check if this means end of item.
            // If so then save the article.
            name = parser.getName();
            if (name.equalsIgnoreCase("item") && currentItem != null) {
              // If didn't find an image than use the default
              if (currentItem.imageUri == null) {
                currentItem.imageUri = defaultImage;
              }
              articles.add(currentItem);
            }
            break;
          case XmlPullParser.TEXT:
            // This is only used for checking how working.
            System.out.println("getting text");
        }
        eventType = parser.next();
      }

      System.out.println("finally done");

    } catch (XmlPullParserException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return articles;
  }