2013-12-13 34 views
0

我希望得到一個簡單的應用程序,我正在學習谷歌地圖V2的API,並熟悉了Android的一些幫助。我試圖解析來自JSON文件的一些信息,但它只是懸掛。我發現了一些對這個錯誤的引用,但是我不能讓它停止在應用程序啓動時掛起,即使我改變了引用JSONarray的行。活動/數據庫代碼/ JSON文件和錯誤如下。難以置信的我的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); 
} 

} 

很欣賞的幫助下,我敢肯定,它的小東西,但我不知道我怎麼能修改此工作。

回答

0

您確定這不是試圖閱讀整個網頁嗎?

您可能想打印出'結果'變量以確保。

0

沒有名爲location的json字符串。

使用

Jasonobject.getString( 「地址」),

而不是

Jasonobject.getString( 「位置」),