在AsyncTask中崩溃

时间:2018-10-05 11:24:40

标签: android android-asynctask

  • 我有一个异步任务,该任务在后台执行一些任务。
  • 我发生了崩溃,但我无法查明崩溃的确切来源,如何 解决这个问题

AsyncSosFeedAdptType.java

public class AsyncSosFeedAdptType extends AsyncTask<String, Void, List<CustomSosFeed>> {

    private List<SOSmodel> sosFeedResults;
    private List<CustomSosFeed> sosFeed;

    private Activity context;

    public AsyncSosFeedAdptType(Activity ctx, List<SOSmodel> sosFeedResults) {
        this.context = ctx;
        this.sosFeedResults = sosFeedResults;
        sosFeed = new ArrayList<>();
    }

    @Override
    protected void onPreExecute() {}

    @Override
    protected List<CustomSosFeed> doInBackground(String... params) {

        String mIgLoc = null;
        //Get the Final Uri for the BitMap
        try {
            return initiateSosFeed();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sosFeed;
    }

    @Override
    protected void onPostExecute(List<CustomSosFeed> result) {
        //Post the image location back to the called class
        EventBus.getDefault().post(new BusDisplayList(result));
    }



    private List<CustomSosFeed> initiateSosFeed() {

        Timber.d("message",sosFeedResults);

        CustomSosFeed custSos;

        for (SOSmodel sos:sosFeedResults) {
            custSos = new CustomSosFeed();

            SpannableStringBuilder message = getMessage(sos);
            String image = getImage(sos);
            String name = getName(sos);
            String sosId = getSosId(sos);
            long time = getTime(sos);
            int countLikes = getLikeCnt(sos);
            int countComments = getCommentsCnt(sos);
            boolean isUrlPresent = isUrlPresent(sos);
            boolean isPostedImgsPresent = isPostedImgsPresent(sos);
            boolean isLiked = isLiked(sos);
            String url = getUrl(sos);
            List<String> images = getimagesPosted(sos);


            int displayType = getDisplayType(sos,isUrlPresent,isPostedImgsPresent);
            String userId = getUserId(sos);


            CustomSosFeedContent content = new CustomSosFeedContent();
            content.setMessage(message);
            content.setImage(image);
            content.setName(name);
            content.setTime(time);
            content.setCountLikes(countLikes);
            content.setCountComments(countComments);
            content.setUrlPresent(isUrlPresent);
            content.setUrl(url);
            content.setImages(images);
            content.setLiked(isLiked);

            custSos.setDisplayType(displayType);
            custSos.setUserId(userId);
            custSos.setSosId(sosId);
            custSos.setContent(content);

            sosFeed.add(custSos);
        }

        return sosFeed;

    }

    private String getSosId(SOSmodel sos) {
        return sos.getId();
    }

    private boolean isLiked(SOSmodel sos) {
        return sos.isLikedBy();
    }

    private boolean isPostedImgsPresent(SOSmodel sos) {
        if(sos.getImages().size()>0){
            return true;
        }else{
            return false;
        }
    }

    private List<String> getimagesPosted(SOSmodel sos) {
        return sos.getImages();
    }

    private String getUrl(SOSmodel sos) {

        String editTextString = sos.getPost();
        String[] parts = editTextString.split("\\s");
        String url="";

        for (String item : parts) {
            if (Patterns.WEB_URL.matcher(item).matches()) {
                try {
                    Uri uri = Uri.parse(item);
                    String prefix = "https://";
                    String prefix1 = "http://";
                    String a = uri.toString();
                    if (!a.substring(0, prefix.length()).equalsIgnoreCase(prefix) && !a.substring(0, prefix1.length()).equalsIgnoreCase(prefix1)) {
                        a = prefix + a;
                    }
                    if (a != null) {
                        url = a;
                        break;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            } else {
                url = "";
            }
        }
        return url;

    }

    private boolean isUrlPresent(SOSmodel sos) {

        String editTextString = sos.getPost();
        String[] parts = editTextString.split("\\s");

        boolean isUrPresent = false;

        for (String item : parts) {
            if (Patterns.WEB_URL.matcher(item).matches()) {
                isUrPresent = true;
                break;
            } else {
                isUrPresent = false;
            }
        }
        return isUrPresent;
    }

    private String getUserId(SOSmodel sos) {
        return sos.getUserId();
    }

    @Contract(pure = true)
    private int getDisplayType(SOSmodel sos, boolean isUrlPresent, boolean isPostedImgsPresent) {

        if(isPostedImgsPresent && isUrlPresent){
            return LinksAndKeys.TYPE_IMAGE_AND_MESSAGE_AND_URL;
        }else if(!isPostedImgsPresent && isUrlPresent){
            return LinksAndKeys.TYPE_MESSAGE_AND_URL;
        }else if(isPostedImgsPresent && !isUrlPresent){
            return LinksAndKeys.TYPE_IMAGE_AND_MESSAGE_AND_URL;
        }else{
            return LinksAndKeys.TYPE_MESSAGE;
        }


    }

    private int getCommentsCnt(SOSmodel sos) {
        return sos.getRepliesCount();
    }

    private int getLikeCnt(SOSmodel sos) {
        return sos.getLikesCount();
    }

    private long getTime(SOSmodel sos) {

        long time = 0;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SS'Z'");
        format.setTimeZone(TimeZone.getTimeZone("GMT"));

        try {
            Date date = format.parse(sos.getCreatedAt());
            Calendar gcal = new GregorianCalendar();
            gcal.setTime(date);
            gcal.add(Calendar.SECOND, -50);
            date = gcal.getTime();
            time = date.getTime();
            date.setTime(time);
        }catch(Exception ex){
            ex.printStackTrace();
        }

        return time;

    }

    private String getName(SOSmodel sos) {
        return sos.getUserName();
    }

    private String getImage(SOSmodel sos) {
        return sos.getUserAvatar();
    }

    private SpannableStringBuilder getMessage(SOSmodel sos) {
        return setDeepLink(sos);
    }

    @Nullable
    private SpannableStringBuilder setDeepLink(SOSmodel sos) {

        String id = null,replaced = null;
        String getpost = StringEscapeUtils.unescapeJava(" "+sos.getPost());


        if (getpost!= null) {
            SpannableStringBuilder ss = new SpannableStringBuilder(getpost); // ss
            StringTokenizer stoken = new StringTokenizer(ss.toString(), "¶");

            while (stoken.hasMoreTokens()) {
                String tmp = "";
                boolean flag = false;
                String data = stoken.nextToken();
                int startindex = -1;
                if (data.startsWith("@")) {
                    startindex = ss.toString().indexOf(data);
                    flag = true;
                } else {
                    flag = false;
                    int index = data.indexOf("@");
                    if (index != -1) {
                        tmp = data.substring(index);
                        startindex = ss.toString().indexOf(tmp);
                    }
                }
                List<String> splitusers = Arrays.asList(data.split(" "));
                for (final String eachComment : splitusers) {
                    int lastindex = -1;
                    //     int startindex=eachComment.toString().indexOf("@");;
                    if (flag)
                        lastindex = eachComment.length();
                    else
                        lastindex = startindex + tmp.length();

                    if (eachComment != null && eachComment.startsWith("@")) {
                        if (eachComment.contains(":")) {
                            String[] Name = eachComment.split(":");
                            id = Name[0];
                            if (id.startsWith("@")) {
                                id = id.replaceFirst("@", "");
                            }
                            replaced = Name[1].replace('%', ' ');  // final string

                            if (startindex != -1 && (lastindex != -1 && lastindex > startindex))
                                ss.replace(startindex, lastindex, replaced);
                        }

                        SOSPostsAdapter.TouchableSpan clickableSpan = new SOSPostsAdapter.TouchableSpan() {
                            @Override
                            public void onClick(View TextView) {
                                this.setPressed(true);
                                String extravar = this.getMyVar();
                                Intent i = new Intent(context, UserProfileActivity.class);
                                Bundle bundle = new Bundle();
                                bundle.putString("User_Profile_Id", extravar);
                                i.putExtra("fromUserprofile", "fromUserprofile");
                                i.putExtras(bundle);
                                (context).startActivityForResult(i, 66);
                            }

                            @Override
                            public void updateDrawState(TextPaint ds) {
                                ds.setColor(ds.linkColor);    // you can use custom color
                                ds.setUnderlineText(false);    // this remove the underline
                            }

                            private boolean mIsPressed;

                            public void setPressed(boolean isSelected) {
                                mIsPressed = isSelected;
                            }
                        };


                        if (ss.toString().contains("¶")) {
                            ss = SpannableStringBuilder.valueOf(ss.toString().replace("¶", ""));
                        }
                        if (ss.toString().contains("`")) {
                            ss = SpannableStringBuilder.valueOf(ss.toString().replace("`", ""));
                        }


                        clickableSpan.setMyVar(id);



                        if (replaced != null && replaced.length() > 0) {
                            int edge = replaced.length();
                            int totalssLength = ss.toString().indexOf(replaced);

                            if (totalssLength != -1)
                                ss.setSpan(clickableSpan, totalssLength, edge + totalssLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                        }
                    }
                }
            }

            return ss;

        }

        return null;
    }


}

日志:

 PID: 25427
    java.lang.RuntimeException: An error occurred while executing doInBackground()
        at android.os.AsyncTask$3.done(AsyncTask.java:309)
        at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
        at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
        at java.util.concurrent.FutureTask.run(FutureTask.java:242)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
        at java.lang.Thread.run(Thread.java:818)
     Caused by: java.lang.StringIndexOutOfBoundsException: length=744; regionStart=44; regionLength=-45
        at java.lang.String.startEndAndLength(String.java:298)
        at java.lang.String.substring(String.java:1087)
        at me.kaelaela.opengraphview.OGParser.setOGData(OGParser.java:115)
        at me.kaelaela.opengraphview.OGParser.parse(OGParser.java:67)
        at me.kaelaela.opengraphview.network.tasks.LoadOGDataTask.doInBackground(LoadOGDataTask.java:49)
        at me.kaelaela.opengraphview.network.tasks.LoadOGDataTask.doInBackground(LoadOGDataTask.java:11)
        at android.os.AsyncTask$2.call(AsyncTask.java:295)
        at java.util.concurrent.FutureTask.run(FutureTask.java:237)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) 
        at java.lang.Thread.run(Thread.java:818) 

1 个答案:

答案 0 :(得分:1)

您的以下代码正在检查两个前缀,因此不应在给定时间同时检查两个前缀。因此您应该使用||代替&&

if (!a.substring(0, prefix.length()).equalsIgnoreCase(prefix) && !a.substring(0, prefix1.length()).equalsIgnoreCase(prefix1)) {
   a = prefix + a;
}