Get the new variable into the JSON String after getting the new value from the server

拜拜、爱过 提交于 2020-01-06 07:16:09

问题


I am starting my TrackingService class from the MainActivity which just contains this onCreate() method:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Intent i = new Intent(this, TrackingService.class);
    startService(i);

}

I am sending some data route, long, lat, mac to the server. When the route is not 0 I am getting the following response from the server {"status": 201}. Often the routes is 0 then the server is being asked to provide the app with the routes when there is enough information to calculate it. In this case I am getting this response

{
 "status":230,
 "routes":[9],
 "distance":296.7374922
}

Afterwards the routes will be passed to the onAsyncTaskFinished in the TrackingService class. There the route_number is being assigned to the new value 9 subsequently the routes in the JSON string has a vlaue of 9and can be sent to the server to insert into the database table.

From the TrackingService I am envloping the route, long, lat, mac with Gson and send it to the PostData class then the data will be transmitted to the server with the aid of AsyncTask.

The code works well when the app runs in the foreground but it processes wrong when it runs in the background. The route_number is not being assigned to the new value.

public class TrackingService extends Service implements AsyncTaskCallback  {

    Location location;
    LocationManager locationManager;

    int route_number = 0;
    int speed;
    double pLong;
    double pLat;

    @Override
    public void onCreate() {


    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        detectLocation();

        return START_STICKY;
    }

    private void detectLocation() {

        LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        LocationListener ll = new myLocationListener(this);
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10 * 1000, 0,
                ll);

    }

    class myLocationListener implements LocationListener {
        final Context bContext;

        public myLocationListener(Context context) {
            bContext = context;
        }

        @Override
        public void onLocationChanged(Location location) {

            // TODO Auto-generated method stub
            if (location != null) {
                 pLong = location.getLongitude();
                 pLat = location.getLatitude();
                 speed = (int) ((location.getSpeed() * 3600) / 1000);

                String mac = get_mac_address();

                String jSONString = convertToJSON(mac, pLong, pLat, time);

                if (isNetworkAvailable()) {
                    System.out.println(jSONString);

                    PostData sender = new PostData(TrackingService.this);
                    sender.post_data(jSONString, bContext);

                } else {
                    Toast.makeText(TrackingService.this,
                            "The device is not connected to the internet ",
                            Toast.LENGTH_SHORT).show();

                }

            }
        }


    } 



    private String convertToJSON(String mac, double pLong, double pLat,
            String time) {
        Data d = new Data(mac, pLat, pLong, time, route_number);
        Gson gson = new GsonBuilder().registerTypeAdapter(Data.class,
                new DataSerializer()).create();
        String a = gson.toJson(d);
        return a;
    }


    @Override
    public void onAsyncTaskFinished(ArrayList<Integer> routeList, double distance) {
        if (distance <= 15 && speed <= 4) {
            stop_popup(routeList);

        } else {
            route_number = routeList.get(0);
            System.out.println("The route number is: " + route_number);
        }

    }

}

PostData class:

public class PostData {
    String jSONString;
    private AsyncTaskCallback callback;


    public PostData(AsyncTaskCallback callback) {
        this.callback = callback;
    }

    public String getjSONString() {
        return jSONString;

    }

    public void setjSONString(String jSONString) {
        this.jSONString = jSONString;
    }

    public void post_data(String jSONString, Context context) {
        this.jSONString = jSONString;

        new MyAsyncTask(context).execute(jSONString);

    }

    class MyAsyncTask extends AsyncTask<String, Integer, ArrayList<Integer>> {
        final Context mContext;
        ArrayList<Integer> routes = new ArrayList<Integer>();
        double distance;

        public MyAsyncTask(Context context) {
            mContext = context;
        }

        @Override
        protected ArrayList<Integer> doInBackground(String... params) {
            // TODO Auto-generated method stub
            BufferedReader reader = null;

            try {
                System.out.println("The output of : doInBackground "
                        + params[0]);

                URL myUrl = new URL(
                        "https://bustrackerserver-test.rhcloud.com/webapi/test");

                HttpURLConnection conn = (HttpURLConnection) myUrl
                        .openConnection();
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
                conn.setRequestProperty("Content-Type", "application/json");
                conn.connect();

                DataOutputStream wr = new DataOutputStream(
                        conn.getOutputStream());
                wr.writeBytes(params[0]);

                wr.close();

                StringBuilder sb = new StringBuilder();
                reader = new BufferedReader(new InputStreamReader(
                        conn.getInputStream()));
                String line;

                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");

                }

                Gson gson = new Gson();
                StopsJSON data = gson.fromJson(sb.toString(), StopsJSON.class);

                routes = data.getRoutes();
                distance = data.getDistance();

            } catch (IOException e) {

                e.printStackTrace();
                return null;
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                        return null;
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }

            return null;

        }

        protected void onPostExecute(ArrayList<Integer> result) {

             if (routes != null && !routes.isEmpty()) {
            callback.onAsyncTaskFinished(routes, distance);
             }else{
                 Log.e("123", "Avoiding null pointer, the routes are null!!!");
             }
        }

    }

}

Some of the output when the app is running in the foreground:

05-28 00:04:02.825: I/System.out(1951): The output of : doInBackground {"mac":"10:A5:D0:06:C6:E9","latitude":53.8689686,"longitude":10.6655828,"route":0}
05-28 00:04:02.856: I/System.out(1951): (HTTPLog)-Static: isSBSettingEnabled false
05-28 00:04:03.026: I/System.out(1951): The output of the StringBulder: {"status":230,"routes":[9],"distance":296.0401842426428}
05-28 00:04:03.026: I/System.out(1951): The route number is: 9
05-28 00:04:12.795: I/System.out(1951): {"mac":"10:A5:D0:06:C6:E9","latitude":53.86892455,"longitude":10.66564527,"route":9}
05-28 00:04:12.835: I/System.out(1951): The output of : doInBackground {"mac":"10:A5:D0:06:C6:E9","latitude":53.86892455,"longitude":10.66564527,"route":9}
05-28 00:04:12.835: I/System.out(1951): (HTTPLog)-Static: isSBSettingEnabled false
05-28 00:04:13.096: I/System.out(1951): The output of the StringBulder: {"status":201}
05-28 00:04:13.096: E/123(1951): Avoiding null pointer, the routes are null!!!
05-28 00:04:23.796: I/System.out(1951): {"mac":"10:A5:D0:06:C6:E9","latitude":53.86882877,"longitude":10.66568087,"route":9}
05-28 00:04:23.806: I/System.out(1951): The output of : doInBackground {"mac":"10:A5:D0:06:C6:E9","latitude":53.86882877,"longitude":10.66568087,"route":9}
05-28 00:04:23.826: I/System.out(1951): (HTTPLog)-Static: isSBSettingEnabled false
05-28 00:04:23.896: I/System.out(1951): KnoxVpnUidStorageknoxVpnSupported API value returned is false
05-28 00:04:24.617: I/System.out(1951): The output of the StringBulder: {"status":201}
05-28 00:04:24.627: E/123(1951): Avoiding null pointer, the routes are null!!!
05-28 00:04:34.767: I/System.out(1951): {"mac":"10:A5:D0:06:C6:E9","latitude":53.86887302,"longitude":10.66568765,"route":9}
05-28 00:04:34.797: I/System.out(1951): The output of : doInBackground {"mac":"10:A5:D0:06:C6:E9","latitude":53.86887302,"longitude":10.66568765,"route":9}
05-28 00:04:34.797: I/System.out(1951): (HTTPLog)-Static: isSBSettingEnabled false
05-28 00:04:35.017: I/System.out(1951): The output of the StringBulder: {"status":201}

来源:https://stackoverflow.com/questions/30492323/get-the-new-variable-into-the-json-string-after-getting-the-new-value-from-the-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!