luiscvalmeida
luiscvalmeida

Reputation: 152

Connect Android App to MySQL db through PHP/JSON

I have a MySQL database with one unique table: geopoints, that has 3 columns: id, lat and long, and this table is filled up with 4 entrys already, 4 values of lat and long (1E6 because its to use on a mapview).

My objective is to mark on a mapview all these 4 geopoints dynamicly using a php script that generates json array, and with a httpPost etc...

This is the code I have so far:

getjson = (Button) findViewById(R.id.button1);

    getjson.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {

            JSONArray jArray;
            String result = null;
            InputStream is = null;
            StringBuilder sb = null;
            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();//Whats this for?

            try {

                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(
                        "http://????????.com/????/getGeopoints.php");
                HttpResponse response = httpclient.execute(httpPost);
                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpEntity entity = response.getEntity();
                is = entity.getContent();

            } catch (Exception e) {
                Log.e("log_tag", "Error connecting to http " + e.toString());
            }

            try {
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(is, "iso-8859-1"), 8);
                sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();

                result = sb.toString();
            } catch (Exception e) {
                Log.e("log_tag", "Error converting  " + e.toString());
            }

            try {

                jArray = new JSONArray(result);

                for (int i = 0; i <= jArray.length(); i++) {

                    JSONObject json_data = jArray.getJSONObject(i);

                    Log.i("log_tag", "id: " + json_data.getInt("id")
                            + ", latitude: " + json_data.getInt("lat")
                            + ", longitude: " + json_data.getInt("long"));


                }
            } catch (JSONException e) {
                Log.e("log_tag", "Error parsing data " + e.toString());
            }
        }
    });

This is the php file:

 <?php
mysql_connect("?????.com", "username", "password");
mysql_select_db("database_name");

$q = mysql_query("SELECT * FROM geopoints");
while ($e = mysql_fetch_assoc($q))
    $output[] = $e;

print(json_encode($output));
mysql_close();
?>

I have this file running right because as I enter the url on a browser it generates the exact json array with the exact information I want. There is only think I don't understand, what's HttpEntity for? Because I followed up a tutorial, and in there it uses an array with information to filter from the db, as I don't want to filter any info (I want all the database table entrys, not just one or two) I just leaved it blank.

What's wrong with my code? The error I get in logcat is all the catch messages "11-29 12:47:29.662: E/log_tag(898): Error connecting to http Http android.os.NetworkOnMainThreadException".

Upvotes: 0

Views: 1131

Answers (2)

Mohsin Naeem
Mohsin Naeem

Reputation: 12642

android.os.NetworkOnMainThreadException

android >= 3.0 does not allow Network request on main UI thread. you need to use AsyncTask to call network request.

Upvotes: 2

That's because you're are blocking the main UI thread. Try to use AsyncTasks for Http requests.

Upvotes: 1

Related Questions