简体   繁体   English

如何解析mysql的json输出

[英]how to parse json output from mysql

I have a google map inside my android application, I have some saved data in mysql db with latitude and longitude and i want to read that data from mysql db. 我在我的android应用程序中有一个google map,我在mysql db中保存了一些经纬度的数据,我想从mysql db中读取该数据。 I have wrote code but the app is still error . 我已经编写了代码,但该应用程序仍然出错。

myphp is : 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;
?>

I have 3 java activities 我有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);              
        }

    });
    }
    }

this JSONparser class : 这个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;
}

 }

this is use to display in listview : 这用于显示在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);

  } 
   }

I just want to display that lattitude and longitude in listview but still error, I'm new to android, I hope some one help me, Thank in advance ! 我只想在listview中显示纬度和经度,但仍然出错,我是android新手,希望有人对我有所帮助,谢谢!

check this link for json help... I suggest to to use log like Log.e("JSON", json); 检查此链接以获得json帮助...我建议使用Log.e("JSON", json);类的日志 Log.e("JSON", json); in different place to find the point where the error actually happens. 在不同的地方找到错误实际上发生的点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM