难以理解我的JSON解析

时间:2013-12-13 02:45:06

标签: android json

我希望通过一个简单的应用程序获得一些帮助,我正在学习谷歌地图v2 api并熟悉自己的android。我正在尝试从JSON文件解析一些信息,但它只是挂起。我发现了一些对这个错误的引用,但即使我更改了引用JSONarray的行,我也无法让它停止在app启动上。活动/ db代码/ JSON文件和错误如下所示。

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


{"places":[{"id":"1","name":"Baskketmakers Arms","address":"12 Gloucester Rd UK","phone":"01273 689006","lat":"50.827043","lng":"-0.136817"},{"id":"2","name":"The World's End","address":"60-61 London Road, UK","phone":"01273 692311","lat":"50.833698","lng":"-0.138108"},{"id":"3","name":"Burger Off!","address":"UK","phone":"01273 326655","lat":"50.825376","lng":"-0.160553"}]}


public class MainActivity extends SherlockFragmentActivity  {

    private static final String UPDATE_URL = "http://pastebin.com/b2W3PYMM";
    private SharedPreferences mPrefs;
    private ProgressDialog pDialog;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new JSON().execute();
        setupTabs();
    }

    class JSON extends AsyncTask<String, String, Void> {
        private ProgressDialog progressDialog = new ProgressDialog(
                MainActivity.this);
        InputStream is = null;
        String result = "";

        protected void onPreExecute() {


            super.onPreExecute();
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Updating Brighton Burger Locations ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(String... params) {

            String url_select = UPDATE_URL;

            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url_select);

            ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();

            try {
                httpPost.setEntity(new UrlEncodedFormEntity(param));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();

                // read content
                is = httpEntity.getContent();

            } catch (Exception e) {

                Log.e("log_tag", "Error in http connection " + e.toString());
            }
            try {
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(is));
                StringBuilder sb = new StringBuilder();
                String line = "";
                while ((line = br.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                result = sb.toString();

            } catch (Exception e) {
                // TODO: handle exception
                Log.e("log_tag", "Error converting result " + e.toString());
            }

            return null;

        }

        protected void onPostExecute(Void v) {

            BurgerDBHandler dbHelper = new BurgerDBHandler(getApplicationContext());
            dbHelper.open();


            try {
                JSONObject object = new JSONObject(result);
                JSONArray Jarray = object.getJSONArray("places");

                for (int i = 0; i < Jarray.length(); i++) {
                    JSONObject Jasonobject = Jarray.getJSONObject(i);
                    dbHelper.insert(Jasonobject.getString("name"),
                            Jasonobject.getString("location"),
                            Jasonobject.getString("phone"), 
                            Jasonobject.getDouble("lat"),
                            Jasonobject.getDouble("lng"));  
                }
                dbHelper.close();
                pDialog.dismiss();

            } catch (Exception e) {
                // TODO: handle exception
                Log.e("log_tag", "Error parsing data " + e.toString());
            }
        }       }


    private void setupTabs() {

        ActionBar actionbar = getSupportActionBar();
        actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        actionbar.setTitle("Brighton Burgers");

        ActionBar.Tab Tab1 = actionbar.newTab().setText("Map View Tab");
        ActionBar.Tab Tab2 = actionbar.newTab().setText("List View Tab");
        Fragment GoogleViewTab = new GoogleViewTab();
        Fragment ListViewTab = new ListViewTab();

        Tab1.setTabListener(new TabsListener(GoogleViewTab));
        Tab2.setTabListener(new TabsListener(ListViewTab));

        actionbar.addTab(Tab1);
        actionbar.addTab(Tab2);

    }

    class TabsListener implements ActionBar.TabListener {
        public Fragment fragment;

        public TabsListener(Fragment fragment){
            this.fragment = fragment;
        }

        @Override
        public void onTabSelected(Tab tab, FragmentTransaction ft) {
            // TODO Auto-generated method stub
            ft.replace(R.id.fragment_container, fragment);
        }

        @Override
        public void onTabUnselected(Tab tab, FragmentTransaction ft) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onTabReselected(Tab tab, FragmentTransaction ft) {
            // TODO Auto-generated method stub

        }
    }

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

    }

    public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
        MenuInflater inflater = getSupportMenuInflater();
        inflater.inflate(R.menu.activity_main_actions, menu);
        return super.onCreateOptionsMenu(menu);
    }
/**
     * On selecting action bar icons
     * */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Take appropriate action for each action item click
        switch (item.getItemId()) {
        case R.id.action_search:
            // search action

            return true;

        case R.id.action_location:

            // location found

            return true;

        case R.id.action_preferences:

            // refresh
            return true;
        case R.id.action_about:
            // help action
            return true;


        default:
            return super.onOptionsItemSelected(item);
        }}   }

和我的数据库处理程序

public class BurgerDBHandler {

private static final String DATABASE_NAME = "burgerDB";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_TABLE = "places";

public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "name";
public static final String KEY_ADDRESS = "address";
public static final String KEY_PHONE = "phone";
public static final String KEY_LAT = "lat";
public static final String KEY_LNG = "lng";
private BurgerDatabaseHelper bDBhelper;
private static SQLiteDatabase bDB;
private final Context bCtx;

private static final String locationdatabase = 
        "CREATE TABLE " + DATABASE_TABLE + 
        " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + 
        KEY_NAME + " TEXT NOT NULL, " + 
        KEY_ADDRESS + " TEXT NOT NULL, " + KEY_PHONE + " TEXT NOT NULL, " +
        KEY_LAT + " DOUBLE NOT NULL, " + KEY_LNG + " DOUBLE NOT NULL)";

 private static final String DATABASE_UPGRADE =
            DATABASE_TABLE +
        " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + 
        KEY_NAME + " TEXT NOT NULL, " + 
        KEY_ADDRESS + " TEXT NOT NULL, " + KEY_PHONE + " TEXT NOT NULL, " +
        KEY_LAT + " DOUBLE NOT NULL, " + KEY_LNG + " DOUBLE NOT NULL)";

    private static final String DATABASE_DROP = 
            "drop table if exists " + DATABASE_TABLE;

private static class BurgerDatabaseHelper extends SQLiteOpenHelper {




    BurgerDatabaseHelper (Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        db.execSQL(locationdatabase);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
        onCreate(db);
    }
}


public void prepare()
{
    bDB.beginTransaction();
    try {
        bDB.execSQL(DATABASE_DROP);
        bDB.execSQL(locationdatabase);
        bDB.setTransactionSuccessful();
    } finally {
        bDB.endTransaction();
    }
}

public static List<String> GetColumns(SQLiteDatabase db, String tableName) 
{
    List<String> ar = null;
    Cursor c = null;
    try {
        c = db.rawQuery("select * from " + tableName + " limit 1", null);
        if (c != null) {
            ar = new ArrayList<String>(Arrays.asList(c.getColumnNames()));
        }
    } catch (Exception e) {
        Log.v(tableName, e.getMessage(), e);
        e.printStackTrace();
    } finally {
        if (c != null)
            c.close();
    }
    return ar;
}

public static String join(List<String> list, String delim) 
{
    StringBuilder buf = new StringBuilder();
    int num = list.size();
    for (int i = 0; i < num; i++) {
        if (i != 0)
            buf.append(delim);
        buf.append((String) list.get(i));
    }
    return buf.toString();
}

/**
 * Constructor - takes the context to allow the database to be
 * opened/created
 * 
 * @param ctx the Context within which to work
 */
public BurgerDBHandler(Context ctx) 
{
    this.bCtx = ctx;
}

/**
 * Open the location database. If it cannot be opened, try to create a new
 * instance of the database. If it cannot be created, throw an exception to
 * signal the failure
 * 
 * @return this (self reference, allowing this to be chained in an
 *         initialization call)
 * @throws SQLException if the database could be neither opened or created
 */
public BurgerDBHandler open() throws SQLException {
    bDBhelper = new BurgerDatabaseHelper(bCtx);
    bDB = bDBhelper.getWritableDatabase();
    return this;
}

/**
 * Close the location database.
 */

public void close() 
{
    bDBhelper.close();
}

/**
 * Return a Cursor over the list of all locations in the database
 * 
 * @return Cursor over all locations
 */
public Cursor fetchAllItems(String sortOrder) 
{
    return bDB.query(DATABASE_TABLE, new String[] {
            KEY_ROWID, KEY_NAME, KEY_ADDRESS, KEY_PHONE, KEY_LAT, KEY_LNG}, 
            null, null, null, null, sortOrder);
}

/**
 * Return a Cursor positioned at the location that matches the given rowId
 * 
 * @param rowId id of location to retrieve
 * @return Cursor positioned to matching note, if found
 * @throws SQLException if note could not be found/retrieved
 */
public Cursor fetchItem(long rowId) throws SQLException 
{

    Cursor cursor = bDB.query(true, DATABASE_TABLE, new String[] {
            KEY_ROWID, KEY_NAME, KEY_ADDRESS, KEY_PHONE, KEY_LAT,KEY_LNG},
            KEY_ROWID + "=" + rowId, 
            null, null, null, null, null);
    if (cursor != null) {
        cursor.moveToFirst();
    }
    return cursor;
}

public String getData()  {
    // TODO Auto-generated method stub
    String[] columns = new String[] { KEY_ROWID, KEY_NAME, KEY_ADDRESS, KEY_PHONE, KEY_LAT, KEY_LNG };

    //cursor reads from database!
    Cursor c = BurgerDBHandler.query(DATABASE_TABLE, columns, null, null, null, null, null);
    String result = "";

    int iRow = c.getColumnIndex(KEY_ROWID);
    int iName = c.getColumnIndex(KEY_NAME);
    int iAddress = c.getColumnIndex(KEY_ADDRESS);
    int iPhone = c.getColumnIndex(KEY_PHONE);
    int iLat = c.getColumnIndex(KEY_LAT);
    int iLng = c.getColumnIndex(KEY_LNG);

    for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
        result = result + c.getString(iRow) + " " + c.getString(iName) + " " + c.getString(iAddress) + " " + c.getString(iPhone) + " " + c.getString(iLat) + " " + c.getString(iLng) + "\n";

    }


    return result;
}

private static Cursor query(String databaseTable, String[] columns,
        Object object, Object object2, Object object3, Object object4,
        Object object5) {
    // TODO Auto-generated method stub
    return null;
}

/**
 * Insert an item into the database
 * @param title     Title of the location
 * @param snippet   Description of the location 
 * @param lat       Latitude of the location
 * @param long      Longitude of the location
 * @return          The _id value of the item in the database
 */

public long insert(String name, String address, String phone, double lat, double lng) 
{
    ContentValues initialValues = new ContentValues();
    initialValues.put(KEY_NAME, name);
    initialValues.put(KEY_ADDRESS, address);
    initialValues.put(KEY_PHONE, phone);
    initialValues.put(KEY_LAT, lat);
    initialValues.put(KEY_LNG, lng);
    return bDB.insert(DATABASE_TABLE, null, initialValues);
}

}

真的很感激帮助,我确定它很小但是我不确定如何修改它才能起作用。

2 个答案:

答案 0 :(得分:0)

您确定这不是在整个网页上阅读吗?

您可能需要打印出'result'变量以确保。

答案 1 :(得分:0)

没有名为location的json字符串。

使用

Jasonobject.getString( “地址”),

而不是

Jasonobject.getString( “位置”),