从Android中的localhost读取json

时间:2013-12-13 15:13:04

标签: android json android-listview getjson

我想从本地主机读取JSON文件但发生错误。我不知道出了什么问题。

JSONParser:

public class JSONParser {
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";
    // constructor
    public JSONParser() {
    }
    public JSONObject getJSONFromUrl(String url) {
        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            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());
        }
        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }
        // return JSON String
        return jObj;
    }
}

UpdateFromSite:

public class UpdateFromSite extends Activity {
    ListView list;
    TextView name;
    TextView description;
    TextView price;
    Button Btngetdata;
    ArrayList<HashMap<String, String>> newItemlist = new ArrayList<HashMap<String, String>>();
    //URL to get JSON Array

    private static String url = "http://localhost/json/newItem.json";
    //JSON Node Names
    private static final String TAG_ITEM = "NewItem";
    private static final String TAG_NAME = "name";
    private static final String TAG_DESCRIPTION = "description";
    private static final String TAG_PRICE = "price";
    JSONArray NewItem = null;

    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.updateapp);
        newItemlist = new ArrayList<HashMap<String, String>>();
        Btngetdata = (Button)findViewById(R.id.getdata);
        Btngetdata.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //check internet connection
                Boolean isInternetPresent = false;
                ConnectionDetector cd;
                cd = new ConnectionDetector(getApplicationContext());
                isInternetPresent = cd.isConnectingToInternet();

                if (isInternetPresent) {
                    new JSONParse().execute();  }

                else {
                    Toast.makeText(getApplicationContext(),"You don't have internet connection.",Toast.LENGTH_SHORT).show();
                                     }
                     }
        });
    }



    private class JSONParse extends AsyncTask<String, String, JSONObject> {


        private ProgressDialog pDialog;

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


            name = (TextView)findViewById(R.id.nameNewItem);
            description = (TextView)findViewById(R.id.descriptionNewItem);
            price = (TextView)findViewById(R.id.priceNewItem);
            pDialog = new ProgressDialog(UpdateFromSite.this);
            pDialog.setMessage("Getting Data ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }
        @Override
        protected JSONObject doInBackground(String... args) {
            try {
                JSONParser jParser = new JSONParser();
                // Getting JSON from URL
                JSONObject json = jParser.getJSONFromUrl(url);
                return json;
            }   catch (Exception ex){
                Toast.makeText(getApplicationContext(),"network problem",Toast.LENGTH_SHORT).show();
                return null;
            }

        }
        @Override
        protected void onPostExecute(JSONObject json) {
            pDialog.dismiss();
            try {
                // Getting JSON Array from URL
                NewItem = json.getJSONArray(TAG_ITEM);
                for(int i = 0; i < NewItem.length(); i++){
                    JSONObject c = NewItem.getJSONObject(i);

                    // Storing  JSON item in a Variable
                    String name = c.getString(TAG_NAME);
                    String description = c.getString(TAG_DESCRIPTION);
                    int price = c.getInt(TAG_PRICE);

                    // Adding value HashMap key => value
                    HashMap<String, String> map = new HashMap<String, String>();
                    map.put(TAG_NAME, name);
                    map.put(TAG_DESCRIPTION, description);
                    map.put(TAG_PRICE, Integer.toString(price));
                    newItemlist.add(map);
                    list=(ListView)findViewById(R.id.listupdate);
                    ListAdapter adapter = new SimpleAdapter(UpdateFromSite.this, newItemlist,
                            R.layout.updateapprow,
                            new String[] { TAG_NAME,TAG_DESCRIPTION, TAG_PRICE }, new int[] {
                            R.id.nameNewItem,R.id.descriptionNewItem, R.id.priceNewItem});
                    list.setAdapter(adapter);

                }
            }

            catch (Exception e) {
                Toast.makeText(getApplicationContext(),"network problem",Toast.LENGTH_SHORT).show();
            }
        }
    }


    }

错误:(logcat的)

12-12 20:43:26.292: WARN/System.err(1069): org.apache.http.conn.HttpHostConnectException: Connection to http://localhost refused
12-12 20:43:26.292: WARN/System.err(1069): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:178)
12-12 20:43:26.302: WARN/System.err(1069): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
12-12 20:43:26.302: WARN/System.err(1069): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
12-12 20:43:26.302: WARN/System.err(1069): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:359)
12-12 20:43:26.302: WARN/System.err(1069): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
12-12 20:43:26.302: WARN/System.err(1069): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
12-12 20:43:26.312: WARN/System.err(1069): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
12-12 20:43:26.312: WARN/System.err(1069): at com.example.easyshopping.JSONParser.getJSONFromUrl(JSONParser.java:31)
12-12 20:43:26.312: WARN/System.err(1069): at com.example.easyshopping.UpdateFromSite$JSONParse.doInBackground(UpdateFromSite.java:89)
12-12 20:43:26.312: WARN/System.err(1069): at com.example.easyshopping.UpdateFromSite$JSONParse.doInBackground(UpdateFromSite.java:65)
12-12 20:43:26.312: WARN/System.err(1069): at android.os.AsyncTask$2.call(AsyncTask.java:185)
12-12 20:43:26.312: WARN/System.err(1069): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
12-12 20:43:26.312: WARN/System.err(1069): at java.util.concurrent.FutureTask.run(FutureTask.java:138)
12-12 20:43:26.312: WARN/System.err(1069): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
12-12 20:43:26.332: WARN/System.err(1069): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
12-12 20:43:26.332: WARN/System.err(1069): at java.lang.Thread.run(Thread.java:1019)
12-12 20:43:26.345: WARN/System.err(1069): Caused by: java.net.ConnectException: /127.0.0.1:80 - Connection refused
12-12 20:43:26.352: WARN/System.err(1069): at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:207)
12-12 20:43:26.352: WARN/System.err(1069): at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:437)
12-12 20:43:26.352: WARN/System.err(1069): at java.net.Socket.connect(Socket.java:983)
12-12 20:43:26.352: WARN/System.err(1069): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
12-12 20:43:26.352: WARN/System.err(1069): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:143)
12-12 20:43:26.352: WARN/System.err(1069): ... 15 more
12-12 20:43:26.364: ERROR/Buffer Error(1069): Error converting result java.lang.NullPointerException
12-12 20:43:26.364: ERROR/JSON Parser(1069): Error parsing data org.json.JSONException: End of input at character 0 of
12-12 20:43:26.502: WARN/InputManagerService(77): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@4089e480

myJsonFile:

{"NewItem:":[{"name":"Roast Ground Coffee","description":"Folgers Medium Classic Roast Ground Coffee 339 oz","price":8},{"name":"Seattle coffee","description":"Seattles Best Coffee Level 3 Whole Bean 12oz","price":10},{"name":"Medium Roast Bean Coffee","description":"Dunkin Donuts Original Blend Medium Roast Whole Bean Coffee 12 oz","price":6},{"name":"Espresso coffee","description":"Starbucks Dark Espresso Roast Whole Bean Coffee 12 oz","price":12},
{"name":"China Green Tea","description":"Tazo China Green Tips Tea 20 filterbags","price":8},{"name":"China Organic Green","description":"Uncle Lees Legends of China Organic Green Tea 100 Tea Bags","price":15},{"name":"Black Tea","description":"Tazo Earl Grey Black Tea 20 count","price":10},{"name":"Chai Spiced Black Tea","description":"Tazo Decaf Chai Spiced Black Tea Latte Concentrate 32 oz","price":5},
{"name":"Passion Tea","description":"Tazo Iced Passion Tea 6ct","price":11},{"name":"Peach Iced Tea","description":"Lipton Diet Peach Iced Tea Mix 2.9 oz","price":12}]}

0 个答案:

没有答案