How to handle slow network connection in Java/Android

前端 未结 3 1321
一个人的身影
一个人的身影 2021-01-06 02:17

I have an app that uses many, many calls to a MySQL database; it does this inside an AsyncTask. Below is a sample of what one may look like.

My main qu

相关标签:
3条回答
  • 2021-01-06 02:29
    1. Your doInBackground returns NULL. return null; You would usually return result; there

    2. your onPostExecute(has NuLL here) :)) as a result. and here onPostExecute(String result) and handle it out this way. Check the example posted again.

    3. You have to handle out these nulls (and perhaps dismiss this progressdialog in the
      onPostExecute() )

    8-13 14:57:00.596: E/AndroidRuntime(2262):     at com.---.--  -.MyFragmentActivity$RateFragment$RatingTask.onPostExecute(MyFragmentActivity.java:461)
       08-13 14:57:00.596: E/AndroidRuntime(2262):     at com.---.---.MyFragmentActivity$RateFragment$RatingTask.onPostExecute(MyFragmentActivity.java:1)
    
    0 讨论(0)
  • 2021-01-06 02:35

    Begin with checking if there is a connection available, and notify the user if there isn't.

    Especially if the user tries to interrupt it (most I have set to non-cancelable, however).

    I would reconsider that decision. Personally, I don't like non-interruptible processes. My suggestion is that you go on from what @CommonsWare suggests in the comments here. Shortly, have a boolean variable that checks whether the data is invalid or your own check to see if your data is null. If it is, don't execute any commands based from this data and you won't have any force closes related to this.

    Is there a better way to handle this than I am below?

    Besides from what is stated above, I'd recommend adding some HTTP parameters to your http client. For example:

    final int CONN_WAIT_TIME = 3000;
    final int CONN_DATA_WAIT_TIME = 2000;
    
    HttpParams httpParams = new BasicHttpParams();      
    HttpConnectionParams.setConnectionTimeout(httpParams, CONN_WAIT_TIME);
    HttpConnectionParams.setSoTimeout(httpParams, CONN_DATA_WAIT_TIME);
    
    DefaultHttpClient postClient = new DefaultHttpClient(httpParams);
    
    // Go on...
    

    If your http client exceeds the time you put in their respective fields, it will simply give you a ConnectTimeoutException. Now you know enough to consider if the data is valid in onPostExecute() and whether you should go on using it or not.

    0 讨论(0)
  • 2021-01-06 02:49

    Your exception is caused because you still have a Dialog showing while you've entered a different Activity. Before you say

    Intent i = new Intent(getApplicationContext(), Items.class);
    i.putExtra("category", cats.get(arg2));
    startActivity(i);
    

    Call this:

    progressDialog.dismiss()
    

    And your activity will not leak anymore.

    0 讨论(0)
提交回复
热议问题