简体   繁体   中英

program close when failing to reach server

I'm new to Android and programming in general. I've built an activity that runs a service that connects to a PHP script to pull some data from a server. The problem is that when the program can't reach the server it crashes. How do I prevent the program from crashing each time it can't reach the php script? Thanks.

The relevant part of the code:

private String getServerData(String returnString) {

      InputStream is = null;

      String result = "";


       try{
               HttpClient httpclient = new DefaultHttpClient();
               HttpPost httppost = new HttpPost(returnString);
               HttpResponse response = httpclient.execute(httppost);
               HttpEntity entity = response.getEntity();
               is = entity.getContent();

       }catch(Exception e){
               Log.e("log_tag", "Error in http connection "+e.toString());
       }

       //convert response to string
       try{
               BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
               StringBuilder sb = new StringBuilder();
               String line = null;
               while ((line = reader.readLine()) != null) {
                       sb.append(line + "\n");
                           }
               is.close();
               result=sb.toString();

           }catch(Exception e){
               Log.e("log_tag", "Error converting result "+e.toString());
       }

       return result; 

   }    

.

08-29 13:10:01.571: ERROR/AndroidRuntime(1116): <p>The requested URL /getAvgScore1.php was not found on this server.</p>
08-29 13:10:01.571: ERROR/AndroidRuntime(1116): <p>Additionally, a 404 Not Found
08-29 13:10:01.571: ERROR/AndroidRuntime(1116): error was encountered while trying to use an ErrorDocument to handle the request.</p>
08-29 13:10:01.571: ERROR/AndroidRuntime(1116): </body></html>
08-29 13:10:01.571: ERROR/AndroidRuntime(1116):     at org.apache.harmony.luni.util.FloatingPointParser.initialParse(FloatingPointParser.java:132)
08-29 13:10:01.571: ERROR/AndroidRuntime(1116):     at org.apache.harmony.luni.util.FloatingPointParser.parseFloat(FloatingPointParser.java:310)
08-29 13:10:01.571: ERROR/AndroidRuntime(1116):     at java.lang.Float.parseFloat(Float.java:327)
08-29 13:10:01.571: ERROR/AndroidRuntime(1116):     at java.lang.Float.valueOf(Float.java:368)
08-29 13:10:01.571: ERROR/AndroidRuntime(1116):     at iAndroid.RYCQ.rankservice.onCreate(rankservice.java:46)
08-29 13:10:01.571: ERROR/AndroidRuntime(1116):     at android.app.ActivityThread.handleCreateService(ActivityThread.java:2465)
08-29 13:10:01.571: ERROR/AndroidRuntime(1116):     ... 10 more
08-29 13:10:01.581: INFO/Process(583): Sending signal. PID: 1116 SIG: 3
08-29 13:10:01.581: INFO/dalvikvm(1116): threadid=7: reacting to signal 3
08-29 13:10:01.591: INFO/dalvikvm(1116): Wrote stack trace to '/data/anr/traces.txt'
08-29 13:10:10.634: WARN/ActivityManager(583): Launch timeout has expired, giving up wake lock!
08-29 13:10:10.634: WARN/ActivityManager(583): Activity idle timeout for HistoryRecord{436eed60 {iAndroid.RYCQ/iAndroid.RYCQ.finalresult}}
08-29 13:10:20.698: WARN/ActivityManager(583): Timeout executing service: ServiceRecord{437c8d88 iAndroid.RYCQ/.rankservice}

Probably you'll just have to catch whatever exception is being thrown when connecting to your server fails. You need to post the code that you are currently using though. Without being able to see what you've done we can only guess randomly at what will fix it.

    public static InputStream fetch(String urlString) throws MalformedURLException, IOException {
    HttpParams httpParameters = new BasicHttpParams();

    int timeoutConnection = 3000;
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);

    int timeoutSocket = 5000;
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

    DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
    HttpGet request = new HttpGet(urlString);
    HttpResponse response = httpClient.execute(request);
    return response.getEntity().getContent();
}

You have to put timeoutConnection and timeoutSocket values so that device won't be waiting for response forever. More info about fields are accessible here .

If there is an Exception thrown in the 1st try block, you instanciate a BufferedReader on a null InputStream . Have only one try/catch block, or properly quit the method in the first catch .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM