簡體   English   中英

如何解析mysql的json輸出

[英]how to parse json output from mysql

我在我的android應用程序中有一個google map,我在mysql db中保存了一些經緯度的數據,我想從mysql db中讀取該數據。 我已經編寫了代碼,但該應用程序仍然出錯。

myphp是:

 <?php
$link = mysql_connect('localhost', 'root', '') or die('Cannot connect to the DB');
mysql_select_db('joe', $link) or die('Cannot select the DB');

/* grab the posts from the db */
$query = "SELECT lattitude, longitude FROM tracking";
$result = mysql_query($query, $link) or die('Errorquery:  '.$query);

$rows = array();
while ($r = mysql_fetch_assoc($result)) {
$rows[] = $r;
}
$data = "{joel:".json_encode($rows)."}";
 echo $data;
?>

我有3個Java活動

public class lagiiiiteslagi extends ListActivity {

private static String url = "http://10.0.2.2/labiltrack/daftartracking.php";
// JSON Node names
private static final String TAG_lattitude = "lattitude";
private static final String TAG_longitude = "longitude";

// contacts JSONArray
JSONArray lattitude = null;


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // Hashmap for ListView
    ArrayList<HashMap<String, String>> contactList = 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
        lattitude = json.getJSONArray(TAG_lattitude);
        // looping through All Contacts
        for(int i = 0; i < lattitude.length(); i++) {
              JSONObject c = lattitude.getJSONObject(i);

            // Storing each json item in variable
              String lattitude = c.getString(TAG_lattitude);
              String longitude = c.getString(TAG_longitude);

           // Phone number is agin JSON Object
              //JSONObject phone = c.getJSONObject(TAG_PHONE);

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

              // adding each child node to HashMap key => value
              map.put(TAG_lattitude, lattitude);
              map.put(TAG_longitude, longitude);

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

      }

      /**
      * Updating parsed JSON data into ListView
      * */
     ListAdapter adapter = new SimpleAdapter(this, contactList,
            R.layout.main,
            new String[] { TAG_lattitude, TAG_longitude }, new int[] {
                    R.id.TextViewResult, R.id.TextViewResult1 });

      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<?> arg0, View view, int position,
                long id) {
            // TODO Auto-generated method stub
            // getting values from selected ListItem
            //String lattitude = ((TextView))  view.findViewById(R.id.TextViewResult)).getText().toString();
            //String longitude = ((TextView)) view.findViewById(R.id.TextViewResult1)).getText(lattitude).toString();
            String lattitude = ((TextView) view.findViewById(R.id.TextViewResult)).getText().toString();
            String longitude = ((TextView) view.findViewById(R.id.TextViewResult1)).getText().toString();

            // Starting new intent
            Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
            in.putExtra(TAG_lattitude, lattitude);
            in.putExtra(TAG_longitude, longitude);
            startActivity(in);              
        }

    });
    }
    }

這個JSONparser類:

 public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser(){

}

public JSONObject getJSONFromUrl(String url) {
    // TODO Auto-generated method stub
    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        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;
}

 }

這用於顯示在listview中:

 public class SingleMenuItemActivity extends Activity {
// JSON node keys
private static final String TAG_lattitude = "lattitude";
private static final String TAG_longitude = "longitude";

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

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

    // Get JSON values from previous intent
    String lattitude = in.getStringExtra(TAG_lattitude);
    String longitude = in.getStringExtra(TAG_longitude);

   // Displaying all values on the screen
     TextView lbllattitude = (TextView) findViewById(R.id.listlat);
    TextView lbllongitude = (TextView) findViewById(R.id.listlong);

    lbllattitude.setText(lattitude);
    lbllongitude.setText(longitude);

  } 
   }

我只想在listview中顯示緯度和經度,但仍然出錯,我是android新手,希望有人對我有所幫助,謝謝!

檢查此鏈接以獲得json幫助...我建議使用Log.e("JSON", json);類的日志 Log.e("JSON", json); 在不同的地方找到錯誤實際上發生的點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM