Socket in AsyncTask - application crashesso the UI won't be blocked

by Jerry Fan » Wed, 21 Jul 2010 16:41:26 GMT


Sponsored Links
 ou can register a handler in your code and send message to update  your UI
component in Handler. I used this way to solve a similar problem like urs
before. For exapmpel

if (socket.isConnected()) {
OutputStreamOut = new
ObjectOutputStream(socket.
getOutputStream());
InputStreamIn = new
ObjectInputStream(socket.getInputStream());
// everything worked fine until here
//instead of doing this, send msg to a customized
handler
//statusTxt.setText("App is now connected to:\n" +
IP + " : "
mHandler.sendEmptyMessage(UPDATE TEXT); //use
something like this
+ Port); // CRASHING !!!!
connectBt.setText("Disconnect");
connected = true;
continueBt.setVisibility(0);
} else {


On Wed, Jul 21, 2010 at 12:25 AM, stephan <dkn...@googlemail.com> wrote:

>



Other Threads

1. how to select text in a TextView?

Hey, i know i can long click a field and click "select all" in the pop-
up menu, but how can i select one word?
i also notice that i can only pop the menu on EditText but not
TextView, is that the way or i need to change some attributes?

Thanks a lot
--~--~---------~--~----~------------~-------~--~----~

2. Socket exception-unknown error from HttpClient execute() method

Hi everyone

I'm trying to figure out how to use HttpClient 4.x to do POST requests
routed via
a Proxy server. I'm seeing a socket exception triggered by calling

DefaultHttpClient.execute(HttpHost target, HttpRequest method). My
HttpPoster class looks like

package com.bt.gcto.android.testhttp;

import java.io.IOException;
import java.util.Hashtable;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.scheme.SocketFactory;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;

import android.net.Uri;
import android.util.Log;

public class HttpPoster {
       private final String TAG="HttpPoster";
           private final String NETWORK_DEVICE_SIDE_TRUE =
";deviceside=true";
           private final String NETWORK_DEVICE_SIDE_FALSE =
";deviceside=false";
           private final String NETWORK_WIFI = ";interface=wifi";
           //private final String proxy="proxy.intra.bt.com:8080";
           private boolean useWifi;
           private boolean deviceSide;
           // Apache HttpClient 4.x stuff
           private static HttpParams defaultParameters = null;
           private static SchemeRegistry supportedSchemes = null;


           /**
             * Performs general setup.
             * This should be called only once.
             */
            private final static void setup() {

                supportedSchemes = new SchemeRegistry();

                // Register the "http" and "https" protocol schemes, they are
                // required by the default operator to look up socket
factories.
                SocketFactory sf = PlainSocketFactory.getSocketFactory();
                supportedSchemes.register(new Scheme("http", sf, 80));
                sf = SSLSocketFactory.getSocketFactory();
                supportedSchemes.register(new Scheme("https", sf, 80));

                // prepare parameters
                HttpParams params = new BasicHttpParams();
                HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
                HttpProtocolParams.setContentCharset(params, "UTF-8");
                HttpProtocolParams.setUseExpectContinue(params, true);
                defaultParameters = params;

            } // setup

            private final static HttpParams getParams() {
                return defaultParameters;
            }


           HttpPoster(boolean deviceSide, boolean useWifi) {
               this.useWifi = useWifi;
               this.deviceSide = deviceSide;
               System.err.println("HttpPoster::HttpPoster");
           }



           public String post(String url,
                                                Hashtable<String,String> 
headerProperties, byte[] bytes )
              throws IOException {
                    HttpClient client = null;
                    HttpPost method=null;
                //InputStream is = null;
                //OutputStream os = null;
                //String response = "";
                HttpResponse rsp = null;
                HttpEntity entity=null;
                String fullUrl;
                //int rc;

                Log.d(TAG,"post() ---ENTER---");
                Log.d(TAG,"HttpPoster::post");
                Log.d(TAG,"http.proxyHost = " +
System.getProperty("http.proxyHost"));
                Log.d(TAG,"http.proxyPort = " +
System.getProperty("http.proxyPort"));
                try {
                    fullUrl = url + (deviceSide ? NETWORK_DEVICE_SIDE_TRUE :
NETWORK_DEVICE_SIDE_FALSE)
                     + (useWifi ? NETWORK_WIFI : "");
                    Uri fullUri = Uri.parse( fullUrl );
                    String targetname = fullUri.getHost();
                    Log.d(TAG,"HttpPoster::post -- about to open connection
on URL = " + fullUrl);
                    //
                    // setup proxy server
                    //
                        final HttpHost target = new HttpHost(targetname, 80,
"http");
                        final HttpHost proxy  = new 
HttpHost("proxy.mycompany.com",
8080, "http");

                        setup() ; // Some general setup
                        client = new DefaultHttpClient() ;
        
client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

                        method = new HttpPost( fullUrl );
                        Log.d(TAG,"Executing request to " + target + " via " +
proxy);
                        rsp = client.execute(target, method);
                        entity = rsp.getEntity();

                        
Log.d(TAG,"---------------------------------------------");
                        Log.d(TAG, rsp.getStatusLine().toString() );
                        Header [] headers = rsp.getAllHeaders();
                        for (int i=0; i<headers.length; i++) {
                                Log.d(TAG,"\t" + headers[i] );
                        }
                        
Log.d(TAG,"---------------------------------------------");

                        if (rsp.getEntity() != null) {
                                Log.d(TAG, EntityUtils.toString( 
rsp.getEntity() ) );
                        }
                } finally {
                        if (entity != null)
                                entity.consumeContent(); // release connection 
gracefully
                }
                // return response;
                Log.d(TAG,"post() ---EXIT---");
                return new String("");
            }

           private final static HttpClient createHttpClient() {

                ClientConnectionManager ccm =
                    new ThreadSafeClientConnManager(getParams(),
supportedSchemes);
                //  new SingleClientConnManager(getParams(),
supportedSchemes);

                DefaultHttpClient dhc =
                    new DefaultHttpClient(ccm, getParams());

                return dhc;
            }

        }




My TestHttp application launches an Activity TestHttp::onCreate()
method  whose DDMS logcat output is

08-21 14:25:54.189: DEBUG/TestHttp(238): onCreate()---enter---
08-21 14:25:54.248: DEBUG/TestHttp(238): httpClient is non-null
08-21 14:25:54.398: DEBUG/TestHttp(238): in catch {} response is null
08-21 14:25:54.418: ERROR/TestHttp(238): Error
08-21 14:25:54.418: ERROR/TestHttp(238): java.net.SocketException:
unknown error
08-21 14:25:54.418: ERROR/TestHttp(238):     at
org.apache.harmony.luni.platform.OSNetworkSystem.createSocketImpl(Native
Method)
08-21 14:25:54.418: ERROR/TestHttp(238):     at
org.apache.harmony.luni.platform.OSNetworkSystem.createSocket(OSNetworkSystem.java:
79)
08-21 14:25:54.418: ERROR/TestHttp(238):     at
org.apache.harmony.luni.net.PlainSocketImpl2.create(PlainSocketImpl2.java:
59)
08-21 14:25:54.418: ERROR/TestHttp(238):     at
java.net.Socket.checkClosedAndCreate(Socket.java:763)
08-21 14:25:54.418: ERROR/TestHttp(238):     at
java.net.Socket.connect(Socket.java:910)
08-21 14:25:54.418: ERROR/TestHttp(238):     at
org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:
117)
08-21 14:25:54.418: ERROR/TestHttp(238):     at
org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:
129)
08-21 14:25:54.418: ERROR/TestHttp(238):     at
org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:
164)
08-21 14:25:54.418: ERROR/TestHttp(238):     at
org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:
119)
08-21 14:25:54.418: ERROR/TestHttp(238):     at
org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:
348)
08-21 14:25:54.418: ERROR/TestHttp(238):     at
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:
555)
08-21 14:25:54.418: ERROR/TestHttp(238):     at
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:
509)
08-21 14:25:54.418: ERROR/TestHttp(238):     at
com.bt.gcto.android.testhttp.HttpPoster.post(HttpPoster.java:115)
08-21 14:25:54.418: ERROR/TestHttp(238):     at
com.bt.gcto.android.testhttp.TestHttp.onCreate(TestHttp.java:42)
08-21 14:25:54.418: ERROR/TestHttp(238):     at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:
1121)
08-21 14:25:54.418: ERROR/TestHttp(238):     at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:
2094)
08-21 14:25:54.418: ERROR/TestHttp(238):     at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:
2147)
08-21 14:25:54.418: ERROR/TestHttp(238):     at
android.app.ActivityThread.access$1800(ActivityThread.java:112)
08-21 14:25:54.418: ERROR/TestHttp(238):     at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1572)
08-21 14:25:54.418: ERROR/TestHttp(238):     at
android.os.Handler.dispatchMessage(Handler.java:88)
08-21 14:25:54.418: ERROR/TestHttp(238):     at
android.os.Looper.loop(Looper.java:123)
08-21 14:25:54.418: ERROR/TestHttp(238):     at
android.app.ActivityThread.main(ActivityThread.java:3708)
08-21 14:25:54.418: ERROR/TestHttp(238):     at
java.lang.reflect.Method.invokeNative(Native Method)
08-21 14:25:54.418: ERROR/TestHttp(238):     at
java.lang.reflect.Method.invoke(Method.java:492)
08-21 14:25:54.418: ERROR/TestHttp(238):     at
com.android.internal.os.ZygoteInit
$MethodAndArgsCaller.run(ZygoteInit.java:734)
08-21 14:25:54.418: ERROR/TestHttp(238):     at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:492)
08-21 14:25:54.418: ERROR/TestHttp(238):     at
dalvik.system.NativeStart.main(Native Method)
08-21 14:25:54.449: DEBUG/TestHttp(238): onCreate()---exit----

The TestHtpp Activity exercises HttpPoster::post() within its
onCreate() method, thus

public class TestHttp extends Activity {
        private static final String TAG="TestHttp";
        private DefaultHttpClient httpClient = null;
        private final Uri galleryServerUri= Uri.parse("http://my-gallery-
server/gallery2/main.php");
        private final String uname = "graeme";
        private final String pwd = "123456";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        Log.d(TAG,"onCreate()---enter---");
        super.onCreate(icicle);
        setContentView(R.layout.main);
        try {
                HttpPoster poster = new HttpPoster(false, false) ;
                poster.post( galleryServerUri.toString(), null,
null );
        } catch (Exception e) {
                Log.e(TAG, "Error", e);
        }
        Log.d(TAG,"onCreate()---exit----");
    }
}



The logcat ouput from class HttpPoster is just ...

08-21 14:25:54.257: DEBUG/HttpPoster(238): post() ---ENTER---
08-21 14:25:54.257: DEBUG/HttpPoster(238): HttpPoster::post
08-21 14:25:54.257: DEBUG/HttpPoster(238): http.proxyHost = null
08-21 14:25:54.257: DEBUG/HttpPoster(238): http.proxyPort = null
08-21 14:25:54.269: DEBUG/HttpPoster(238): HttpPoster::post -- about
to open connection on URL = 
http://my-gallery-server/gallery2/main.php;deviceside=false
08-21 14:25:54.289: DEBUG/HttpPoster(238): Executing request to
http://my-gallery-server:80 via http://proxy.mycompany.com:8080

I am running Android SDK-0.9 on and Windows XP SP2 devel machine.
Do I need to take any special; steps to enable the emulator to open
network
(socket) connections ?

Thanks for any help.
Graeme

--~--~---------~--~----~------------~-------~--~----~

3. How to listen for changes on SMS content provider?

4. One week to go.....

5. UK pre-registrations...

6. Package problem?

7. Emulator bug: Intent action/categories is null