如何在android中每秒更新gps坐标?

时间:2015-04-22 12:08:44

标签: android gps

我是Android开发的新手,这是我的第一个应用程序。我的应用是使用其他应用程序跟踪一部手机。我现在设法做第一个发送gps坐标的应用程序。现在我正在做第二个应用程序,到目前为止应用程序可以从mysql服务器检索GPS坐标并在谷歌地图上显示它。问题是我的mysql数据库每秒都会更新,我在应用程序中刷新gps坐标时遇到问题。我尝试使用

 new Handler().postDelayed(new Runnable() {
        public void run() {
            // call JSON methods here
            new JsonReadTask ().execute();
        }
    }, 60000  );

调用我的异步任务,但应用程序崩溃并显示错误消息

E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #2
Process

我一直在寻找,因为我对android缺乏了解,我发现很难改变并实施解决方案来解决我的问题。谁能帮帮我吗。

我的活动代码

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.widget.Toast;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


public class MyActivity extends FragmentActivity {



private String jsonResult;
private String url = "http://address.com/recieve1.php";




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

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(params[0]);
        try {
            HttpResponse response = httpclient.execute(httppost);
            jsonResult = inputStreamToString(
                    response.getEntity().getContent()).toString();
        }

        catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private StringBuilder inputStreamToString(InputStream is) {
        String rLine = "";
        StringBuilder answer = new StringBuilder();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));

        try {
            while ((rLine = rd.readLine()) != null) {
                answer.append(rLine);
            }
        }

        catch (IOException e) {
            // e.printStackTrace();
            Toast.makeText(getApplicationContext(),
                    "Error..." + e.toString(), Toast.LENGTH_LONG).show();
        }
        return answer;
    }

    @Override
    protected void onPostExecute(String result) {
        jsonvalue();
    }
}// end async task

public void accessWebService() {
    JsonReadTask task = new JsonReadTask();
    // passes values for the urls string array
    task.execute(new String[] { url });
}



public void jsonvalue() {
    List<Map<String, String>> employeeList = new ArrayList<Map<String, String>>();


    try {
        JSONObject jsonResponse = new JSONObject(jsonResult);
        JSONArray jsonMainNode = jsonResponse.optJSONArray("my_coor");
        for (int i = 0; i < jsonMainNode.length(); i++) {
            JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
            String latitude = jsonChildNode.optString("latitude");
            String longitude = jsonChildNode.optString("longitude");
            String coordinates[] = {latitude, longitude};
            double lat = Double.parseDouble(coordinates[0]);
            double lng = Double.parseDouble(coordinates[1]);

            // Getting reference to SupportMapFragment
            SupportMapFragment fragment = (SupportMapFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.map);

            // Creating GoogleMap from SupportMapFragment
            mapView = fragment.getMap();

            LatLng location;
            location = new LatLng(lat, lng);

            mapView.addMarker(new MarkerOptions().position(location));
            mapView.moveCamera(CameraUpdateFactory.newLatLng(location));
            mapView.animateCamera(CameraUpdateFactory.zoomTo(15));
        }
    } catch (JSONException e) {
        Toast.makeText(getApplicationContext(), "Error" + e.toString(),
                Toast.LENGTH_SHORT).show();

    }






    }

完整的错误日志

04-22 20:50:25.236  11023-11023/com.unmcbus.unmcbustracker E/Zygote﹕     MountEmulatedStorage()
04-22 20:50:25.236  11023-11023/com.unmcbus.unmcbustracker E/Zygote﹕ v2
04-22 20:50:25.236  11023-11023/com.unmcbus.unmcbustracker E/SELinux﹕ [DEBUG]   get_category: variable seinfo: default sensitivity: NULL, cateogry: NULL
04-22 20:51:34.331  11023-12546/com.unmcbus.unmcbustracker E/AndroidRuntime﹕   FATAL EXCEPTION: AsyncTask #2
Process: com.unmcbus.unmcbustracker, PID: 11023
java.lang.RuntimeException: An error occured while executing   doInBackground()
        at android.os.AsyncTask$3.done(AsyncTask.java:300)
        at   java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
        at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
        at java.util.concurrent.FutureTask.run(FutureTask.java:242)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
        at   java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
        at java.lang.Thread.run(Thread.java:818)
 Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
        at   com.unmcbus.unmcbustracker.UNMCtoTTSActivity$JsonReadTask.doInBackground(UNMCtoT     TSActivity.java:66)
        at com.unmcbus.unmcbustracker.UNMCtoTTSActivity$JsonReadTask.doInBackground(UNMCtoTTSActivity.java:61)
        at android.os.AsyncTask$2.call(AsyncTask.java:288)
        at java.util.concurrent.FutureTask.run(FutureTask.java:237)

2 个答案:

答案 0 :(得分:0)

请发布完整的错误日志,以便清楚了解错误。

但是我能在您的代码中找到问题 - &GT;您无法从后台线程(doInBackground()方法)

执行任何UI操作

答案 1 :(得分:0)

我相信你在doInBackground中执行任务的方式是空的,因为你没有传递一个URL。

我可以看到,这应该通过URL:

 new Handler().postDelayed(new Runnable() {
    public void run() {
        // call JSON methods here
        accessWebService();
    }
}, 60000  );