java.lang.IllegalStateException何时以json对象字符串

时间:2016-04-17 17:17:11

标签: java android json

我有< img>我试图解析的json中的标签。我在this question中使用了接受的答案来显示 图片。但该应用程序崩溃了java.lang.IllegalStateException。 下面是类和堆栈跟踪:

PostDetails

public class PostDetails extends AppCompatActivity {

    private final String TAG = "PostDetails";


    TextView postTitle, postAuthorDate, postContent, labelHold, dpostLabel;
    View firstView, secView;
    CircularNetworkImageView authorImg;
    ImageLoader AuthImgLoader;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_post_details);

        postTitle = (TextView) findViewById(R.id.dpost_title);
        postAuthorDate = (TextView) findViewById(R.id.author_date);
        postContent = (TextView) findViewById(R.id.dpost_content);
        authorImg = (CircularNetworkImageView) findViewById(R.id.author_img);
        labelHold = (TextView) findViewById(R.id.label_hold);
        dpostLabel = (TextView) findViewById(R.id.dpost_label);
        firstView =  findViewById(R.id.dviewtop);
        secView =  findViewById(R.id.dviewbottom);

        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }



        if (savedInstanceState != null) {
            postTitle.setText(savedInstanceState.getString("postTitle"));
            postAuthorDate.setText(savedInstanceState.getString("posAuthorDate"));
            postContent.setText(savedInstanceState.getString("postContent"));

            //Unhiding views
            postTitle.setVisibility(View.VISIBLE);
            postAuthorDate.setVisibility(View.VISIBLE);
            postContent.setVisibility(View.VISIBLE);
            authorImg.setVisibility(View.VISIBLE);
            labelHold.setVisibility(View.VISIBLE);
            dpostLabel.setVisibility(View.VISIBLE);
            firstView.setVisibility(View.VISIBLE);
            secView.setVisibility(View.VISIBLE);
        } else {
            if (NetworkCheck.isAvailableAndConnected(this)) {
                //Calling method to load posts
                loadPost();
            } else {
                final Context context;
                context = this;
                final AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
                alertDialog.setTitle(R.string.alert_titl);
                alertDialog.setCancelable(false);
                alertDialog.setIcon(R.mipmap.ic_launcher);
                alertDialog.setMessage(R.string.failed_post);
                alertDialog.setPositiveButton(R.string.alert_retry, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (!NetworkCheck.isAvailableAndConnected(context)) {
                            alertDialog.show();
                        } else {
                            loadPost();
                        }
                    }
                });
                alertDialog.setNegativeButton(R.string.alert_cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                });
                alertDialog.show();
            }
        }
    }

    private void loadPost() {
        Log.d(TAG, "loadPost called");

        final ProgressBar progressBar;
        progressBar = (ProgressBar) findViewById(R.id.progress_circle);
        progressBar.setVisibility(View.VISIBLE);


        int news_id = getIntent().getIntExtra("PostId", -1);
        Log.d(TAG, "You clicked post id " + news_id);

        final JsonObjectRequest jsonObjReq = new JsonObjectRequest( DetailConfig.GET_DURL + news_id, null,


                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d("Debug", response.toString());

                        //Unhiding views
                        postTitle.setVisibility(View.VISIBLE);
                        postAuthorDate.setVisibility(View.VISIBLE);
                        postContent.setVisibility(View.VISIBLE);
                        authorImg.setVisibility(View.VISIBLE);
                        labelHold.setVisibility(View.VISIBLE);
                        dpostLabel.setVisibility(View.VISIBLE);
                        firstView.setVisibility(View.VISIBLE);
                        secView.setVisibility(View.VISIBLE);

                        //Dismissing progressbar;
                        if (progressBar != null) {
                            progressBar.setVisibility(View.GONE);
                        }

                        //Calling method to parse json array
                        parsePost(response);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.d("", "Error: " + error.getMessage());
                    }
                });

        //Creating request queue
        RequestQueue requestQueue = Volley.newRequestQueue(this);

        //Adding request to queue
        requestQueue.add(jsonObjReq);
    }

    //This method will parse json data of post
    private void parsePost(JSONObject jsonObject) {

        Log.d(TAG, "Parsing post array");


            try {
                String title = jsonObject.getString(DetailConfig.TAG_DPOST_TITLE);
                postTitle.setText(Html.fromHtml(title));

                JSONObject pAuthor = jsonObject.getJSONObject("author");
                String author = pAuthor.getString("name");
                String authorimg = pAuthor.getString("avatar");

                AuthImgLoader = VolleyRequest.getInstance(getApplicationContext()).getImageLoader();
                AuthImgLoader.get(authorimg, ImageLoader.getImageListener(authorImg, R.drawable.ic_author, R.drawable.ic_author));
                authorImg.setImageUrl(authorimg, AuthImgLoader);


                SimpleDateFormat dateFormat = new SimpleDateFormat("dd MMMM, yyyy");
                SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
                String inputDateStr = jsonObject.getString(DetailConfig.TAG_DPOST_DATE);
                try {
                    Date inputDate = inputFormat.parse(inputDateStr);
                    String date = dateFormat.format(inputDate);
                    Resources resources = getResources();
                    String authdate= String.format(resources.getString(R.string.post_by), author, date);
                    postAuthorDate.setText(authdate);
                } catch (ParseException e) {
                    Log.d(TAG, "Error in parsing date");
                }

                String content = jsonObject.getString(DetailConfig.TAG_DPOST_CONTENT);
                Spanned spanned = Html.fromHtml(content, new UILImageGetter(postContent, this), null);
                postContent.setText(spanned);

            } catch (JSONException w) {
                w.printStackTrace();
            }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("postTitle", postTitle.getText().toString());
        outState.putString("posAuthorDate", postAuthorDate.getText().toString());
        outState.putString("postContent", postContent.getText().toString());
        //outState.putInt("authorImg", authorimg);
    }

    @Override
    public boolean onSupportNavigateUp() {
        onBackPressed();
        return true;
    }

}

UILImageGetter

public class UILImageGetter implements Html.ImageGetter{
    Context c;
    TextView conatiner;
    UrlImageDownloader urlDrawable;

    public UILImageGetter(View textView, Context context) {
        this.c = context;
        this.conatiner = (TextView) textView;
    }

    @Override
    public Drawable getDrawable(String source) {
        urlDrawable = new UrlImageDownloader(c.getResources(), source);
        urlDrawable.mDrawable = c.getResources().getDrawable(R.drawable.default_thumb);

        ImageLoader.getInstance().loadImage(source, new SimpleListener(urlDrawable));
        return urlDrawable;
    }

    private class SimpleListener extends SimpleImageLoadingListener {
        UrlImageDownloader mUrlImageDownloader;

        public SimpleListener(UrlImageDownloader downloader) {
            super();
            mUrlImageDownloader= downloader;
        }

        @Override
        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
            int width = loadedImage.getWidth();
            int height = loadedImage.getHeight();

            int newWidth = width;
            int newHeight = height;

            if (width > conatiner.getWidth()) {
                newWidth = conatiner.getWidth();
                newHeight = (newWidth * height) / width;
            }

            if (view != null) {
                view.getLayoutParams().width = newWidth;
                view.getLayoutParams().height = newHeight;
            }

            Drawable result = new BitmapDrawable(c.getResources(), loadedImage);
            result.setBounds(0, 0, newWidth, newHeight);

            mUrlImageDownloader.setBounds(0, 0, newWidth, newHeight);
            mUrlImageDownloader.mDrawable = result;

            conatiner.setHeight((conatiner.getHeight() + result.getIntrinsicHeight()));
            conatiner.invalidate();
        }

    }

    private class UrlImageDownloader extends BitmapDrawable {
        public  Drawable mDrawable;

        public UrlImageDownloader(Resources resources, String filepath) {
            super(resources, filepath);
            mDrawable = new BitmapDrawable(resources, filepath);
        }

        @Override
        public void draw(Canvas canvas) {
            if (mDrawable != null) {
                mDrawable.draw(canvas);
            }
        }
    }
}

栈跟踪

04-17 17:53:41.717 4470-4470/com.blogking.poster D/PostDetails: Parsing post array
 04-17 17:53:41.747 4470-4470/com.blogking.poster E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: https:/ahmadawais.com/wp-content/uploads/2016/04/Ahmad-Awais-Core-Contributor-for-WordPress-4.5-1024x196.jpg: open failed: ENOENT (No such file or directory)
 04-17 17:53:41.747 4470-4470/com.blogking.poster W/BitmapDrawable: BitmapDrawable cannot decode https://ahmadawais.com/wp-content/uploads/2016/04/Ahmad-Awais-Core-Contributor-for-WordPress-4.5-1024x196.jpg
 04-17 17:53:41.747 4470-4470/com.blogking.poster E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: https:/ahmadawais.com/wp-content/uploads/2016/04/Ahmad-Awais-Core-Contributor-for-WordPress-4.5-1024x196.jpg: open failed: ENOENT (No such file or directory)
 04-17 17:53:41.747 4470-4470/com.blogking.poster W/BitmapDrawable: BitmapDrawable cannot decode https://ahmadawais.com/wp-content/uploads/2016/04/Ahmad-Awais-Core-Contributor-for-WordPress-4.5-1024x196.jpg
 04-17 17:53:41.777 4470-4470/com.blogking.poster D/AndroidRuntime: Shutting down VM
 04-17 17:53:41.788 4470-4470/com.blogking.poster E/AndroidRuntime: FATAL EXCEPTION: main
                                                                    Process: com.blogking.poster, PID: 4470
                                                                    java.lang.IllegalStateException: ImageLoader must be init with configuration before using
                                                                        at com.nostra13.universalimageloader.core.ImageLoader.checkConfiguration(ImageLoader.java:613)
                                                                        at com.nostra13.universalimageloader.core.ImageLoader.loadImage(ImageLoader.java:519)
                                                                        at com.nostra13.universalimageloader.core.ImageLoader.loadImage(ImageLoader.java:425)
                                                                        at com.blogking.poster.UILImageGetter.getDrawable(UILImageGetter.java:34)
                                                                        at android.text.HtmlToSpannedConverter.startImg(Html.java:634)
                                                                        at android.text.HtmlToSpannedConverter.handleStartTag(Html.java:520)
                                                                        at android.text.HtmlToSpannedConverter.startElement(Html.java:761)
                                                                        at org.ccil.cowan.tagsoup.Parser.push(Parser.java:794)
                                                                        at org.ccil.cowan.tagsoup.Parser.rectify(Parser.java:1061)
                                                                        at org.ccil.cowan.tagsoup.Parser.stage(Parser.java:1026)
                                                                        at org.ccil.cowan.tagsoup.HTMLScanner.scan(HTMLScanner.java:632)
                                                                        at org.ccil.cowan.tagsoup.Parser.parse(Parser.java:449)
                                                                        at android.text.HtmlToSpannedConverter.convert(Html.java:442)
                                                                        at android.text.Html.fromHtml(Html.java:136)
                                                                        at com.blogking.poster.PostDetails.parsePost(PostDetails.java:198)
                                                                        at com.blogking.poster.PostDetails.access$100(PostDetails.java:34)
                                                                        at com.blogking.poster.PostDetails$3.onResponse(PostDetails.java:148)
                                                                        at com.blogking.poster.PostDetails$3.onResponse(PostDetails.java:127)
                                                                        at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
                                                                        at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
                                                                        at android.os.Handler.handleCallback(Handler.java:739)
                                                                        at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                        at android.os.Looper.loop(Looper.java:135)
                                                                        at android.app.ActivityThread.main(ActivityThread.java:5910)
                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                        at java.lang.reflect.Method.invoke(Method.java:372)
                                                                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)

在堆栈跟踪中,第198行是Spanned spanned = Html.fromHtml(content, new UILImageGetter(postContent, this), null);

第34行是public class PostDetails extends AppCompatActivity {

第148行是parsePost(response);

第127行是new Response.Listener<JSONObject>() {

有没有解决方案?

注意: UILImageGetter 正在使用Android-Universal-Image-Loader库。

1 个答案:

答案 0 :(得分:0)

如错误所示,您需要在使用之前初始化UIL。请参阅此答案:Android - ImageLoader must be init with configuration before using in UIL