-1

I have a navigation drawer and some async task which will do in background. What I am trying to do is when certain item was selected from navigation drawer, I then execute the method which do in background in async task. Here is the code where something was selected from navigation drawer:

private void selectItem(int position) {
    selectedPosition = position;
    mDrawerLayout.closeDrawer(navDrawerView);

    switch (selectedPosition) {
    case 0:
        try {
            ViewEventsOnMap();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Toast.makeText(ENeighbourhoodActivity.this, "Press and hold at the area where you wish to create an event!",
                Toast.LENGTH_LONG).show();
        break;
    case 1:
        Toast.makeText(ENeighbourhoodActivity.this, "Analyze Event",
                Toast.LENGTH_LONG).show();
        break;
    }

    setTitle(mEventSelection[selectedPosition]);

}

And my async task class:

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

    protected void onPostExecute(Double result) {
    }

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

I called this async task class when onCreate so it does not depends on which item was selected from navigation drawer.

public void ViewEventsOnMap() throws JSONException {
    String page;
    JSONArray jsonArray;

    try {
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(URL);
        HttpResponse response = client.execute(request);
        HttpEntity entity = response.getEntity();
        try {
            // Codes to retrieve data from servlet and plot marker onto the map
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

But with these codes, I am getting these error messages:

11-04 20:54:45.642: W/dalvikvm(25527): threadid=1: thread exiting with uncaught exception (group=0x40c3f1f8)
11-04 20:54:45.673: E/AndroidRuntime(25527): FATAL EXCEPTION: main
11-04 20:54:45.673: E/AndroidRuntime(25527): android.os.NetworkOnMainThreadException
11-04 20:54:45.673: E/AndroidRuntime(25527):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
11-04 20:54:45.673: E/AndroidRuntime(25527):    at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
11-04 20:54:45.673: E/AndroidRuntime(25527):    at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
11-04 20:54:45.673: E/AndroidRuntime(25527):    at libcore.io.IoBridge.connect(IoBridge.java:112)
11-04 20:54:45.673: E/AndroidRuntime(25527):    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
11-04 20:54:45.673: E/AndroidRuntime(25527):    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
11-04 20:54:45.673: E/AndroidRuntime(25527):    at java.net.Socket.connect(Socket.java:842)
11-04 20:54:45.673: E/AndroidRuntime(25527):    at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
11-04 20:54:45.673: E/AndroidRuntime(25527):    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
11-04 20:54:45.673: E/AndroidRuntime(25527):    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
11-04 20:54:45.673: E/AndroidRuntime(25527):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
11-04 20:54:45.673: E/AndroidRuntime(25527):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
11-04 20:54:45.673: E/AndroidRuntime(25527):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
11-04 20:54:45.673: E/AndroidRuntime(25527):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
11-04 20:54:45.673: E/AndroidRuntime(25527):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
11-04 20:54:45.673: E/AndroidRuntime(25527):    at nyp.edu.eneighbourhood.ENeighbourhoodActivity.ViewEventsOnMap(ENeighbourhoodActivity.java:204)
11-04 20:54:45.673: E/AndroidRuntime(25527):    at nyp.edu.eneighbourhood.ENeighbourhoodActivity.selectItem(ENeighbourhoodActivity.java:385)
11-04 20:54:45.673: E/AndroidRuntime(25527):    at nyp.edu.eneighbourhood.ENeighbourhoodActivity.access$4(ENeighbourhoodActivity.java:378)
11-04 20:54:45.673: E/AndroidRuntime(25527):    at nyp.edu.eneighbourhood.ENeighbourhoodActivity$5.onChildClick(ENeighbourhoodActivity.java:341)
11-04 20:54:45.673: E/AndroidRuntime(25527):    at android.widget.ExpandableListView.handleItemClick(ExpandableListView.java:584)
11-04 20:54:45.673: E/AndroidRuntime(25527):    at android.widget.ExpandableListView.performItemClick(ExpandableListView.java:521)
11-04 20:54:45.673: E/AndroidRuntime(25527):    at android.widget.AbsListView$PerformClick.run(AbsListView.java:2713)
11-04 20:54:45.673: E/AndroidRuntime(25527):    at android.widget.AbsListView$1.run(AbsListView.java:3468)
11-04 20:54:45.673: E/AndroidRuntime(25527):    at android.os.Handler.handleCallback(Handler.java:605)
11-04 20:54:45.673: E/AndroidRuntime(25527):    at android.os.Handler.dispatchMessage(Handler.java:92)
11-04 20:54:45.673: E/AndroidRuntime(25527):    at android.os.Looper.loop(Looper.java:137)
11-04 20:54:45.673: E/AndroidRuntime(25527):    at android.app.ActivityThread.main(ActivityThread.java:4512)
11-04 20:54:45.673: E/AndroidRuntime(25527):    at java.lang.reflect.Method.invokeNative(Native Method)
11-04 20:54:45.673: E/AndroidRuntime(25527):    at java.lang.reflect.Method.invoke(Method.java:511)
11-04 20:54:45.673: E/AndroidRuntime(25527):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:982)
11-04 20:54:45.673: E/AndroidRuntime(25527):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:749)
11-04 20:54:45.673: E/AndroidRuntime(25527):    at dalvik.system.NativeStart.main(Native Method)

Any guides? Thanks in advance.

2 Answers2

2

You wrote an AsyncTask class, and you are not using it. Your stack trace shows that you are calling ViewEventsOnMap() from selectItem() on the main application thread, and that you are not using MyAsyncTask anywhere.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • The viewEventsOnMap() supposed to do in background and I've called the async task class when on create. So when my map loads, it straight away shows all the marker without me selecting from navigation drawer. –  Nov 04 '14 at 13:13
  • @IWasSoLost: "The viewEventsOnMap() supposed to do in background" -- not according to the code that you wrote. "I've called the async task class when on create" -- that does not matter, as you are *not* calling it from `selectItem()`, which is where your `NetworkOnMainThreadException` is coming from. – CommonsWare Nov 04 '14 at 13:41
  • Do you have any ideas so I could twist my codes around to work in what I've expected? –  Nov 04 '14 at 13:45
  • @IWasSoLost: Use your `MyAsyncTask` in `selectItem()`. – CommonsWare Nov 04 '14 at 13:46
  • So basically if next time I've select another item, I should call the MyAsyncTask again? –  Nov 04 '14 at 13:49
  • @IWasSoLost: I have no idea, as I do not know the details of your business logic. That being said, `selectItem()` is being called on the main application thread, and therefore you need to ensure that any network I/O triggered by `selectItem()` is done in a background thread. – CommonsWare Nov 04 '14 at 23:06
0

You are not using AsyncTask for your network calls. You have written a AsyncTask but not exactly using it.

On selection of an item in navigation drawer you are directly calling the method ViewEventsOnMap() which runs on UI thread.

Instead of doing that you should call your AsycnTask

Rohit5k2
  • 17,948
  • 8
  • 45
  • 57
  • The viewEventsOnMap() supposed to do in background and I've called the async task class when on create. So when my map loads, it straight away shows all the marker without me selecting from navigation drawer. –  Nov 04 '14 at 13:12
  • Method ViewEventsOnMap() is doing a network call and it has to be inside a AsyncTask without any choice. Find a workaround. – Rohit5k2 Nov 04 '14 at 13:14
  • But do you have any ideas? –  Nov 04 '14 at 13:16
  • If you are calling the AsycnTask then why do you call that method again on selection of an item? You should have data in your hand eventually, till then show a progress bar or something like that. Once you have data show it on your screen. – Rohit5k2 Nov 04 '14 at 13:17
  • Because the ViewEventOnMap() is basically plotting some marker retrieved from servlet onto the map. So I do not want it to plot when the map loads for the first time. Instead, when user select certain item from navigation drawer, I then perform the plotting –  Nov 04 '14 at 13:22
  • Even if you want it to be ready your network calls has to be in a AsyncTask. No options – Rohit5k2 Nov 04 '14 at 13:55