0

我正在使用谷歌获取货币并使用 json 我应该获取货币的价值,但出现错误。“可惜,xxx停了。”

String result = null;

我的异步任务

private class usdjson extends AsyncTask<URL, Void, JSONObject> {

       @Override
        protected JSONObject doInBackground(URL... urls) {
               DefaultHttpClient   httpclient = new DefaultHttpClient(new BasicHttpParams());
               HttpPost httppost = new HttpPost("http://www.google.com/ig/calculator?hl=en&q=2GBP=?USD");
               httppost.setHeader("Content-type", "application/json");
                            InputStream inputStream = null;
                            try {
                                HttpResponse response = httpclient.execute(httppost);           
                                HttpEntity entity = response.getEntity();

                                inputStream = entity.getContent();
                                // json is UTF-8 by default
                                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
                                StringBuilder sb = new StringBuilder();

                                String line = null;
                                while ((line = reader.readLine()) != null)
                                {
                                    sb.append(line + "\n");
                                }
                                result = sb.toString();
                               Log.e("Log", result);
                            } catch (Exception e) { 
                                // Oops
                            }
                            finally {
                                try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
                            }

                            JSONObject object = null;
                            try {
                                object = new JSONObject(result);
                            } catch (JSONException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                            JSONArray Jarray = null;
                            try {
                                Jarray = object.getJSONArray("lhs");
                            } catch (JSONException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                            JSONObject Jasonobject = null;
                            for (int i = 0; i < Jarray.length(); i++) {
                            try {
                                Jasonobject = Jarray.getJSONObject(i);
                            } catch (JSONException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                            }
                        return Jasonobject;

        }

       @Override
        protected void onPostExecute(JSONObject jsonData) {
           value.setText(result);
        }
    }

我的按钮点击

.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            new usdjson().execute();
                            }
                    });

日志猫:

08-30 21:21:51.769: E/AndroidRuntime(28903): FATAL EXCEPTION: AsyncTask #1
08-30 21:21:51.769: E/AndroidRuntime(28903): java.lang.RuntimeException: An error occured while executing doInBackground()
08-30 21:21:51.769: E/AndroidRuntime(28903):    at android.os.AsyncTask$3.done(AsyncTask.java:299)
08-30 21:21:51.769: E/AndroidRuntime(28903):    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
08-30 21:21:51.769: E/AndroidRuntime(28903):    at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
08-30 21:21:51.769: E/AndroidRuntime(28903):    at java.util.concurrent.FutureTask.run(FutureTask.java:239)
08-30 21:21:51.769: E/AndroidRuntime(28903):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
08-30 21:21:51.769: E/AndroidRuntime(28903):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
4

3 回答 3

3

使用AsyncTask进行网络操作,因为 Android API Level-10 及更高版本不支持主 UI 线程上的网络操作。创建 Activity 的子类(使其扩展 AsyncTask),然后将代码移至子类的doInBackgroundonPostExecute方法。在onClickListener中使用 execute 方法调用子类。此外,不要使用多个 try catch 块,而是使用 try 块并为它们编写多个 catch 语句。AsyncTask 的 android 文档 http://developer.android.com/reference/android/os/AsyncTask.html

setOnClickListener(new View.OnClickListener() {     
       @Override 
       public void onClick(View v) {
                new FetchData().execute(); // here FetchData is the name of the subclass
                 }
             });

FetchData 类的代码是

class FetchData extends AsyncTask<String, String, String>
{
      JSONObject object = null;
      JSONArray JArray = null;
      protected String doInBackground(String...params)
       {
       try { 
        DefaultHttpClient   httpclient = new DefaultHttpClient(new BasicHttpParams());
                        HttpPost httppost = new HttpPost("http://www.google.com/ig/calculator?hl=en&q=2GBP=?USD");
                        httppost.setHeader("Content-type", "application/json");
        InputStream inputStream = null;
                            HttpResponse response = httpclient.execute(httppost);           
                            HttpEntity entity = response.getEntity();

                            inputStream = entity.getContent();
                            // json is UTF-8 by default 
                            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
                            StringBuilder sb = new StringBuilder();

                             String line = null;
                            while ((line = reader.readLine()) != null)
                            { 
                                sb.append(line + "\n");
                            } 
                            result = sb.toString();
                            object = new JSONObject(result);
                            Jarray = object.getJSONArray("lhs");
                          } catch (Exception e) { 
                            e.printStackTrace();
                        } catch(JSONException e){
                            e.printStackTrace():
                         }
                       }
protected void onPostExecute(String url){
      try{
      for (int i = 0; i < Jarray.length(); i++) 
                           {
                               JSONObject Jasonobject = Jarray.getJSONObject(i);//you can access all your data using this JSONObject
                          }
    } catch(JSONException e){
      e.printStackTrace();
     }
  }
 }
}

我还认为您有一些未处理的 InputStreamException 可能导致您的应用程序崩溃。

于 2013-08-30T18:48:19.663 回答
1

正如 Selvin 所提到的,您正试图在主线程上执行网络操作,这会导致错误。为避免这种情况,您需要在另一个线程中执行这些网络操作。

实现这一目标的最常见方法是使用扩展的类:http AsyncTask: //developer.android.com/reference/android/os/AsyncTask.html

扩展 AsyncTask 时,您将不得不重写几个方法,特别是doInBackground()onPostExecute(). 第一个将用于在后台进行网络操作,第二个将处理您将在第一个中返回的结果。

在您的情况下,网络操作在DefaultHttpClient httpclient.....直到value.setText(result);(不包括在内)之后开始。这必须在doInBackground. 不要忘记返回result变量。

您的其余代码,实际上该行value.setText(result);必须移至onPostExecute(). 您将在那里检索result并进行处理。

编辑

关于你的另一个问题,你应该有:

private class usdjson extends AsyncTask<URL, Void, JSONObject> {

   @Override
    protected JSONObject doInBackground(URL... urls) {

           DefaultHttpClient   httpclient = new DefaultHttpClient(new BasicHttpParams());
           HttpPost httppost = new HttpPost(urls[0]);
           httppost.setHeader("Content-type", "application/json");

                        InputStream inputStream = null;
                        try {
                            HttpResponse response = httpclient.execute(httppost);           
                            HttpEntity entity = response.getEntity();

                            inputStream = entity.getContent();
                            // json is UTF-8 by default
                            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
                            StringBuilder sb = new StringBuilder();

                            String line = null;
                            while ((line = reader.readLine()) != null)
                            {
                                sb.append(line + "\n");
                            }
                            result = sb.toString();
                        } catch (Exception e) { 
                            // Oops
                        }
                        finally {
                            try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
                        }

                        JSONObject object = null;
                        try {
                            object = new JSONObject(result);
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        JSONArray Jarray = null;
                        try {
                            Jarray = object.getJSONArray("lhs");
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        JSONObject Jasonobject;
                        for (int i = 0; i < Jarray.length(); i++) {
                        try {
                            Jasonobject = Jarray.getJSONObject(i);
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        }
                    return Jasonobject 

    }

   @Override
    protected void onPostExecute(JSONObject jsonData) {
         value.setText(result);
    }
}
于 2013-08-30T17:04:28.123 回答
1

在这种情况下,AsyncTask 不是最好的方法,请尝试:

private void convert() {
    new Thread(new Runnable() {

        @Override
        public void run() {
            String url = "http://www.google.com/ig/calculator?hl=en&q="+amount+"GBP=?USD";

            String request = "THE RESULT OF YOUR HTTP REQUEST";

            try {
                JSONObject jsonObject = new JSONObject(request);

                final String result = jsonObject.getString("rhs");

                handler.post(new Runnable() {

                    @Override
                    public void run() {
                        value.setText(result);
                    }

                });

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

        }

    }).start();
}
于 2013-08-30T19:10:17.483 回答