如何解析Android中的URL?

时间:2016-01-20 06:09:42

标签: android android-json

我有一个URL,我必须解析,然后将其数据反映到相关字段。当我以静态格式放置URL时,我能够获取数据并完成解析。 我的静态网址就像这样

            String loginUrl = "http://54.152.108.131/iphone111/getParentInput?child_id="+id+"&date="+date.toString();

但是现在我想改变它的ChldId和日期,所以我用这种格式制作了我的网址。

class ParentInputData extends
        AsyncTask<String, String, JSONObject> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

    }

    @Override
    protected JSONObject doInBackground(String... params) {
        String loginUrl = "http://54.152.108.131/iphone111/getParentInput?child_id="+id+"&date="+date.toString();
     Toast.makeText(getApplicationContext(), "value of loginUrl : " + loginUrl, Toast.LENGTH_LONG).show();
    System.out.println(loginUrl);   

     JSONParser jParser = new JSONParser();
        JSONObject json = jParser.getJSONFromUrl(loginUrl);
        return json;

    }

    @Override
    protected void onPostExecute(JSONObject json) {
        try {

            json_array = json.getJSONArray("CenterInfoData");
            for (int i = 0; i < json_array.length(); i++) {
                JSONObject c = json_array.getJSONObject(i);
                c = c.getJSONObject("ParentInput");

                String wake_up_time = c.getString("wake_up_time");
                String sleep_quality = c.getString("sleep_quality");
                String person_picking_child = c.getString("person_picking_child");
                String pick_up_time = c.getString("pick_up_time");
                String last_diaper_bm = c.getString("last_diaper_bm");
                String last_bottle_feeding = c.getString("last_bottle_feeding");
    }
}

我的代码就像这样

01-19 08:09:43.628: E/AndroidRuntime(18018): FATAL EXCEPTION: AsyncTask #3
01-19 08:09:43.628: E/AndroidRuntime(18018): Process: com.MyKidzDay, PID: 18018
01-19 08:09:43.628: E/AndroidRuntime(18018): java.lang.RuntimeException: An error occured while executing doInBackground()
01-19 08:09:43.628: E/AndroidRuntime(18018):    at android.os.AsyncTask$3.done(AsyncTask.java:300)
01-19 08:09:43.628: E/AndroidRuntime(18018):    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
01-19 08:09:43.628: E/AndroidRuntime(18018):    at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
01-19 08:09:43.628: E/AndroidRuntime(18018):    at java.util.concurrent.FutureTask.run(FutureTask.java:242)
01-19 08:09:43.628: E/AndroidRuntime(18018):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
01-19 08:09:43.628: E/AndroidRuntime(18018):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
01-19 08:09:43.628: E/AndroidRuntime(18018):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
01-19 08:09:43.628: E/AndroidRuntime(18018):    at java.lang.Thread.run(Thread.java:841)
01-19 08:09:43.628: E/AndroidRuntime(18018): Caused by: java.lang.NullPointerException
01-19 08:09:43.628: E/AndroidRuntime(18018):    at com.KidsTabs.KidSummary$ParentInputData.doInBackground(KidSummary.java:1651)
01-19 08:09:43.628: E/AndroidRuntime(18018):    at com.KidsTabs.KidSummary$ParentInputData.doInBackground(KidSummary.java:1)
01-19 08:09:43.628: E/AndroidRuntime(18018):    at android.os.AsyncTask$2.call(AsyncTask.java:288)
01-19 08:09:43.628: E/AndroidRuntime(18018):    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
01-19 08:09:43.628: E/AndroidRuntime(18018):    ... 4 more
01-19 08:09:43.644: W/EGL_genymotion(18018): eglSurfaceAttrib not implemented
01-19 08:09:44.084: I/Inside convertstream method(18018): hello

但是在这种情况下我得到Null指针异常..我调试了我的URL但它仍然显示完整的URL有ChildId和日期..我在哪里做错误..我已经尝试过URLEncoder .. 我的LogCat在这里

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public String makeHttpRequest(String url, String method,
            List<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method
            if (method == "POST") {
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            } else if (method == "GET") {
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // return JSON String
        return json;

    }
}

我的JSONParser代码就在这里..

{
    "type": "button",
    "title": "Save",
    "onClick": submitFunc
}

1 个答案:

答案 0 :(得分:1)

您收到错误是因为您在后台主题中显示 Toast

您的 doInBackground 应如下所示:

@Override
    protected Void doInBackground(Void... params) {
   // Other stuff
   runOnUiThread(new Runnable() {
      @Override
      public void run() {
          Toast.makeText(getApplicationContext(), "value of loginUrl : " + loginUrl, Toast.LENGTH_LONG).show();
            }
        });
      return null;
 }

希望这会对你有所帮助。