我如何解析URL在给定的code改为每在code定义的输出? [英] How do I parse the url in the given code to read as per the output defined in the code?

查看:132
本文介绍了我如何解析URL在给定的code改为每在code定义的输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的Andr​​oid和我想用 JSON 解析URL。我得到的例外,当我运行code和我的应用程序说不幸的myapp已停止运行。我也张贴了我的的logcat 。我想读的结果
当然code:101,结果
课程名称:blahblah结果
提供学期:第一学期,第二学期,第三学期

 进口java.io.BufferedReader中;
进口java.io.IOException异常;
进口java.io.InputStreamReader中;
进口java.net.HttpURLConnection中;
进口java.net.MalformedURLException;
进口的java.net.URL;
进口java.net.URLConnection中;
进口的java.util.ArrayList;进口org.apache.http.client.ClientProtocolException;
进口org.apache.http.client.HttpClient;
进口org.apache.http.client.ResponseHandler;
进口org.apache.http.client.methods.HttpPost;
进口org.apache.http.impl.client.BasicResponseHandler;
进口org.apache.http.impl.client.DefaultHttpClient;
进口org.apache.http.params.BasicHttpParams;
进口org.apache.http.params.HttpParams;
进口org.json.JSONArray;
进口org.json.JSONException;
进口org.json.JSONObject;进口android.os.AsyncTask;
进口android.os.Bundle;
进口android.app.Activity;
进口android.app.ListActivity;
进口android.util.Log;
进口android.view.Menu;
进口android.view.View;
进口android.view.View.OnClickListener;
进口android.widget.ArrayAdapter;
进口android.widget.Button;
进口android.widget.TextView;
进口android.widget.Toast;公共类Compsci734MainActivity扩展ListActivity {    AsyncTask的<太虚,太虚,太虚> mTask;
    串jsonString;    //字符串URL = \"https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=50cent&count=2\";    字符串URL =htt​​p://redsox.tcs.auckland.ac.nz/734A/CSService.svc/courses;    //键b;
    @覆盖
    公共无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_compsci734_main);
        //getActionBar().setDisplayHomeAsUpEnabled(true);        Button按钮=(按钮)findViewById(R.id.btnFetch);
        最终的TextView电视=(的TextView)findViewById(R.id.txtView);        mTask =新的AsyncTask<太虚,太虚,太虚> (){
            @覆盖
            保护无效doInBackground(虚空...... PARAMS){
                尝试{
                    jsonString = getJsonFromServer(URL);
                }赶上(IOException异常五){
                    // TODO自动生成catch块
                    e.printStackTrace();
                }
                返回null;
            }            @覆盖
            保护无效onPostExecute(虚空结果){
                super.onPostExecute(结果);                tv.setText(jsonString);            }
        };// Button按钮=(按钮)findViewById(R.id.btnFetch);
// TextView的电视=(的TextView)findViewById(R.id.txtView);
        button.setOnClickListener(新OnClickListener(){            公共无效的onClick(视图v){
                尝试{
                    字符串URL =htt​​p://redsox.tcs.auckland.ac.nz
                                                  /734A/CSService.svc/courses;
                    HttpPost httppost =新HttpPost(URL);
                    尝试{
                        的HttpParams P =新BasicHttpParams();
                        HttpClient的HttpClient的=新DefaultHttpClient(P);
                        ResponseHandler所<串GT; ResponseHandler所=新
                                                        BasicResponseHandler();
                        字符串responseBody = httpclient.execute(httppost,
                                ResponseHandler所);
                        JSONArray jArray =新JSONArray(responseBody);
                        字符串文本=;
                        的for(int i = 0; I< jArray.length();我++){
                            JSONObject的E = jArray.getJSONObject(I)
                                文字文本= +课程编号:
                                        + e.getString(courseField)+\\ n;
                                文字文本= +课程名称:
                                         + e.getString(titleField)+\\ n;
                                文字文本= +学期所开设:
                                      + e.getString(semesterField)+\\ n;
                                //文本=文字+Birthyear:
                                //+ e.getString(birthyear)+\\ n;
                        }
                        Log.i(responseBody,文字);
                        tv.setText(文本);
                    }赶上(ClientProtocolException E){
                        e.printStackTrace();
                    }赶上(IOException异常五){
                        e.printStackTrace();
                    }                }赶上(的Throwable t)的{
                    Toast.makeText(getBaseContext(),请求失败:+
                                        t.toString(),Toast.LENGTH_LONG).show();
                    t.printStackTrace();
                }
                //tv.setText(result);
            }
        });
    }
    公共静态字符串getJsonFromServer(字符串URL)抛出IOException        BufferedReader中的InputStream = NULL;        网址jsonUrl =新的URL(网址);
        的URLConnection直流= jsonUrl.openConnection();        dc.setConnectTimeout(5000);
        dc.setReadTimeout(5000);        的InputStream =新的BufferedReader(新的InputStreamReader(
                dc.getInputStream()));        //读取JSON结果转换成字符串
        串jsonResult = inputStream.readLine();
        返回jsonResult;
    }    }

这是我的logcat:

  05-13 16:27:16.375:I / dalvikvm(1040):主题ID = 3:反应信号3
05-13 16:27:16.585:E / dalvikvm(1040):无法打开堆栈跟踪文件'/data/anr/traces.txt:是一个目录
05-13 16:27:16.585:D / AndroidRuntime(1040):关闭VM
05-13 16:27:16.595:W / dalvikvm(1040):主题ID = 1:螺纹未捕获的异常(组= 0x409c01f8)退出
05-13 16:27:16.605:E / AndroidRuntime(1040):致命异常:主要
05-13 16:27:16.605:E / AndroidRuntime(1040):了java.lang.RuntimeException:无法启动活动ComponentInfo {com.example.compsci_734p / com.example.compsci_734p.Compsci734MainActivity}了java.lang.RuntimeException:二进制XML文件行#7:你必须提供一个layout_width属性。
05-13 16:27:16.605:E / AndroidRuntime(1040):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
05-13 16:27:16.605:E / AndroidRuntime(1040):在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
05-13 16:27:16.605:E / AndroidRuntime(1040):在android.app.ActivityThread.access $ 600(ActivityThread.java:123)
05-13 16:27:16.605:E / AndroidRuntime(1040):在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1147)
05-13 16:27:16.605:E / AndroidRuntime(1040):在android.os.Handler.dispatchMessage(Handler.java:99)
05-13 16:27:16.605:E / AndroidRuntime(1040):在android.os.Looper.loop(Looper.java:137)
05-13 16:27:16.605:E / AndroidRuntime(1040):在android.app.ActivityThread.main(ActivityThread.java:4424)
05-13 16:27:16.605:E / AndroidRuntime(1040):在java.lang.reflect.Method.invokeNative(本机方法)
05-13 16:27:16.605:E / AndroidRuntime(1040):在java.lang.reflect.Method.invoke(Method.java:511)
05-13 16:27:16.605:E / AndroidRuntime(1040):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:784)
05-13 16:27:16.605:E / AndroidRuntime(1040):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
05-13 16:27:16.605:E / AndroidRuntime(1040):在dalvik.system.NativeStart.main(本机方法)
05-13 16:27:16.605:E / AndroidRuntime(1040):了java.lang.RuntimeException:通过引起二进制XML文件行#7:你必须提供一个layout_width属性。
05-13 16:27:16.605:E / AndroidRuntime(1040):在android.content.res.TypedArray.getLayoutDimension(TypedArray.java:491)
05-13 16:27:16.605:E / AndroidRuntime(1040):在android.view.ViewGroup $ LayoutParams.setBaseAttributes(ViewGroup.java:5318)
05-13 16:27:16.605:E / AndroidRuntime(1040):在android.view.ViewGroup $ MarginLayoutParams<&初始化GT;(ViewGroup.java:5439)
05-13 16:27:16.605:E / AndroidRuntime(1040):在android.widget.LinearLayout $的LayoutParams<&初始化GT;(LinearLayout.java:1776)
05-13 16:27:16.605:E / AndroidRuntime(1040):在android.widget.LinearLayout.generateLayoutParams(LinearLayout.java:1700)
05-13 16:27:16.605:E / AndroidRuntime(1040):在android.widget.LinearLayout.generateLayoutParams(LinearLayout.java:56)
05-13 16:27:16.605:E / AndroidRuntime(1040):在android.view.LayoutInflater.rInflate(LayoutInflater.java:741)
05-13 16:27:16.605:E / AndroidRuntime(1040):在android.view.LayoutInflater.inflate(LayoutInflater.java:489)
05-13 16:27:16.605:E / AndroidRuntime(1040):在android.view.LayoutInflater.inflate(LayoutInflater.java:396)
05-13 16:27:16.605:E / AndroidRuntime(1040):在android.view.LayoutInflater.inflate(LayoutInflater.java:352)
05-13 16:27:16.605:E / AndroidRuntime(1040):在com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:251)
05-13 16:27:16.605:E / AndroidRuntime(1040):在android.app.Activity.setContentView(Activity.java:1835)
05-13 16:27:16.605:E / AndroidRuntime(1040):在com.example.compsci_734p.Compsci734MainActivity.onCreate(Compsci734MainActivity.java:50)
05-13 16:27:16.605:E / AndroidRuntime(1040):在android.app.Activity.performCreate(Activity.java:4465)
05-13 16:27:16.605:E / AndroidRuntime(1040):在android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
05-13 16:27:16.605:E / AndroidRuntime(1040):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
05-13 16:27:16.605:E / AndroidRuntime(1040):11 ...更多
05-13 16:27:16.885的:I / dalvikvm(1040):主题ID = 3:反应以信号3
05-13 16:27:16.885:I / dalvikvm(1040):写的堆栈跟踪到/data/anr/traces.txt
05-13 16:27:17.155的:I / dalvikvm(1040):主题ID = 3:反应以信号3
05-13 16:27:17.165:I / dalvikvm(1040):写的堆栈跟踪到/data/anr/traces.txt


解决方案

感谢的人! :)我已经解决了它,并做了一个列表视图出于此。这是我的工作code:

 包com.example.compsci_734t;进口java.io.BufferedReader中;
进口java.io.IOException异常;
进口的java.io.InputStream;
进口java.io.InputStreamReader中;
进口java.io.UnsupportedEncodingException;
进口的java.net.URL;
进口的java.util.ArrayList;
进口java.util.zip.GZIPInputStream;进口org.apache.http.HttpEntity;
进口org.apache.http.Htt presponse;
进口org.apache.http.StatusLine;
进口org.apache.http.client.ClientProtocolException;
进口org.apache.http.client.HttpClient;
进口org.apache.http.client.methods.HttpGet;
进口org.apache.http.impl.client.DefaultHttpClient;
进口org.json.JSONArray;
进口org.json.JSONException;
进口org.json.JSONObject;进口android.app.Activity;
进口android.app.ListActivity;
进口android.os.AsyncTask;
进口android.os.Bundle;
进口android.util.Log;
进口android.widget.ArrayAdapter;
进口android.widget.ListView;公共类扩展了人们的活动{        ArrayList的<串GT;项目=新的ArrayList<串GT;();
        静态InputStream为= NULL;
        //私有静态字符串URL =;
        //私有静态字符串URL =HTTP:...;
        私有静态字符串URL =HTTP ......;
        // URL requestUrl =新的URL(网址);
        JSONArray人= NULL;
        私有静态最后弦乐TAG_COURSES =课程;
        静态的JSONObject jObj = NULL;
        静态JSON字符串=;        @覆盖
        公共无效的onCreate(捆绑savedInstanceState){
            super.onCreate(savedInstanceState);
            的setContentView(R.layout.people);
            新MyTasks()执行();
        }
        私有类MyTasks扩展的AsyncTask< URL,太虚,JSONObject的> {            @覆盖
            受保护的JSONObject doInBackground(URL网址...){
               //返回loadJSON(URL);
                尝试{
                    // defaultHttpClient
                    DefaultHttpClient的HttpClient =新DefaultHttpClient();
                    // HttpPost httpPost =新HttpPost(URL);
                    HTTPGET HTTPGET =新HTTPGET(URL);
                    HTT presponse HTT presponse = httpClient.execute(HTTPGET);                    HttpEntity httpEntity = HTT presponse.getEntity();
                    是= httpEntity.getContent();                }赶上(UnsupportedEncodingException五){
                    e.printStackTrace();
                }赶上(ClientProtocolException E){
                    e.printStackTrace();
                }赶上(IOException异常五){
                    e.printStackTrace();
                }
              尝试{
                / *的BufferedReader读者=新的BufferedReader(新的InputStreamReader(
                        是,UTF-8),8); * /
                为InputStream的InputStream =是;
                GZIPInputStream输入=新GZIPInputStream(InputStream的);
                InputStreamReader的读者=新的InputStreamReader(输入);
                在的BufferedReader =新的BufferedReader(读者);
                StringBuilder的SB =新的StringBuilder();
                串线= NULL;
                而((行= in.readLine())!= NULL){
                    sb.append(线);
                   //System.out.println(line);
                }
                is.close();
                JSON = sb.toString();
            }赶上(例外五){
                Log.e(缓冲区错误,错误转换结果+ e.toString());
            }            //尝试分析字符串到一个JSON对象            尝试{                JSONArray人=新JSONArray(JSON);
                // JSONArray人=新JSONArray(JSON);                的for(int i = 0; I< people.length();我++){
                    //System.out.println(courses.getJSONObject(ⅰ)的ToString());
                    的JSONObject p值= people.getJSONObject(ⅰ);                    //存储在变量中的每个JSON项目
                    串为person_id = p.getString(someString1);
                    items.add(为person_id);                    /*Log.v(\"--,人物:\\ n+\\ n UPI:+为person_id); * /
                }
                // jObj =新的JSONObject(JSON);
            }赶上(JSONException E){
                Log.e(JSON解析器,错误分析数据+ e.toString());
            }            //返回JSON字符串
            返回jObj;
            }            保护无效onPostExecute(JSON的JSONObject){
                ListView控件myListView =(ListView控件)findViewById(R.id.peopleList);
                myListView.setAdapter(新ArrayAdapter(getApplicationContext(),android.R.layout.simple_list_item_1,物品));
        }
        }

I am new to android and I want to parse url using json. I get exceptions when I run the code and my application says unfortunately myapp has stopped running. I have also posted my logcat. I want to read
Course code:101,
Course title : "blahblah"
Semesters offered : Semester 1, Semester 2, Semester 3

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class Compsci734MainActivity extends ListActivity {

    AsyncTask<Void, Void, Void> mTask;
    String jsonString;

    //String url = "https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=50cent&count=2";

    String url = "http://redsox.tcs.auckland.ac.nz/734A/CSService.svc/courses";

    //Button b;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_compsci734_main);
        //getActionBar().setDisplayHomeAsUpEnabled(true);

        Button button = (Button) findViewById(R.id.btnFetch);
        final TextView tv = (TextView) findViewById(R.id.txtView);

        mTask = new AsyncTask<Void, Void, Void> () {
            @Override
            protected Void doInBackground(Void... params) {
                try {
                    jsonString = getJsonFromServer(url);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return null;
            }

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

                tv.setText(jsonString);

            }
        };

//      Button button =(Button) findViewById(R.id.btnFetch);
//        TextView tv =(TextView) findViewById(R.id.txtView);
        button.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                try {
                    String url = "http://redsox.tcs.auckland.ac.nz
                                                  /734A/CSService.svc/courses";
                    HttpPost httppost = new HttpPost(url);
                    try {
                        HttpParams p = new BasicHttpParams();
                        HttpClient httpclient = new DefaultHttpClient(p);
                        ResponseHandler<String> responseHandler = new
                                                        BasicResponseHandler();
                        String responseBody = httpclient.execute(httppost,
                                responseHandler);
                        JSONArray jArray = new JSONArray(responseBody);
                        String text="";
                        for (int i = 0; i < jArray.length(); i++) {
                            JSONObject e = jArray.getJSONObject(i);
                                text = text + "Course ID :
                                        "+e.getString("courseField")+"\n";
                                text = text + "Course name :
                                         "+e.getString("titleField")+"\n";
                                text = text + "Semesters offered:
                                      "+e.getString("semesterField")+"\n";
                                //text = text + "Birthyear :
                                //        "+e.getString("birthyear")+"\n";
                        }
                        Log.i(responseBody, text);
                        tv.setText(text);
                    } catch (ClientProtocolException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                } catch (Throwable t) {
                    Toast.makeText(getBaseContext(), "Request failed: " +
                                        t.toString(), Toast.LENGTH_LONG).show();
                    t.printStackTrace();
                }    


                //tv.setText(result);
            }
        });
    }


    public static String getJsonFromServer(String url) throws IOException {

        BufferedReader inputStream = null;

        URL jsonUrl = new URL(url);
        URLConnection dc = jsonUrl.openConnection();

        dc.setConnectTimeout(5000);
        dc.setReadTimeout(5000);

        inputStream = new BufferedReader(new InputStreamReader(
                dc.getInputStream()));

        // read the JSON results into a string
        String jsonResult = inputStream.readLine();
        return jsonResult;
    }

    }

Here is my logcat:

05-13 16:27:16.375: I/dalvikvm(1040): threadid=3: reacting to signal 3
05-13 16:27:16.585: E/dalvikvm(1040): Unable to open stack trace file '/data/anr/traces.txt': Is a directory
05-13 16:27:16.585: D/AndroidRuntime(1040): Shutting down VM
05-13 16:27:16.595: W/dalvikvm(1040): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
05-13 16:27:16.605: E/AndroidRuntime(1040): FATAL EXCEPTION: main
05-13 16:27:16.605: E/AndroidRuntime(1040): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.compsci_734p/com.example.compsci_734p.Compsci734MainActivity}: java.lang.RuntimeException: Binary XML file line #7: You must supply a layout_width attribute.
05-13 16:27:16.605: E/AndroidRuntime(1040):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at android.app.ActivityThread.access$600(ActivityThread.java:123)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at android.os.Handler.dispatchMessage(Handler.java:99)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at android.os.Looper.loop(Looper.java:137)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at android.app.ActivityThread.main(ActivityThread.java:4424)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at java.lang.reflect.Method.invokeNative(Native Method)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at java.lang.reflect.Method.invoke(Method.java:511)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at dalvik.system.NativeStart.main(Native Method)
05-13 16:27:16.605: E/AndroidRuntime(1040): Caused by: java.lang.RuntimeException: Binary XML file line #7: You must supply a layout_width attribute.
05-13 16:27:16.605: E/AndroidRuntime(1040):     at android.content.res.TypedArray.getLayoutDimension(TypedArray.java:491)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at android.view.ViewGroup$LayoutParams.setBaseAttributes(ViewGroup.java:5318)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at android.view.ViewGroup$MarginLayoutParams.<init>(ViewGroup.java:5439)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at android.widget.LinearLayout$LayoutParams.<init>(LinearLayout.java:1776)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at android.widget.LinearLayout.generateLayoutParams(LinearLayout.java:1700)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at android.widget.LinearLayout.generateLayoutParams(LinearLayout.java:56)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at android.view.LayoutInflater.rInflate(LayoutInflater.java:741)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:251)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at android.app.Activity.setContentView(Activity.java:1835)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at com.example.compsci_734p.Compsci734MainActivity.onCreate(Compsci734MainActivity.java:50)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at android.app.Activity.performCreate(Activity.java:4465)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
05-13 16:27:16.605: E/AndroidRuntime(1040):     ... 11 more
05-13 16:27:16.885: I/dalvikvm(1040): threadid=3: reacting to signal 3
05-13 16:27:16.885: I/dalvikvm(1040): Wrote stack traces to '/data/anr/traces.txt'
05-13 16:27:17.155: I/dalvikvm(1040): threadid=3: reacting to signal 3
05-13 16:27:17.165: I/dalvikvm(1040): Wrote stack traces to '/data/anr/traces.txt'

解决方案

Thanks people!!! :) I have solved it and made a listview out of this. Here is my working code:

package com.example.compsci_734t;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.ArrayList;
import java.util.zip.GZIPInputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;





import android.app.Activity;
import android.app.ListActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;



public class People extends Activity{

        ArrayList<String> items = new ArrayList<String>();
        static InputStream is = null;
        //private static String url = "";
        //private static String url = "http:...";
        private static String url = "http....";
        //URL requestUrl = new URL(url);
        JSONArray people = null;
        private static final String TAG_COURSES = "Courses";
        static JSONObject jObj = null;
        static String json = "";

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.people);
            new MyTasks().execute();
        }


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

            @Override
            protected JSONObject doInBackground(URL... urls) {
               // return loadJSON(url);
                try {
                    // defaultHttpClient
                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    //HttpPost httpPost = new HttpPost(url);
                    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, "UTF-8"), 8);*/
                InputStream inputStream = is;
                GZIPInputStream input = new GZIPInputStream(inputStream);
                InputStreamReader reader = new InputStreamReader(input);
                BufferedReader in = new BufferedReader(reader);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = in.readLine()) != null) {
                    sb.append(line);
                   //System.out.println(line);
                }
                is.close();
                json = sb.toString();
            } catch (Exception e) {
                Log.e("Buffer Error", "Error converting result " + e.toString());
            }

            // try parse the string to a JSON object

            try {

                JSONArray people = new JSONArray(json);
                //JSONArray people = new JSONArray(json);

                for (int i = 0; i < people.length(); i++) {
                    //System.out.println(courses.getJSONObject(i).toString());
                    JSONObject p = people.getJSONObject(i);

                    // Storing each json item in variable
                    String person_id = p.getString("someString1");


                    items.add(person_id);

                    /*Log.v("--", "People: \n" + "\n UPI: " + person_id);*/
                }


                //jObj = new JSONObject(json);
            } catch (JSONException e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            } 

            // return JSON String
            return jObj;
            }

            protected void onPostExecute(JSONObject json) {
                ListView myListView = (ListView)findViewById(R.id.peopleList);
                myListView.setAdapter(new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1, items));
        }
        }

这篇关于我如何解析URL在给定的code改为每在code定义的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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