1 Replies - 592 Views - Last Post: 03 June 2015 - 01:57 AM Rate Topic: -----

#1 alk   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 02-June 15

Efficiency and connection problems when executing AsyncTask within Loo

Posted 02 June 2015 - 04:19 PM

I'm designing an android app which stores user bets in a database. I use an AsyncTask which fetches the details of all of the users bets from the database in the following format.

 {"bet":[{"id":"dofahgnr07t21dd9en4d3abl5l","teams":"(12\/X)(11\/X)","stake":"5","returns":"74","status":"open","user":"[email protected]"},{"id":"7gfeu366vemjk663btap960ha","teams":"(10\/1)(11\/1)","stake":"1","returns":"1","status":"open","user":"[email protected]"} 

After this is done I retrieve the teams variable for each bet (10/1) for example (event id/ outcome) and I use the following loop to check the outcome of each of the users bets before they are displayed to them in a listview.

 for (HashMap<String,String> a : bet){
                        currentitem = a;
                        String teams = a.get(TAG_TEAMS);
                        Map<String,String> listofteams = new HashMap<>();

                        Pattern p = Pattern.compile("[(](\\d+)/([1X2])[)]");
                        Matcher m = p.matcher(teams);
                        Log.d("printa", teams);
                            listofteams.put(m.group(1), m.group(2));
                        if (a.get(TAG_STATUS).equals("open")) {
                            CheckBet checker = new CheckBet(listofteams);
                            String finaloutcome = checker.checkbetoutcome();}}

This loop calls on the following class:


public class CheckBet {
    private Map<String, String> bet;
    private ArrayList<String> statuses = new ArrayList<>();
    private ArrayList<String> userstatuses = new ArrayList<>();
    private String status = "open";
    private static String url_check_bet = "******";
    String resulttest;
    private String currentitem;
    private String game;
    private String finalstatus = "won";
    private String c = "";
    JSONArray allgames = null;

    public CheckBet(Map<String, String> bet) {
        this.bet = bet;


    public String checkbetoutcome() {
        for (String x : bet.keySet()) {
            String b = x + ",";
            c = c + b;
            Log.d("X", x);
            currentitem = x;
        c = c.substring(0, c.lastIndexOf(","));
        new LoadAllGamet().execute();
        try {
            Thread.sleep(4000);                 //1000 milliseconds is one second.
        } catch(InterruptedException ex) {
        Log.d("C", c);
        return backgrounder();
    public String backgrounder() {
        for (int i = 0; i < userstatuses.size(); i++) {
            Log.d("STATUS", statuses.get(i));
            if (statuses.get(i).equals("null")) {
                finalstatus = "open";
            else if (!(statuses.get(i).equals(userstatuses.get(i)))) {
                finalstatus = "lost";
        return finalstatus;

    class LoadAllGamet extends AsyncTask<String, String, String> {
        protected void onPreExecute() {


        protected String doInBackground(String... args) {
            HttpParams httpParameters = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpParameters, 250000);
            HttpConnectionParams.setSoTimeout(httpParameters, 250000);
            HttpClient client = new DefaultHttpClient(httpParameters);
            HttpPost post = new HttpPost(url_check_bet);
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("param", c));
            Log.d("CURRENTITEM", currentitem);
            try {
                post.setEntity(new UrlEncodedFormEntity(params));
            } catch (IOException ioe) {
            try {
                HttpResponse response = client.execute(post);
                Log.d("Http Post Responsecxxx:", response.toString());
                HttpEntity httpEntity = response.getEntity();
                InputStream is = httpEntity.getContent();
                JSONObject jObj = null;
                String json = "";
                try {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(
                            is, "iso-8859-1"), 8);
                    StringBuilder sb = new StringBuilder();
                    String line = null;
                    while ((line = reader.readLine()) != null) {

                        if (!line.startsWith("<", 0)) {
                            if (!line.startsWith("(", 0)) {
                                sb.append(line + "\n");

                    json = sb.toString();

                    json = json.substring(json.indexOf('{'));
                    Log.d("sbsssssssssss", json);
                    try {
                        jObj = new JSONObject(json);
                    } catch (JSONException e) {
                        Log.e("JSON Parser", "Error parsing data " + e.toString());
                    allgames = jObj.getJSONArray("bet");
                    Log.d("WHAT IS MY ARRAY?", allgames.toString());

                        for (int i = 0; i < allgames.length(); i++) {
                            JSONObject c = allgames.getJSONObject(i);

                            // Storing each json item in variable
                            String Result = c.getString("Result");


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

             catch (IOException e) {

            return "";

        protected void onPostExecute(String param) {

The problem here is that if the user has 20 bets for example, the AsyncTask is executed 20 times, and 20 httpconnections are made. This forces me to include all the Thread.sleep() lines of code, as otherwise the next lines of code are executed before the httpconnection finishes and I end up with nullpointerexceptions etc. in the further code as it is not populated with values in time. Furthermore, even with this set up, if the amount of bets is large, I get nullpointer exceptions at this line Log.d("STATUS", statuses.get(i)); as the statuses arraylist is not populated in time. I also get ETIMEDOUT Connection refused exceptions if the amount of bets is large. This process is absolutely vital to the functioning of my app and currently the whole process is incredibly inefficient as the user has to wait 4 seconds after each bet is processed. I use AsyncTasks in other locations to send new bets to my database and to load all the available events and odds and this works without any problem. As someone who doesn't have a lot of experience with using AsyncTasks and php, my question is how can I make this code more efficient and avoid all these errors and the long processig time. The obvious solution seems to be to pass all the user bets within one AsyncTask and do the processing on the side of the php, however I do not have an idea on how to do this. I will post the two php files I use to this question as they may be of help to you. I understand this is an unconventional question without an obvious response, but I hope for all the help I can get. I think this is the only code that is relevant to the problem, however if you think you need more information, let me know and I will provide any other info you may require.


    // get tag
   $param= $_POST['param'];
   $id = explode(",",$param);
   $arrlength = count($id);
    // include db handler
     require_once 'include/Check_Bets.php';

    $db = new Check_Bets();
    $response["bet"] = array();

   for($x = 0; $x < $arrlength; $x++) {

    $result= $db->checkuserbets($id[$x]);
    array_push($response["bet"], $result);
    echo json_encode($response);




class Check_Bets {

   function __construct() {

	require_once 'DB_Connect.php';
	$this->db = new DB_Connect();



function __destruct() {

  public function checkuserbets($id) {

   $conn=mysqli_connect("****", "***", "***","***");

   $result = mysqli_query($conn,"SELECT Result FROM gamelist WHERE gid = '$id'");
 $no_of_rows = mysqli_num_rows($result);
    if ($no_of_rows > 0) {

 return mysqli_fetch_array($result,MYSQLI_ASSOC);

Is This A Good Question/Topic? 0
  • +

Replies To: Efficiency and connection problems when executing AsyncTask within Loo

#2 g00se   User is online

  • D.I.C Lover
  • member icon

Reputation: 3704
  • View blog
  • Posts: 16,980
  • Joined: 20-September 08

Re: Efficiency and connection problems when executing AsyncTask within Loo

Posted 03 June 2015 - 01:57 AM


Efficiency and connection problems when executing AsyncTask within Loo

Don't do it in the lavatory - it's not hygienic


Pattern p = Pattern.compile("[(](\\d+)/([1X2])[)]");

That's not hygienic either - never home brew a parser when you can use a proper one. You have JSON - get a JSON parser and use it.

I don't do Android so can't address those specific issues
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1