-1

I am having some problem when trying to insert data into MySQL from Android via servlet. So my situation is when the map was onSingleTap, it will get the coordinates X and Y and insert into database.

@Override
public void onCreate(Bundle savedInstanceState) {
    mMapView.setOnSingleTapListener(new OnSingleTapListener() {
        public void onSingleTap(float x, float y) {
            Point point = mMapView.toMapPoint(x, y);
                Log.e("Coord", point.toString());
                eventCtrl.createEvent(point.toString());
            }
    });
    new MyAsyncTask().execute();
}

private class MyAsyncTask extends AsyncTask<Void, Integer, Double> {
    @Override
    protected Double doInBackground(Void... params) {
        try {
            eventCtrl.retrieveEventJSON();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    protected void onPostExecute(Double result) {
    }

    protected void onProgressUpdate(Integer... progress) {
    }
}

public void createEvent(String point) {
    HttpPost post = new HttpPost(ENeighbourhoodActivity.URL);

    HttpClient client = new DefaultHttpClient();

    List<NameValuePair> nvp = new ArrayList<NameValuePair>(2);
    nvp.add(new BasicNameValuePair("eventX", point));
    nvp.add(new BasicNameValuePair("eventY", point));

    try {
        post.setEntity(new UrlEncodedFormEntity(nvp));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    try {
        HttpResponse response = client.execute(post);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

And my servlet:

protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {

    PrintWriter out = response.getWriter();
    String eventX = request.getParameter("eventX");
    String eventY = request.getParameter("eventY");
    Connection con = null;
    Statement stmt = null;
    try {
        con = DriverManager.getConnection("jdbc:mysql://localhost/mydb",
                "root", "root");
    } catch (SQLException e) {
        e.printStackTrace();
    }

    try {
        stmt = con.createStatement();
    } catch (SQLException e) {
        e.printStackTrace();
    }

    String sqlStr = "INSERT into event VALUES (" + eventX + "," + eventY
            + ");";

    try {
        int rSet = stmt.executeUpdate(sqlStr);
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

However, I am getting NetworkOnMainThreadException error message as the LogCat:

11-05 20:37:29.690: E/Coord(26573): Point [m_attributes=[27289.373913043477, 34157.21304347826], m_description=com.esri.core.geometry.VertexDescription@7c5d0f85]
11-05 20:37:29.784: D/AndroidRuntime(26573): Shutting down VM
11-05 20:37:29.784: W/dalvikvm(26573): threadid=1: thread exiting with uncaught exception (group=0x40c3f1f8)
11-05 20:37:29.815: D/dalvikvm(26573): GC_CONCURRENT freed 498K, 13% free 10934K/12487K, paused 44ms+3ms
11-05 20:37:29.885: E/AndroidRuntime(26573): FATAL EXCEPTION: main
11-05 20:37:29.885: E/AndroidRuntime(26573): android.os.NetworkOnMainThreadException
11-05 20:37:29.885: E/AndroidRuntime(26573):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
11-05 20:37:29.885: E/AndroidRuntime(26573):    at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
11-05 20:37:29.885: E/AndroidRuntime(26573):    at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
11-05 20:37:29.885: E/AndroidRuntime(26573):    at libcore.io.IoBridge.connect(IoBridge.java:112)
11-05 20:37:29.885: E/AndroidRuntime(26573):    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
11-05 20:37:29.885: E/AndroidRuntime(26573):    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
11-05 20:37:29.885: E/AndroidRuntime(26573):    at java.net.Socket.connect(Socket.java:842)
11-05 20:37:29.885: E/AndroidRuntime(26573):    at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
11-05 20:37:29.885: E/AndroidRuntime(26573):    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
11-05 20:37:29.885: E/AndroidRuntime(26573):    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
11-05 20:37:29.885: E/AndroidRuntime(26573):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
11-05 20:37:29.885: E/AndroidRuntime(26573):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
11-05 20:37:29.885: E/AndroidRuntime(26573):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
11-05 20:37:29.885: E/AndroidRuntime(26573):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
11-05 20:37:29.885: E/AndroidRuntime(26573):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
11-05 20:37:29.885: E/AndroidRuntime(26573):    at Controller.EventController.createEvent(EventController.java:135)
11-05 20:37:29.885: E/AndroidRuntime(26573):    at nyp.edu.eneighbourhood.ENeighbourhoodActivity$3.onSingleTap(ENeighbourhoodActivity.java:188)
11-05 20:37:29.885: E/AndroidRuntime(26573):    at com.esri.android.map.MapOnTouchListener.onSingleTap(Unknown Source)
11-05 20:37:29.885: E/AndroidRuntime(26573):    at com.esri.android.map.MapGestureDetector$a.onSingleTapConfirmed(Unknown Source)
11-05 20:37:29.885: E/AndroidRuntime(26573):    at android.view.GestureDetector$GestureHandler.handleMessage(GestureDetector.java:393)
11-05 20:37:29.885: E/AndroidRuntime(26573):    at android.os.Handler.dispatchMessage(Handler.java:99)
11-05 20:37:29.885: E/AndroidRuntime(26573):    at android.os.Looper.loop(Looper.java:137)
11-05 20:37:29.885: E/AndroidRuntime(26573):    at android.app.ActivityThread.main(ActivityThread.java:4512)
11-05 20:37:29.885: E/AndroidRuntime(26573):    at java.lang.reflect.Method.invokeNative(Native Method)
11-05 20:37:29.885: E/AndroidRuntime(26573):    at java.lang.reflect.Method.invoke(Method.java:511)
11-05 20:37:29.885: E/AndroidRuntime(26573):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:982)
11-05 20:37:29.885: E/AndroidRuntime(26573):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:749)
11-05 20:37:29.885: E/AndroidRuntime(26573):    at dalvik.system.NativeStart.main(Native Method)

I knew this error message was because I am trying to access network stuff but I did not do in background. I wonder is there any way for me to call the createEvent() in MyAsyncTask class?

Thanks in advance.

2 Answers2

1

Pass your point as parameter to AsyncTask.

@Override
public void onCreate(Bundle savedInstanceState) {
    mMapView.setOnSingleTapListener(new OnSingleTapListener() {
        public void onSingleTap(float x, float y) {
            Point point = mMapView.toMapPoint(x, y);
                Log.e("Coord", point.toString());
                new MyAsyncTask().execute(point);
            }
    });
}

private class MyAsyncTask extends AsyncTask<Point, Integer, Double> {
    @Override
    protected Double doInBackground(Point... params) {
        if(params.length == 1) {
            try {
                eventCtrl.createEvent(params[0].toString());
                eventCtrl.retrieveEventJSON();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    protected void onPostExecute(Double result) {
    }

    protected void onProgressUpdate(Integer... progress) {
    }
}
Boban S.
  • 1,662
  • 13
  • 16
  • But let's say now the point was changed to Event object. So I just simply replace the Point... params to Event... params? –  Nov 05 '14 at 12:57
  • Yes, and also to replace `extends` part to `AsyncTask` – Boban S. Nov 05 '14 at 12:58
  • One more question, what is the params[0] for? Sorry I am quite new to this. –  Nov 05 '14 at 13:01
  • `execute` method can have more than one parameter, as many as you need. Dots `...` in function declaration represents that. So when function is called you receive `params` array and you are accessing them as any other `array` in Java. – Boban S. Nov 05 '14 at 13:03
  • @BobamS. I wanted to pass in different parameter into MyAysncTask() class from different method. Let's say from method 1, I am passing Event object. But for method 2, I am passing two double values. So how should I modify the parameter in doInBackground() –  Nov 11 '14 at 02:08
  • You can pass parameter `Object` and then check in `doInBackground` what type it actually is. – Boban S. Nov 11 '14 at 09:22
  • Would you mind to provide some examples? Also, I am getting Fatal Exception: AsyncTask #2. Let me post it as a question and share the link with you –  Nov 11 '14 at 09:22
  • In the answer above just replace `Point` with `Object` and in `doInBackground` use `if(params[0] instance of...)`. I can't write better code in comment. – Boban S. Nov 11 '14 at 09:23
0

This question has been asked zillions of times....

Your create event createEvent should be ONLY called on an async task because it performs networks operations. Don't call createEvent on your activity.

Pedro Oliveira
  • 20,442
  • 8
  • 55
  • 82
  • But I've to get some value from activity and pass them to create event. How can I call it in doInBackground? –  Nov 05 '14 at 12:54
  • You're telling us that you don't know how to create an async task and pass values to it? – Pedro Oliveira Nov 05 '14 at 12:55