0

我很抱歉这个菜鸟问题,但我只是不知道如何解决这个问题......

1:我在连接 USB 的手机上测试时收到此错误,但在执行搜索时在 AVD 上没有收到此错误。

Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject

2:在 AVD 中运行时,第一次 JSON 搜索成功,但一旦退出并尝试访问新搜索,结果为空。下面是搜索后实例化的 JSON 列表活动:

    package com.example.georgiahistoricalmarkers;

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

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;
import android.widget.Toast;

public class MainListActivity extends ListActivity {

    // url to make request
    private static String url = "http://www.georgiaplanning.com/DCAMarkerService/dcamarkerservice.markerservice.svc/rest/Locations?SearchText=";

    // JSON Node names
    private static final String TAG_MARKERSINRANGE = "GetAllMarkersInRangeResult";
    private static final String TAG_DCAID = "DCA_ID";
    private static final String TAG_MARKERTITLE = "MarkerTitle";
    private static final String TAG_MARKERLATITUDE = "MarkerLatitude";
    private static final String TAG_MARKERLONGITUDE = "MarkerLongitude";

    // contacts JSONArray
    JSONArray markersInRange = null;

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

        String value = null;
        Bundle extras = getIntent().getExtras();
        if(extras != null){
            value = extras.getString("markerSearch");
        }

        url = (url+value);

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

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

        // getting JSON string from URL
        JSONObject json = jParser.getJSONFromUrl(url);

        try {
            // Getting Array of Contacts
            markersInRange = json.getJSONArray(TAG_MARKERSINRANGE);

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

                // Storing each json item in variable
                int dcaid = c.getInt(TAG_DCAID);
                String markertitle = c.getString(TAG_MARKERTITLE);
                double markerlongitude = c.getDouble(TAG_MARKERLATITUDE);
                double markerlatitude = c.getDouble(TAG_MARKERLONGITUDE);

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

                // adding each child node to HashMap key => value
                map.put(TAG_DCAID, Integer.toString(dcaid));
                map.put(TAG_MARKERTITLE, markertitle);
                map.put(TAG_MARKERLONGITUDE, Double.toString(markerlongitude));
                map.put(TAG_MARKERLONGITUDE, Double.toString(markerlatitude));

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

        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(this, markerList,
                R.layout.list_item,
                new String[] { TAG_MARKERTITLE, TAG_DCAID }, new int[] {
                        R.id.title, R.id.dcaid });

        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 passId = ((TextView) view.findViewById(R.id.dcaid)).getText().toString();

                // Starting new intent
                Intent in = new Intent(getApplicationContext(), SingleItemActivity.class);
                in.putExtra(TAG_DCAID, passId);
                startActivity(in);

            }
        });



    }

}

如果这可能有助于理解这个问题,下面是我的清单:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.georgiahistoricalmarkers"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.example.georgiahistoricalmarkers.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".MainListActivity"
        android:label="MainListActivity" >
    </activity>
    <activity
        android:name=".SingleItemActivity"
        android:label="SingleItemActivity" >
    </activity>
</application>

4

1 回答 1

0

我们应该在您的 http 请求标头中添加“application/x-www-form-urlencoded”

在您的情况下,您正在等待接收 json,因此添加以下内容:

    httpost.setHeader("Content-type", "application/json;charset=utf8");
    request.setHeader("Accept", "application/json");

问题是您收到的响应是 html 而不是 json。希望这对你有用,如果有用,请告诉我。

/ * EDIT * / 使用这个解析器:

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

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
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() {

}

public JSONObject getJSONFromUrl(String url) {

    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);

        httpGet.setHeader("Content-type", "application/json;charset=utf8");
        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);
        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;

}

您还应该在线程或异步线程中执行请求。否则,您将在 4.0 至更高版本的设备中出现网络异常。这就是我解决您的活动的方式:

    public class MainListActivity extends ListActivity {



// url to make request
        private static String url = "http://www.georgiaplanning.com/DCAMarkerService/dcamarkerservice.markerservice.svc/rest/Locations?SearchText=";

        // JSON Node names
        private static final String TAG_MARKERSINRANGE = "GetAllMarkersInRangeResult";
        private static final String TAG_DCAID = "DCA_ID";
        private static final String TAG_MARKERTITLE = "MarkerTitle";
        private static final String TAG_MARKERLATITUDE = "MarkerLatitude";
        private static final String TAG_MARKERLONGITUDE = "MarkerLongitude";

        // contacts JSONArray
        JSONArray markersInRange = null;

        private ArrayList<HashMap<String, String>> markerList;

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

            String value = null;
            Bundle extras = getIntent().getExtras();
            if (extras != null) {
                value = extras.getString("markerSearch");
            }

            url = (url + value);

            markerList = new ArrayList<HashMap<String, String>>();

            new DoMarkersSearchTask().execute();

        }

        class DoMarkersSearchTask extends AsyncTask<Void, Void, Void> {

            @Override
            protected Void doInBackground(Void... params) {
                // Creating JSON Parser instance
                JSONParser jParser = new JSONParser();

                // getting JSON string from URL
                JSONObject json = jParser.getJSONFromUrl(url);

                try {
                    // Getting Array of Contacts
                    markersInRange = json.getJSONArray(TAG_MARKERSINRANGE);

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

                        // Storing each json item in variable
                        int dcaid = c.getInt(TAG_DCAID);
                        String markertitle = c.getString(TAG_MARKERTITLE);
                        double markerlongitude = c.getDouble(TAG_MARKERLATITUDE);
                        double markerlatitude = c.getDouble(TAG_MARKERLONGITUDE);

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

                        // adding each child node to HashMap key => value
                        map.put(TAG_DCAID, Integer.toString(dcaid));
                        map.put(TAG_MARKERTITLE, markertitle);
                        map.put(TAG_MARKERLONGITUDE, Double.toString(markerlongitude));
                        map.put(TAG_MARKERLONGITUDE, Double.toString(markerlatitude));

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

            @Override
            protected void onPostExecute(Void result) {
                /**
                 * Updating parsed JSON data into ListView
                 * */
                ListAdapter adapter = new SimpleAdapter(getApplicationContext(), markerList, R.layout.list_item,
                        new String[] { TAG_MARKERTITLE, TAG_DCAID }, new int[] { R.id.title, R.id.dcaid });

                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 passId = ((TextView) view.findViewById(R.id.dcaid)).getText().toString();

                        // Starting new intent
                        Intent in = new Intent(getApplicationContext(), SingleItemActivity.class);
                        in.putExtra(TAG_DCAID, passId);
                        startActivity(in);

                    }
                });
            }

        }

    }

希望这最终对你有用:)

于 2013-10-09T21:53:41.710 回答