SpeedAmphetamine
SpeedAmphetamine

Reputation: 177

fetching map markers from mysql database to android app

I am completely new to android programming and java programming. I have a existing web app which has coordinates stored in mysql database. By following some online tutorials on Google Map API and JSON i have written codes in order to display map markers for the points stored the database.

My php script returns the following output when run

[{"RowID":"15","LatLng":"(27.70171145916157, 85.30419380111698)","Type":"hospital"},{"RowID":"16","LatLng":"(27.704200193429045, 85.32494337005619)","Type":"hospital"}]

I have crated a class to parse the JSON data

    public class ImportMarkers {

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

    // constructor
    public ImportMarkers() {

    }

    public JSONObject getJSONFromUrl(String url) {

        // 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;

    }
}

and finally to display the markers in the map view that i have created i have used the following code

    //url to make request
private static String url = "http://10.0.2.2/jsonsenddata.php";

//JSON Node names
private static final String id = "RowID";
private static final String latlng = "LatLng";
private static final String type = "Type";

JSONArray markers = null;

     // Creating JSON Parser instance
        ImportMarkers marker = new ImportMarkers();

        // getting JSON string from URL
        JSONObject json = marker.getJSONFromUrl(url);

        try {
            // Getting AJSONObjectrray 
            markers = json.getJSONArray(null);

            // looping through All rows
            for(int i = 0; i < markers.length(); i++){
                JSONObject c = markers.getJSONObject(i);

                // Storing each json item in variable
                String RowID = c.getString(id);
                String LatLng = c.getString(latlng);
                String Type = c.getString(type);
                String[] parts = LatLng.split(",");
                String lat = parts[0]; 
                String lon = parts[1]; 
                float latInt = Float.valueOf(lat).floatValue(); 
                float longInt = Float.valueOf(lon).floatValue(); 
                GeoPoint X = new GeoPoint((int) (latInt*1E6),(int) (longInt*1E6) ); 
                if (Type == "hospital"){
                    OverlayItem overlayItem = new OverlayItem (X , "Hospital", "ADDITION");
                    AddLocation hospital = new AddLocation (hos, MainActivity.this);
                    hospital.addLocation(overlayItem);
                    overlayList.add(hospital);
                }
                else {
                    OverlayItem overlayItem = new OverlayItem (X , "Airport", "ADDITION");
                    AddLocation airport = new AddLocation (air, MainActivity.this);
                    airport.addLocation(overlayItem);
                    overlayList.add(airport);
                }


            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

I dont know what is wrong with my code , i would be greatful if anybody provided some help.

Here is my logcat log

12-02 13:45:41.348: D/dalvikvm(448): GC_CONCURRENT freed 174K, 4% free 6623K/6855K, paused 6ms+4ms
12-02 13:45:41.628: D/dalvikvm(448): GC_CONCURRENT freed 356K, 6% free 6823K/7239K, paused 4ms+4ms
12-02 13:45:42.028: D/dalvikvm(448): GC_CONCURRENT freed 699K, 11% free 6616K/7431K, paused 4ms+5ms
12-02 13:45:42.028: W/CursorWrapperInner(448): Cursor finalized without prior close()
12-02 13:45:42.038: W/CursorWrapperInner(448): Cursor finalized without prior close()
12-02 13:45:42.438: D/dalvikvm(448): GC_CONCURRENT freed 198K, 7% free 6929K/7431K, paused 4ms+7ms
12-02 13:45:42.789: D/dalvikvm(448): GC_CONCURRENT freed 311K, 5% free 7189K/7559K, paused 8ms+16ms
12-02 13:45:43.258: D/dalvikvm(448): GC_CONCURRENT freed 519K, 8% free 7234K/7815K, paused 5ms+7ms
12-02 13:45:43.580: D/dalvikvm(448): GC_CONCURRENT freed 267K, 6% free 7385K/7815K, paused 5ms+4ms
12-02 13:45:44.048: D/dalvikvm(448): GC_CONCURRENT freed 675K, 10% free 7259K/8007K, paused 5ms+4ms
12-02 13:45:44.148: D/AndroidRuntime(448): Shutting down VM
12-02 13:45:44.148: W/dalvikvm(448): threadid=1: thread exiting with uncaught exception (group=0x40014760)
12-02 13:45:44.168: E/AndroidRuntime(448): FATAL EXCEPTION: main
12-02 13:45:44.168: E/AndroidRuntime(448): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.finalyear.quakereact/com.finalyear.quakereact.MainActivity}: android.os.NetworkOnMainThreadException
12-02 13:45:44.168: E/AndroidRuntime(448):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1815)
12-02 13:45:44.168: E/AndroidRuntime(448):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1831)
12-02 13:45:44.168: E/AndroidRuntime(448):  at android.app.ActivityThread.access$500(ActivityThread.java:122)
12-02 13:45:44.168: E/AndroidRuntime(448):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1024)
12-02 13:45:44.168: E/AndroidRuntime(448):  at android.os.Handler.dispatchMessage(Handler.java:99)
12-02 13:45:44.168: E/AndroidRuntime(448):  at android.os.Looper.loop(Looper.java:132)
12-02 13:45:44.168: E/AndroidRuntime(448):  at android.app.ActivityThread.main(ActivityThread.java:4123)
12-02 13:45:44.168: E/AndroidRuntime(448):  at java.lang.reflect.Method.invokeNative(Native Method)
12-02 13:45:44.168: E/AndroidRuntime(448):  at java.lang.reflect.Method.invoke(Method.java:491)
12-02 13:45:44.168: E/AndroidRuntime(448):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
12-02 13:45:44.168: E/AndroidRuntime(448):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
12-02 13:45:44.168: E/AndroidRuntime(448):  at dalvik.system.NativeStart.main(Native Method)
12-02 13:45:44.168: E/AndroidRuntime(448): Caused by: android.os.NetworkOnMainThreadException
12-02 13:45:44.168: E/AndroidRuntime(448):  at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1077)
12-02 13:45:44.168: E/AndroidRuntime(448):  at dalvik.system.BlockGuard$WrappedNetworkSystem.connect(BlockGuard.java:368)
12-02 13:45:44.168: E/AndroidRuntime(448):  at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:208)
12-02 13:45:44.168: E/AndroidRuntime(448):  at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:431)
12-02 13:45:44.168: E/AndroidRuntime(448):  at java.net.Socket.connect(Socket.java:901)
12-02 13:45:44.168: E/AndroidRuntime(448):  at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
12-02 13:45:44.168: E/AndroidRuntime(448):  at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:143)
12-02 13:45:44.168: E/AndroidRuntime(448):  at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
12-02 13:45:44.168: E/AndroidRuntime(448):  at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
12-02 13:45:44.168: E/AndroidRuntime(448):  at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
12-02 13:45:44.168: E/AndroidRuntime(448):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
12-02 13:45:44.168: E/AndroidRuntime(448):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
12-02 13:45:44.168: E/AndroidRuntime(448):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
12-02 13:45:44.168: E/AndroidRuntime(448):  at com.finalyear.quakereact.ImportMarkers.getJSONFromUrl(ImportMarkers.java:38)
12-02 13:45:44.168: E/AndroidRuntime(448):  at com.finalyear.quakereact.MainActivity.onCreate(MainActivity.java:80)
12-02 13:45:44.168: E/AndroidRuntime(448):  at android.app.Activity.performCreate(Activity.java:4397)
12-02 13:45:44.168: E/AndroidRuntime(448):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1048)
12-02 13:45:44.168: E/AndroidRuntime(448):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1779)
12-02 13:45:44.168: E/AndroidRuntime(448):  ... 11 more
12-02 13:46:42.368: I/Process(448): Sending signal. PID: 448 SIG: 9

Thank you in advance.

Upvotes: 1

Views: 2053

Answers (1)

nullpotent
nullpotent

Reputation: 9260

The exception is NetworkOnMainThreadException

The exception that is thrown when an application attempts to perform a networking operation on its main thread.

This is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it's heavily discouraged.

So, fetch on a separate thread. AsyncTask perhaps? (if you need to update the UI)

Upvotes: 1

Related Questions