为什么在安卓提取的Json给人一种例外? [英] why Extracting Json in android giving an exception?

查看:226
本文介绍了为什么在安卓提取的Json给人一种例外?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从一个url这是给一个JSON array.i试图消除JSON对象值 Toast.makeText() doInBackgound()方法。但它的崩溃。

请帮忙。 code是如下:

MainActivity.java

 公共类MainActivity扩展ActionBarActivity {        静态的ArrayList<&位图GT;位=新的ArrayList<&位图GT;();
        ArrayList的<&HashMap的LT;字符串,字符串>> JSON =新的ArrayList<&HashMap的LT;字符串,字符串>>();
        私人静态字符串url=\"http://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=7b414d5858e1af7c06a9fb87a11ea64b\";        @覆盖
        保护无效的onCreate(捆绑savedInstanceState){
            super.onCreate(savedInstanceState);
            的setContentView(R.layout.activity_main);
            新Background().execute(\"http://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=7b414d5858e1af7c06a9fb87a11ea64b\");
        }        @覆盖
        公共布尔onCreateOptionsMenu(菜单菜单){
            //充气菜单;如果是present这增加了项目操作栏。
            。getMenuInflater()膨胀(R.menu.menu_main,菜单);
            返回true;
        }        @覆盖
        公共布尔onOptionsItemSelected(菜单项项){
            //处理动作栏项目点击这里。操作栏会
            //自动处理上点击主页/向上按钮,只要
            //你在AndroidManifest.xml中指定一个父活动。
            INT ID = item.getItemId();            // noinspection SimplifiableIfStatement
            如果(ID == R.id.action_settings){
                返回true;
            }            返回super.onOptionsItemSelected(项目);
        }        类Background扩展的AsyncTask<弦乐,太虚,太虚> {            @覆盖
            保护无效doInBackground(串...字符串){
                JsonParser J =新JsonParser();
                JSONArray空气= j.getJsonFrmUrl(URL);                的for(int i = 0; I< air.length();我++){
                    尝试{
                        JSONObject的C = air.getJSONObject(I)
                        串图象=htt​​p://image.tmdb.org/t/p/w185/+ c.getString(backdrop_path);
                        字符串ID = c.getString(ID);
                        字符串title = c.getString(ORIGINAL_TITLE);
                        HashMap的<字符串,字符串>地图=新的HashMap<字符串,字符串>();
                        map.put(backdrop_path,图像);
                        map.put(ID,身份证);
                        map.put(ORIGINAL_TITLE称号);
                        json.add(地图);
                        Toast.makeText(MainActivity.this,图像,Toast.LENGTH_LONG).show();                        bitmap.add(BitmapFactory.de codeStream((InputStream的)新的URL(图片).getContent()));                    }
                    赶上(例外五){                    }
                }
                返回null;
            }            @覆盖
            保护无效onPostExecute(虚空避免){
                super.onPostExecute(避免);
            }
        }
    }


解决方案

不要把 Toast.makeText(MainActivity.this,图像,Toast.LENGTH_LONG).show(); doInBackground(串...字符串) mehod。

此方法是在后台线程进行计算。

您可以写 Toast.makeText(MainActivity.this,图像,Toast.LENGTH_LONG).show();
的onCreate(捆绑savedInstanceState)

为您所呼叫
新背景()执行(YOUR_URL); 从那里。
与您的一切活动应该在UI线程来完成。

该UIThread执行是为您的应用程序的主线程。这是大多数应用程序code的运行。您的所有应用程序组件(活动,服务,ContentProviders,BroadcastReceivers)都在此线程创建的,任何系统调用这些组件在这个线程执行。的

例如,假设您的应用程序是一个Activity类。随后的生命周期方法和所有的大部分事件处理code是在这个UIThread运行。这些都是像的onCreate 的onPause 的onDestroy ,<方法code>的onClick 等。此外,这是所有的更新到用户界面制成。任何导致用户界面进行更新或更改具有UI线程上发生的。


  

有关您参考进程和线程


当你明确地产生一个新的线程来完成工作的背景,code未在UIThread运行。如果后台线程需要做一些改变UI会发生什么?这就是 runOnUiThread 是。其实你应该使用一个处理程序(见下面的链接以获取更多信息)。它提供了这些后台线程执行code,可以修改UI的能力。他们通过把UI的修改code在Runnable对象,并把它传递给 runOnUiThread 办法做到这一点。

工作线程

I am trying to extract json object values from a url which is giving a json array.i tried removing Toast.makeText() from the doInBackgound() method. But its crashing.

Please help. Code is as following:

MainActivity.java

public class MainActivity extends ActionBarActivity {

        static ArrayList<Bitmap>bitmap=new ArrayList<Bitmap>();
        ArrayList<HashMap<String,String>> json= new ArrayList<HashMap<String,String>>();
        private static String url="http://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=7b414d5858e1af7c06a9fb87a11ea64b";

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            new Background().execute("http://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=7b414d5858e1af7c06a9fb87a11ea64b");
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.menu_main, menu);
            return true;
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();

            //noinspection SimplifiableIfStatement
            if (id == R.id.action_settings) {
                return true;
            }

            return super.onOptionsItemSelected(item);
        }

        class Background extends AsyncTask<String,Void,Void> {

            @Override
            protected Void doInBackground(String... strings) {
                JsonParser j=new JsonParser();
                JSONArray air=j.getJsonFrmUrl(url);

                for(int i=0;i<air.length();i++) {
                    try{
                        JSONObject c=air.getJSONObject(i);
                        String image="http://image.tmdb.org/t/p/w185/" + c.getString("backdrop_path");
                        String id=c.getString("id");
                        String title=c.getString("original_title");
                        HashMap<String, String> map=new HashMap<String, String>();
                        map.put("backdrop_path", image);
                        map.put("id", id);
                        map.put("original_title", title);
                        json.add(map);
                        Toast.makeText(MainActivity.this,image,Toast.LENGTH_LONG).show();

                        bitmap.add(BitmapFactory.decodeStream((InputStream) new URL(image).getContent()));

                    }
                    catch(Exception e){

                    }
                }
                return null;
            }

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

解决方案

Don't put Toast.makeText(MainActivity.this,image,Toast.LENGTH_LONG).show(); in doInBackground(String...strings) mehod.

This method is to perform a computation on a background thread.

You can write Toast.makeText(MainActivity.this,image,Toast.LENGTH_LONG).show(); in onCreate(Bundle savedInstanceState) method

as you are calling new Background().execute("YOUR_URL"); from there. Everything related to your activities should be done on UI Threads.

The UIThread is the main thread of execution for your application. This is where most of your application code is run. All of your application components (Activities, Services, ContentProviders, BroadcastReceivers) are created in this thread, and any system calls to those components are performed in this thread.

For instance, let's say your application is a single Activity class. Then all of the lifecycle methods and most of your event handling code is run in this UIThread. These are methods like onCreate, onPause, onDestroy, onClick, etc. Additionally, this is where all of the updates to the UI are made. Anything that causes the UI to be updated or changed HAS to happen on the UI thread.

For your Reference Processes and Threads

When you explicitly spawn a new thread to do work in the background, this code is not run on the UIThread. So what happens if this background thread needs to do something that changes the UI? This is what the runOnUiThread is for. Actually you're supposed to use a Handler (see the link below for more info on this). It provides these background threads the ability to execute code that can modify the UI. They do this by putting the UI-modifying code in a Runnable object and passing it to the runOnUiThread method.

Worker Threads

这篇关于为什么在安卓提取的Json给人一种例外?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆