-2

So my object is simple and need to know if I can either make my code better all the way around or remove sleep from my code and somehow wait for the async task to finish with getting data from a database before loading maps.

After fighting with trying to figure out why my code wasn't working as it should I put 5 different LOG.i in labeled STEP 1 to STEP 5 and in the order I expected things to run.

Well after looking at the logs when I did this, it was running in this order, STEP 4, then 1, 5 , 2, then 3. So I added a temp sleep timer in and now it is showing in logcat the steps in order 1 through 5.

I know a 10 second sleep is too long. Is there a way to do a sleep on a flag instead of a predetermined amount of time, like in a while loop. Something like while vara = 0 and varb = 0 sleep a milisecond or something like that?

Or is there just a better way to write my code so that way it is more efficient and not have to use sleep at all?

Below is my current code:

import android.os.AsyncTask;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.app.restaurant.bowzers.R;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import java.util.concurrent.TimeUnit;

public class TruckFragment2 extends Fragment{
    double mylocationLong, mylocationLat;
    String mySB;
    GoogleMap googleMap;
    GoogleMap gMap;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Initialize view
        View view=inflater.inflate(R.layout.fragment_truck, container, false);

        mylocationLat = 39.9;
        mylocationLong = -82.83;



        getJSON("https://bowzershotdogstand.com/app/get_location.php");
        try {
            TimeUnit.SECONDS.sleep(10);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        Log.i("STEP 4",mylocationLong + "," + mylocationLat);
        LatLng latLng = new LatLng(mylocationLat,mylocationLong);
        // Initialize map fragment
        SupportMapFragment supportMapFragment=(SupportMapFragment)
                getChildFragmentManager().findFragmentById(R.id.truck_map);


        // Async map
        supportMapFragment.getMapAsync(new OnMapReadyCallback() {
            @Override
            public void onMapReady(@NonNull GoogleMap googleMap) {
gMap=googleMap;
                Log.i("STEP 5", mylocationLong + "," + mylocationLat);






                     MarkerOptions markerOptions=new MarkerOptions();
                        // Set position of marker
                        markerOptions.position(latLng);
                        // Set title of marker
                        markerOptions.title(latLng.latitude+" : "+latLng.longitude);
                        // Remove all marker
//                        gMap.clear();
                        // Animating to zoom the marker
                        gMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,16));
                        // Add marker on map
                        gMap.addMarker(markerOptions);
//                    }
//                });
            }
        });

        // Return view
        return view;
    }
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    public void getJSON(final String urlWebService) {
        class GetJSON extends AsyncTask<Void, Void, String> {



            protected void onPreExecute() {
                super.onPreExecute();

            }

            protected void onPostExecute(String s) {
                super.onPostExecute(s);


            }

            protected String doInBackground(Void... Voids) {
                Log.i("STEP 1", urlWebService);
                try {
                    URL url = new URL(urlWebService);
                    HttpURLConnection con = (HttpURLConnection) url.openConnection();
                    StringBuilder sb = new StringBuilder();
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
                    String json;
                    while ((json = bufferedReader.readLine()) != null) {
                        sb.append((json + "\n"));

                    }
                    Log.i("STEP 2", String.valueOf(sb));
                    mySB = String.valueOf(sb);

//                    JSONArray JA = new JSONArray(mySB);
                    JSONArray JA = new JSONArray(mySB);
                    for(int i =0 ;i <JA.length(); i++){
                        JSONObject JO = (JSONObject) JA.get(i);
                                mylocationLong = Double.parseDouble(JO.getString("longitude"));
                                mylocationLat = Double.parseDouble(JO.getString("lattitude"));
                                Log.i("STEP 3", mylocationLat + "," + mylocationLong);

                        LatLng marker = new LatLng(mylocationLong,mylocationLat);


                        gMap.clear();
                        gMap.addMarker(new MarkerOptions().position(marker).title("Marker Somewhere"));
                        gMap.moveCamera(CameraUpdateFactory.newLatLng(marker));
                                break;
                        }

                    return sb.toString().trim();

                } catch (Exception e) {
                    return null;
                }
            }
        }
        GetJSON getJSON = new GetJSON();
        getJSON.execute();
    }

}
6
  • 1
    Please stop using AsyncTask its been deprecated for years now.. You can use any of alternate . Commented Jan 30, 2024 at 6:00
  • 2
    One does not wait for an async task to finish. Instead one does what one has to do in onPostExecute. So place all code after the getjson() call in onPostExecute. Commented Jan 30, 2024 at 6:45
  • You can also add a Callback to the constructor of your task and call it in onPostExecute. Commented Jan 30, 2024 at 6:46
  • Wrong.. your separate getjson function to create and execute the task. Wrong also to call it get json. Commented Jan 30, 2024 at 6:47
  • 2
    Even if you are going to use an asynctask alternative you have to redesign your code as you cannot wait then too . Commented Jan 30, 2024 at 6:57

2 Answers 2

0

I'm not familiar with android development, but in plain java i would consider this code

CompletableFuture.supplyAsync(() -> "Your code here").get()

Method supplyAsync(Function fn) makes your code execute in ForkJoinPool asynchronously

Method get() waits for the response

Methods thenApply(Function fn) and thenRun(Function fn) applies your function to the result of computation

Sign up to request clarification or add additional context in comments.

Comments

0

So by recommendation of blackapps, I chose to go that route for now, as I am in a time crunch to get this app published. After some reading, I do agree with ADM, that I need to use something other than asynctask to do this, and I will research this option further and implement it and release it as an update.

Below is the final revised code that solves my issue immediately at hand which was to execute tasks in the proper order without having to use a sleep timer.

import android.os.AsyncTask;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.app.restaurant.bowzers.R;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


public class TruckFragment2 extends Fragment{
    double mylocationLong, mylocationLat;
    String mySB;
    GoogleMap gMap;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Initialize view
        View view=inflater.inflate(R.layout.fragment_truck, container, false);

        mylocationLat = 39.9;
        mylocationLong = -82.83;



        getJSON("https://bowzershotdogstand.com/app/get_location.php");
 
        // Return view
        return view;

    }
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    public void getJSON(final String urlWebService) {
        class GetJSON extends AsyncTask<Void, Void, String> {



            protected void onPreExecute() {
                super.onPreExecute();

            }

            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                Log.i("STEP 4",mylocationLong + "," + mylocationLat);
                LatLng latLng = new LatLng(mylocationLat,mylocationLong);
                // Initialize map fragment
                SupportMapFragment supportMapFragment=(SupportMapFragment)
                        getChildFragmentManager().findFragmentById(R.id.truck_map);


                // Async map
                supportMapFragment.getMapAsync(new OnMapReadyCallback() {
                    @Override
                    public void onMapReady(@NonNull GoogleMap googleMap) {
                        gMap=googleMap;
                        Log.i("STEP 5", mylocationLong + "," + mylocationLat);






                        MarkerOptions markerOptions=new MarkerOptions();
                        // Set position of marker
                        markerOptions.position(latLng);
                        // Set title of marker
                        markerOptions.title(latLng.latitude+" : "+latLng.longitude);
                        // Remove all marker
                        gMap.clear();
                        // Animating to zoom the marker
                        gMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,16));
                        // Add marker on map
                        gMap.addMarker(markerOptions);
//                    }
//                });
                    }
                });


            }

            protected String doInBackground(Void... Voids) {
                Log.i("STEP 1", urlWebService);
                try {
                    URL url = new URL(urlWebService);
                    HttpURLConnection con = (HttpURLConnection) url.openConnection();
                    StringBuilder sb = new StringBuilder();
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
                    String json;
                    while ((json = bufferedReader.readLine()) != null) {
                        sb.append((json + "\n"));

                    }
                    Log.i("STEP 2", String.valueOf(sb));
                    mySB = String.valueOf(sb);

//                    JSONArray JA = new JSONArray(mySB);
                    JSONArray JA = new JSONArray(mySB);
                    for(int i =0 ;i <JA.length(); i++){
                        JSONObject JO = (JSONObject) JA.get(i);
                                mylocationLong = Double.parseDouble(JO.getString("longitude"));
                                mylocationLat = Double.parseDouble(JO.getString("lattitude"));
                                Log.i("STEP 3", mylocationLat + "," + mylocationLong);

                        LatLng marker = new LatLng(mylocationLong,mylocationLat);
                        break;
                        }

                    return sb.toString().trim();

                } catch (Exception e) {
                    return null;
                }
            }
        }
        GetJSON getJSON = new GetJSON();
        getJSON.execute();
    }

}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.