2

我已经成功地将数据库中的数据转换成json格式,我的json数据如下

{"room":[{"id":"1044","location":"kathmandu","title":"room room rome",
 "quantity":"2","price":"1000","contact":"9811111111","area":"1500",
"description":"kjkfs ksdjfsd kj","address":"kat"}],"success":1}

我想在android上查看这些数据,我的json解析器代码是

package com.iwantnew.www;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

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 method
    public JSONObject 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());
        }

        // 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;

    }
}

我的视图房间 java 文件旨在提取 json 数据

package com.iwantnew.www;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
//import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class viewroom extends ListActivity {

    // url to make request
    private static String url = "http://10.0.2.2/iWant/src/android_view_all_room.php";

    // JSON Node names
    private static final String TAG_ROOM = "room";
   // private static final String TAG_SUCCESS = "success";
    private static final String TAG_ID = "id";
    private static final String TAG_LOCATION = "location";
    private static final String TAG_TITLE = "title";
    private static final String TAG_QUANTITY = "quantity";
    private static final String TAG_PRICE = "price";
    private static final String TAG_CONTACT = "contact";
    private static final String TAG_AREA = "area";
    private static final String TAG_DESCRIPTION = "description";
    private static final String TAG_ADDRESS = "address";

    // contacts JSONArray
    JSONArray room = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.view_room);

        // Hashmap for ListView
        ArrayList<HashMap<String, String>> roomList = new ArrayList<HashMap<String, String>>();

        // Creating JSON Parser instance
        JSONParser jParser = new JSONParser();

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(url, "GET", params);

        try {
            // Getting Array of Contacts
            room = json.getJSONArray(TAG_ROOM);

            // looping through All Contacts
            for(int i = 0; i < room.length(); i++){
                JSONObject c = room.getJSONObject(i);

                // Storing each json item in variable
                String id = c.getString(TAG_ID);
                String location = c.getString(TAG_LOCATION);
                String quantity = c.getString(TAG_QUANTITY);
                String address = c.getString(TAG_ADDRESS);
                String price = c.getString(TAG_PRICE);
                String contact = c.getString(TAG_CONTACT);
                String area = c.getString(TAG_AREA);
                String description = c.getString(TAG_DESCRIPTION);
                String title = c.getString(TAG_TITLE);

                // creating new HashMap
                HashMap<String, String> map = new HashMap<String, String>();

                // adding each child node to HashMap key => value
                map.put(TAG_ID, id);
                map.put(TAG_LOCATION, location);
                map.put(TAG_QUANTITY, quantity);
                map.put(TAG_ADDRESS, address);
                map.put(TAG_PRICE, price);
                map.put(TAG_CONTACT, contact);
                map.put(TAG_AREA, area);
                map.put(TAG_DESCRIPTION, description);
                map.put(TAG_TITLE, title);

                // adding HashList to ArrayList
                roomList.add(map);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }


        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(this, roomList,
                R.layout.list_room,
                new String[] { TAG_TITLE, TAG_LOCATION, TAG_PRICE }, new int[] {
                        R.id.title, R.id.location, R.id.price });
        setListAdapter(adapter);
        // selecting single ListView item
        ListView lv = getListView();
        // Launching new screen on Selecting Single ListItem
        lv.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // getting values from selected ListItem
                String title = ((TextView) view.findViewById(R.id.title)).getText().toString();
                String location = ((TextView) view.findViewById(R.id.location)).getText().toString();
                String price = ((TextView) view.findViewById(R.id.price)).getText().toString();            
                // Starting new intent
                Intent in = new Intent(getApplicationContext(), SingleRoomActivity.class);
                in.putExtra(TAG_TITLE, title);
                in.putExtra(TAG_LOCATION, location);
                in.putExtra(TAG_PRICE, price);
                startActivity(in);
            }
        });
    }
}

singleroom活动类只显示点击房间的数据,如下

package com.iwantnew.www;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class SingleRoomActivity extends Activity {


private static final String TAG_TITLE = "title";
private static final String TAG_LOCATION = "location";
private static final String TAG_PRICE = "price";

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.single_room);

    // getting intent data
    Intent in = getIntent();

    // Get JSON values from previous intent
    String title = in.getStringExtra(TAG_TITLE);
    String location = in.getStringExtra(TAG_LOCATION);
    String price = in.getStringExtra(TAG_PRICE);

    // Displaying all values on the screen
    TextView lblTitle = (TextView) findViewById(R.id.title_label);
    TextView lblLocation = (TextView) findViewById(R.id.location_label);
    TextView lblPrice = (TextView) findViewById(R.id.price_label);

    lblTitle.setText(title);
    lblLocation.setText(location);
    lblPrice.setText(price);
}

}

这是我得到的日志猫错误。:(

http://pastebin.com/q4yQxKvF

4

3 回答 3

1

根据您的代码,Exception您将获得的是NetworkOnMainThreadException

因为你是 performing Network operations on Main UI Thread

避免它AsyncTask在里面使用view room java file

在此处查看示例AsyncTask Android 示例

于 2013-08-24T12:12:26.333 回答
0

使用 ICS 及更高版本,您无法在主线程上进行网络调用(正如您所注意到的,它会引发错误),这就是您需要使用类似AsyncTask; 或者,您可以创建一个新线程(使用Runnable该类)来进行网络调用。无论哪种方式,您都没有在主线程上进行 http 调用。即使您没有使用 ICS 或 JB 设备,您也不应该在主线程上进行网络调用。

来自 Android 文档:

网络操作可能涉及不可预知的延迟。为防止这导致糟糕的用户体验,请始终在与 UI 不同的线程上执行网络操作。AsyncTask 类提供了一种从 UI 线程触发新任务的最简单方法。

这是该链接:http: //developer.android.com/training/basics/network-ops/connecting.html

于 2013-08-24T12:27:20.340 回答
0

尝试在下面的viewroom活动中使用以下代码setContentView()以避免 networkOnmainThread 异常..

if (android.os.Build.VERSION.SDK_INT > 9) {
                StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                StrictMode.setThreadPolicy(policy);
            }

但是,在不阻塞主线程的情况下使用 AsyncTask 在后台线程内执行繁重的操作会很棒!

于 2013-08-24T12:08:15.460 回答