0

我的android应用程序中有一个谷歌地图,我在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);

  } 
   }

我只想在列表视图中显示纬度和经度,但仍然出错,我是 android 新手,希望有人能帮助我,在此先感谢!

4

1 回答 1

0

检查此链接以获取 json 帮助...我建议在不同的地方使用日志Log.e("JSON", json);查找错误实际发生的点。

于 2012-07-12T12:08:26.237 回答