Unfortunately has stopped

2019-03-04 02:38发布

问题:

I have an app where the user submits some data in a form which is then sent to a server. I am testing it on a tablet and an Android smartphone (Galaxy S2). On the tablet, as soon as I click on "Submit", the application stops working with the message "Unfortunately has stopped working". This problem is not seen on either the phone or the emulator, which has me stumped.

There is another screen in the app where the user has the option to re-submit the same credentials. There too, the same problem is encountered. The rest of the app works OK. This has led me to conclude that the problem might lie in the way I am sending data to the server. That code snippet is as follows:

//code to send to server should begin here.
        HttpClient hc = new DefaultHttpClient();
        HttpPost hp = new HttpPost("http://www.mywebsite.com/takeDetails.php");

        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            String val = "new";
            nameValuePairs.add(new BasicNameValuePair("mode", val));
            nameValuePairs.add(new BasicNameValuePair("name", name));
            nameValuePairs.add(new BasicNameValuePair("number", number));
            nameValuePairs.add(new BasicNameValuePair("email", emailID));
            Log.v(this.toString(), "Email = " + emailID);
            hp.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            // Execute HTTP Post Request
            HttpResponse response = hc.execute(hp);

            //Toast.makeText(getApplicationContext(), "Attempting to register.", Toast.LENGTH_LONG).show();

            String responseBody = EntityUtils.toString(response.getEntity());
            if(responseBody.contains("Success")) {
                Toast.makeText(getApplicationContext(), "Thank you for registering! You will receive an email with your username and password shortly.", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(getApplicationContext(), "Attempt to register failed.", Toast.LENGTH_LONG).show();
            }
            Log.v(this.toString(), "HTTP Response = " + responseBody);

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }

Logcat output:

V/com.sriram.htmldisplay.htmlDisplay@4107bef0( 3766): Line read = Name: jguyjfhf
V/com.sriram.htmldisplay.htmlDisplay@4107bef0( 3766): Line read = Number: 668895898
V/com.sriram.htmldisplay.htmlDisplay@4107bef0( 3766): Line read = Email ID:jvjhfhc@ccf.mkj
V/com.sriram.htmldisplay.htmlDisplay@4107bef0( 3766): User details gleaned = Name = jguyjfhf
V/com.sriram.htmldisplay.htmlDisplay@4107bef0( 3766): 668895898
V/com.sriram.htmldisplay.htmlDisplay@4107bef0( 3766): jvjhfhc@ccf.mkj
V/com.sriram.htmldisplay.htmlDisplay@4107bef0( 3766): Email = jvjhfhc@ccf.mkj
D/AndroidRuntime( 3766): Shutting down VM
W/dalvikvm( 3766): threadid=1: thread exiting with uncaught exception (group=0x409f11f8)
E/AndroidRuntime( 3766): FATAL EXCEPTION: main
E/AndroidRuntime( 3766): android.os.NetworkOnMainThreadException
E/AndroidRuntime( 3766):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
E/AndroidRuntime( 3766):    at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
E/AndroidRuntime( 3766):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
E/AndroidRuntime( 3766):    at java.net.InetAddress.getAllByName(InetAddress.java:220)
E/AndroidRuntime( 3766):    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
E/AndroidRuntime( 3766):    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
E/AndroidRuntime( 3766):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
E/AndroidRuntime( 3766):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
E/AndroidRuntime( 3766):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
E/AndroidRuntime( 3766):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
E/AndroidRuntime( 3766):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
E/AndroidRuntime( 3766):    at com.sriram.htmldisplay.htmlDisplay.writeSendDetails(htmlDisplay.java:200)
E/AndroidRuntime( 3766):    at com.sriram.htmldisplay.htmlDisplay.access$10(htmlDisplay.java:127)
E/AndroidRuntime( 3766):    at com.sriram.htmldisplay.htmlDisplay$1.onClick(htmlDisplay.java:110)
E/AndroidRuntime( 3766):    at android.view.View.performClick(View.java:3511)
E/AndroidRuntime( 3766):    at android.view.View$PerformClick.run(View.java:14105)
E/AndroidRuntime( 3766):    at android.os.Handler.handleCallback(Handler.java:605)
E/AndroidRuntime( 3766):    at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime( 3766):    at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime( 3766):    at android.app.ActivityThread.main(ActivityThread.java:4424)
E/AndroidRuntime( 3766):    at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime( 3766):    at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime( 3766):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
E/AndroidRuntime( 3766):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
E/AndroidRuntime( 3766):    at dalvik.system.NativeStart.main(Native Method)
D/dalvikvm( 3766): GC_CONCURRENT freed 290K, 7% free 6697K/7175K, paused 4ms+6ms
W/ActivityManager( 1268):   Force finishing activity com.sriram.htmldisplay/.htmlDisplay
D/TabletStatusBar( 1340): hiding the MENU button
W/ActivityManager( 1268): Activity pause timeout for ActivityRecord{41406c60 com.sriram.htmldisplay/.htmlDisplay

My questions:
1. Is there a better way to handle errors from the HTTPClient?
2. Any ideas on what may be causing only the tablet to fail are most welcome.

回答1:

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

add this code in onCreate

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

StrictMode.setThreadPolicy(policy); 

or add HTTP call code into AsyncTask

class RetreiveFeedTask extends AsyncTask<String, Void, RSSFeed> {

        private Exception exception;

        protected RSSFeed doInBackground(String... urls) {
            try {

                // add your all code here

            } catch (Exception e) {
                this.exception = e;
                return null;
            }
        }

        protected void onPostExecute(RSSFeed feed) {
            // TODO: check this.exception 
            // TODO: do something with the feed
        }
     }

to execute the AsyncTask:

new RetreiveFeedTask().execute(urlToRssFeed);

hope you have added below permission in android manifest file

<uses-permission android:name="android.permission.INTERNET"/>


回答2:

You're trying to run a network request on the main UI thread. Android does not allow you to do that since 3.0 (I believe). Doing so causes your UI to lock up until the request is completed, rendering your app useless during the execution of the request.

You'll either have to run your request in a new Thread or an ASyncTask, to take the load of the UI thread. You can find more info on how to use multiple threads here.



回答3:

You're doing your network operations from the main thread, which is a very very bad idea. You should at least do this inside an AsyncTask.



回答4:

This issue is happening that you are not using the painless thread. That all the android os versions which is higher than 3.0 wont support any king of internet accessing works (http connections ) in the oncreate.. So that you are supposed to use ASYNCTask . please have a look at this link to know about this .

http://samir-mangroliya.blogspot.in/p/android-asynctask-example.html

http://developer.android.com/reference/android/os/AsyncTask.html