JSON到Android的错误 [英] JSON to Android error

查看:49
本文介绍了JSON到Android的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a successfully converted data from database into json format, my json data is as follows

{"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解析器代码为

I want to view these data on android, my json parser code is

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数据

my view room java file is intended to extract the json data

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活动类旨在仅显示有关点击房间的数据, 如下

the singleroom activity class is intended to show data about clicked room only, it is as follows

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);
}

}

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

and here is the log cat error i get. :(

http://pastebin.com/q4yQxKvF

推荐答案

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

Try using the below code inside your viewroom activity below setContentView() to avoid networkOnmainThread exception..

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

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

But, doing heavy operation inside background thread using AsyncTask without blocking main thread would be great!

这篇关于JSON到Android的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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