1

I am having issues with networking being very slow.. For testing purposes, I tried to cut out asynctask completely with Android 4.0.4 and of course I need to avoid my network calls on the main thread or I get the networkNotOnMainThread exception.. So I wrapped my call in a thread and I am STILL getting this error. What the heck is wrong here??

public class DrupalTestActivity extends Activity {

    private Context mCtx;

    final static String URL = "http://www.mytestsite.com/";
    final static String ENDPOINT = "rest/";
    String mResponse = null;
    TextView textView;




    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        textView = (TextView) findViewById(R.id.textView);
                //retrieves the user account JSON object.
        JSONObject mUserAccount = UserAccount.getJSONUserAccount(this);
                //login using the JSON
        userLogin(mUserAccount);
    }



    public void userLogin(final JSONObject mUserAccount) {
        Thread t = new Thread() {
            public void run() {
                String uri = URL + ENDPOINT + "user/login";
                HttpPost httppost = new HttpPost(uri);
                httppost.setHeader("Content-type", "application/json");
                StringEntity se;
                try {
                    HttpClient mHttpClient = new DefaultHttpClient();
                    HttpParams mHttpParams = new BasicHttpParams();
                    HttpConnectionParams.setConnectionTimeout(mHttpParams,
                            10000);
                    HttpConnectionParams.setSoTimeout(mHttpParams, 10000);

                    se = new StringEntity(mUserAccount.toString());
                    se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                            "application/json"));
                    httppost.setEntity(se);
                    Log.d("STATUS", "CALLING DRUPAL");
                    ResponseHandler<String> handler = new BasicResponseHandler();
                    mResponse = mHttpClient.execute(httppost, handler);
                    mHttpClient.getConnectionManager().shutdown();


                    Log.d("STATUS", "LOGIN COMPLETE");
                    Log.d("RESPONSE", mResponse);

                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (ClientProtocolException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        };
        t.run();
    }
}

User Account method.. I don't think it's even part of the problem.

public static JSONObject getJSONUserAccount(Context ctx) {
        SharedPreferences accountSettings = PreferenceManager
                .getDefaultSharedPreferences(ctx);
        String nUsername = accountSettings.getString("username", "tester");
        String nPassword = accountSettings.getString("password", "password");
        JSONObject JSONUser = new JSONObject();
        try {
            JSONUser.put("password", nPassword);
            JSONUser.put("username", nUsername);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return JSONUser;
    }

Log is..

07-05 10:34:58.377: E/AndroidRuntime(32538): FATAL EXCEPTION: main
07-05 10:34:58.377: E/AndroidRuntime(32538): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.seine.drupal/com.seine.drupal.DrupalTestActivity}: android.os.NetworkOnMainThreadException
07-05 10:34:58.377: E/AndroidRuntime(32538):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2049)
07-05 10:34:58.377: E/AndroidRuntime(32538):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2083)
07-05 10:34:58.377: E/AndroidRuntime(32538):    at android.app.ActivityThread.access$600(ActivityThread.java:134)
07-05 10:34:58.377: E/AndroidRuntime(32538):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1233)
07-05 10:34:58.377: E/AndroidRuntime(32538):    at android.os.Handler.dispatchMessage(Handler.java:99)
07-05 10:34:58.377: E/AndroidRuntime(32538):    at android.os.Looper.loop(Looper.java:137)
07-05 10:34:58.377: E/AndroidRuntime(32538):    at android.app.ActivityThread.main(ActivityThread.java:4697)
07-05 10:34:58.377: E/AndroidRuntime(32538):    at java.lang.reflect.Method.invokeNative(Native Method)
07-05 10:34:58.377: E/AndroidRuntime(32538):    at java.lang.reflect.Method.invoke(Method.java:511)
07-05 10:34:58.377: E/AndroidRuntime(32538):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:787)
07-05 10:34:58.377: E/AndroidRuntime(32538):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:554)
07-05 10:34:58.377: E/AndroidRuntime(32538):    at dalvik.system.NativeStart.main(Native Method)
07-05 10:34:58.377: E/AndroidRuntime(32538): Caused by: android.os.NetworkOnMainThreadException
07-05 10:34:58.377: E/AndroidRuntime(32538):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1119)
07-05 10:34:58.377: E/AndroidRuntime(32538):    at java.net.InetAddress.lookupHostByName(InetAddress.java:441)
07-05 10:34:58.377: E/AndroidRuntime(32538):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:243)
07-05 10:34:58.377: E/AndroidRuntime(32538):    at java.net.InetAddress.getAllByName(InetAddress.java:220)
07-05 10:34:58.377: E/AndroidRuntime(32538):    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
07-05 10:34:58.377: E/AndroidRuntime(32538):    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
07-05 10:34:58.377: E/AndroidRuntime(32538):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
07-05 10:34:58.377: E/AndroidRuntime(32538):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
07-05 10:34:58.377: E/AndroidRuntime(32538):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
07-05 10:34:58.377: E/AndroidRuntime(32538):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:653)
07-05 10:34:58.377: E/AndroidRuntime(32538):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:627)
07-05 10:34:58.377: E/AndroidRuntime(32538):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:616)
07-05 10:34:58.377: E/AndroidRuntime(32538):    at com.seine.drupal.DrupalTestActivity.userLogin(DrupalTestActivity.java:90)
07-05 10:34:58.377: E/AndroidRuntime(32538):    at com.seine.drupal.DrupalTestActivity$1.run(DrupalTestActivity.java:65)
07-05 10:34:58.377: E/AndroidRuntime(32538):    at com.seine.drupal.DrupalTestActivity.onCreate(DrupalTestActivity.java:69)
07-05 10:34:58.377: E/AndroidRuntime(32538):    at android.app.Activity.performCreate(Activity.java:4539)
07-05 10:34:58.377: E/AndroidRuntime(32538):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
07-05 10:34:58.377: E/AndroidRuntime(32538):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2013)
07-05 10:34:58.377: E/AndroidRuntime(32538):    ... 11 more

I am baffled and this must be something new in ICS because this all worked in earlier versions of android. Am I really forced to used AsyncTask? I just can't believe that.

Todd Painton
  • 701
  • 7
  • 20
  • When you move UserAccount into a thread, on what line do you get the exception? – Seva Alekseyev Jul 05 '12 at 15:38
  • Forgot to add Log.. editing now. Thanks. I also added the method to get the user JSON object.. but I don't think it's relevant. – Todd Painton Jul 05 '12 at 15:40
  • @ToddPainton You aren't forced to use an `AsyncTask`... you are forced to use a separate `Thread` though, and this is completely reasonable... you shouldn't be blocking the UI thread for any reason whatsoever. That said, I am not really sure why you are complaining... the whole purpose of `AsyncTask`s is to abstract the whole idea of `Thread`s out of the picture... using an `AsyncTask` is about as simple as it gets. – Alex Lockwood Jul 05 '12 at 17:44

1 Answers1

3

You're calling run() on the thread object instead of start(). Calling run() just executes your thread procedure on the main thread.

The line goes

t.run(); 

in the very end. Should be

t.start(); 
Seva Alekseyev
  • 59,826
  • 25
  • 160
  • 281
  • Doh!!! I think that also might be explaining a lot of other problems I am having as well :)) I am very thankful I have you guys to call on.. – Todd Painton Jul 05 '12 at 15:49