How to prevent PhoneGap application from freezing on Android while making an asynchronous AJAX call?

I have a PhoneGap-Android app and I'm using jQuery. I make an ASYNCHRONOUS AJAX call, and during the call the application just hangs and waits after the AJAX call ends (this is mainly noticeable when connected via GSM).

I would understand this if I were doing a synchronous request, but I have:

$.ajax({type: 'POST',url: 'http://www.example.com', data: data,async:true,success:callback});

Can anybody help?

+5
source share
5 answers

I got into the same problem today. Solved it using setTimeout with a delay of 10 ms.

I don’t know why this works, which is scary. But it works.

+1
source

AJAX ? :

public class JsonParsingActivity extends Activity {

    private static final String url = "http://search.twitter.com/search.json?q=javacodegeeks";
    protected InitTask _initTask;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button button = (Button)findViewById(R.id.button1);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                _initTask = new InitTask();
                _initTask.execute( getApplicationContext() );
            }
        });
    }

    @Override
    public void onStop() {
        super.onStop();
        _initTask.cancel(true);
    }

    protected class InitTask extends AsyncTask<Context, String, SearchResponse>
    {
        @Override
        protected SearchResponse doInBackground( Context... params ) 
        {
            InputStream source = retrieveStream(url);
            SearchResponse response = null;
            if (source != null) {
                Gson gson = new Gson();
                Reader reader = new InputStreamReader(source);
                try {
                    response = gson.fromJson(reader, SearchResponse.class);
                    publishProgress( response.query );
                    reader.close();
                } catch (Exception e) {
                    Log.w(getClass().getSimpleName(), "Error: " + e.getMessage() + " for URL " + url);
                }
            }
            if (!this.isCancelled()) {
                return response;
            } else {
                return null;
            }
        }

        @Override
        protected void onProgressUpdate(String... s) 
        {
            super.onProgressUpdate(s);
            Toast.makeText(getApplicationContext(), s[0], Toast.LENGTH_SHORT).show();
        }

        @Override
        protected void onPostExecute( SearchResponse response ) 
        {
            super.onPostExecute(response);
            StringBuilder builder = new StringBuilder();
            if (response != null) {
                String delim = "* ";
                List<Result> results = response.results;
                for (Result result : results) {
                    builder.append(delim).append(result.fromUser);
                    delim="\n* ";
                }
            }
            if (builder.length() > 0) {
                Toast.makeText(getApplicationContext(), builder.toString(), Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getApplicationContext(), "The response was empty.", Toast.LENGTH_SHORT).show();
            }

        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
            Toast.makeText(getApplicationContext(), "The operation was cancelled.", 1).show();
        }

        private InputStream retrieveStream(String url) {
            DefaultHttpClient client = new DefaultHttpClient(); 
            HttpGet getRequest;
            try {
                getRequest = new HttpGet(url);
                HttpResponse getResponse = client.execute(getRequest);
                HttpEntity getResponseEntity = getResponse.getEntity();
                return getResponseEntity.getContent();
            } catch (Exception e) {
                Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
                return null;
            }
        }

    }

}
+1

, , ajax "deviceready", .

, , ajax . document deviceready ajax . .

function appReady(){
  // do the ajax here
}
document.addEventListener("deviceready", appReady, false);

, .

+1

Jquery:

: true (.. true). , false. dataType: "jsonp" . , , , .

localhost, . , GET POST.

0

:

 $(document).ready(function () {
        $.ajax({     
        type: "POST",
        url: "https://demo.yoursuppliernetwork.com/tnvrs/userservice/login/checkUser",
        data:{"username":login,"password":password},
        dataType:"json",
        contentType: "application/json; charset=utf-8",
        success: function(html)
        {
            ss=html; 
            console.log(ss);
            document.write("success");
        },
       error:function(error)
       {
        console.log(error.status)
        document.write("error");
       },
       complete:function(html){
       console.log()
       document.write("complete");
       }
            });

     });
0

All Articles