Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/google-maps/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android AsyncTask偶尔工作_Android_Google Maps_Android Asynctask - Fatal编程技术网

Android AsyncTask偶尔工作

Android AsyncTask偶尔工作,android,google-maps,android-asynctask,Android,Google Maps,Android Asynctask,我有地图功能,可以在我的应用程序上显示谷歌地图。 我有一个文本文件,其中有街道名称、邮政编码和城市名称。我使用BufferedReader读取此文本文件。我的文本文件中有近100条街道。因此,我以编程方式在GoogleMap中添加了近100个标记。这需要时间,这取决于互联网连接 因此,我决定使用AsyncTask。因为我知道,UI不能在doInBackground中完成,所以我将我的readfile()方法(它添加了这100个标记)作为一个可运行的线程放在doInBackground中。我不希望

我有地图功能,可以在我的应用程序上显示谷歌地图。 我有一个文本文件,其中有街道名称、邮政编码和城市名称。我使用BufferedReader读取此文本文件。我的文本文件中有近100条街道。因此,我以编程方式在GoogleMap中添加了近100个标记。这需要时间,这取决于互联网连接

因此,我决定使用AsyncTask。因为我知道,UI不能在
doInBackground
中完成,所以我将我的
readfile()
方法(它添加了这100个标记)作为一个可运行的线程放在
doInBackground
中。我不希望用户看到一个空白屏幕,因此我添加了一个进度条

问题就在这里:Progressbar并不总是工作,它不总是可以看到,偶尔可以看到,这让我认为我的Asycntask有问题。也许我称之为异步任务的方式不好。请看一下我的代码

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
String city, adress, zip;
LatLngBounds.Builder builder = new LatLngBounds.Builder();


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


    setContentView(R.layout.activity_maps);

    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(map);
    mapFragment.getMapAsync(this);


}


@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    new Test().execute(null,null,null); //calling AsyncTask

}


public void readFile() {

    Geocoder coder = new Geocoder(MapsActivity.this, Locale.getDefault());
    List<Address> address;
    LatLng p2;

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(getAssets().open("liste.txt")));
        String line;

        while ((line = reader.readLine()) != null) {

            String splittedLine[] = line.split(",");
            int numberofElements = 2;
            String[] onlyAdressandZip = Arrays.copyOf(splittedLine, numberofElements);

            if ( address.size() !=0) {

                Address location = address.get(0);
                location.getLatitude();
                location.getLongitude();

                p2 = new LatLng(location.getLatitude(), location.getLongitude());

                mMap.addMarker(new MarkerOptions().position(p2).title("Location " + onlyAdressandZip[0]+"," + onlyAdressandZip[1]));
                builder.include(p2);

                LatLngBounds bounds = builder.build();
                mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 20));

            }

              }

    } catch (IOException ex) {
        ex.printStackTrace();
    }

}


public class Test extends AsyncTask<Void, Void, Void>{
    ProgressDialog dialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // what to do before background task
        dialog = new ProgressDialog(MapsActivity.this);
        dialog.setTitle("Loading...");
        dialog.setMessage("Please wait.");
        dialog.setIndeterminate(true);
        dialog.setCancelable(false);
        dialog.show();
    }



    @Override
    protected Void doInBackground(Void... params) {
        runOnUiThread(new Runnable() {
            public void run() {

                readFile();

            }
        });
        return null;
    }

    @Override
    protected void onPostExecute(Void foo) {
    super.onPostExecute(foo);
    dialog.cancel();

    }
}
}
公共类MapsActivity扩展了FragmentActivity在MapreadyCallback上的实现{
私有谷歌地图;
字符串城市,地址,邮编;
LatLngBounds.Builder=新的LatLngBounds.Builder();
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_映射);
//获取SupportMapFragment,并在地图准备好使用时收到通知。
SupportMapFragment mapFragment=(SupportMapFragment)getSupportFragmentManager()
.findFragmentById(地图);
getMapAsync(这个);
}
@凌驾
4月1日公开作废(谷歌地图谷歌地图){
mMap=谷歌地图;
new Test().execute(null,null,null);//调用AsyncTask
}
公共void readFile(){
Geocoder coder=新的Geocoder(MapsActivity.this,Locale.getDefault());
名单地址;
板条p2;
试一试{
BufferedReader=新的BufferedReader(新的InputStreamReader(getAssets().open(“liste.txt”));
弦线;
而((line=reader.readLine())!=null){
String splittedLine[]=line.split(“,”);
int numberofElements=2;
字符串[]onlyAddressAndZip=Arrays.copyOf(splittedLine,numberofElements);
如果(address.size()!=0){
地址位置=地址。获取(0);
location.getLatitude();
location.getLongitude();
p2=新车床(location.getLatitude(),location.getLongitude());
mMap.addMarker(新的MarkerOptions().position(p2).title(“Location”+onlyAddressAndZip[0]+”,“+onlyAddressAndZip[1]);
建筑商。包括(p2);
LatLngBounds bounds=builder.build();
mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds,20));
}
}
}捕获(IOEX异常){
例如printStackTrace();
}
}
公共类测试扩展了异步任务{
进程对话;
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
//背景任务之前要做什么
dialog=新建ProgressDialog(MapsActivity.this);
对话框.setTitle(“加载…”);
setMessage(“请稍候”);
对话框。setUndeterminate(true);
对话框。可设置可取消(false);
dialog.show();
}
@凌驾
受保护的Void doInBackground(Void…参数){
runOnUiThread(新的Runnable(){
公开募捐{
readFile();
}
});
返回null;
}
@凌驾
受保护的void onPostExecute(void foo){
super.onPostExecute(foo);
dialog.cancel();
}
}
}

因此,正如我在评论中所说,在本例中,基本上我重新编写了异步任务,以便在后台运行文件读取,并在uithread中更新映射的进度。代码远非最终版本,但您应该对其进行测试和改进

因为AsyncTask为您提供了更新UIThread的工具,所以您不应该在其中使用
runOnUiThread()

报告说:

AsyncTask允许正确且轻松地使用UI线程。这个班 允许您在上执行后台操作和发布结果 UI线程,而无需操作线程和/或处理程序

示例:

public class Test extends AsyncTask<Void, WrapperObject, Void> {
    ProgressDialog dialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // what to do before background task
        dialog = new ProgressDialog(MapsActivity.this);
        dialog.setTitle("Loading...");
        dialog.setMessage("Please wait.");
        dialog.setIndeterminate(true);
        dialog.setCancelable(false);
        dialog.show();
    }


    @Override
    protected Void doInBackground(Void... params) {

        Geocoder coder = new Geocoder(MapsActivity.this, Locale.getDefault());
        List<Address> address;
        LatLng p2;

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(getAssets().open("liste.txt")));
            String line;

            while ((line = reader.readLine()) != null) {

                String splittedLine[] = line.split(",");
                int numberofElements = 2;
                String[] onlyAdressandZip = Arrays.copyOf(splittedLine, numberofElements);

                if (address.size() != 0) {

                    Address location = address.get(0);
                    location.getLatitude();
                    location.getLongitude();

                    p2 = new LatLng(location.getLatitude(), location.getLongitude());
                    builder.include(p2);

                    WrapperObject wrapperObject = new WrapperObject();
                    wrapperObject.bounds = builder.build();
                    wrapperObject.latlng = p2;
                    wrapperObject.onlyAdressandZip = onlyAdressandZip;
                    publishProgress(wrapperObject);
                }

            }

        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return null;
    }

    protected void onProgressUpdate(WrapperObject... wrapperObjects) {
        WrapperObject wrapperObject = wrapperObjects[0];
        mMap.addMarker(new MarkerOptions().position(wrapperObject.latlng).title("Location " + wrapperObject.onlyAdressandZip[0]+"," + wrapperObject.onlyAdressandZip[1]));
        mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(wrapperObject.bounds, 20));
    }

    @Override
    protected void onPostExecute(Void foo) {
        super.onPostExecute(foo);
        dialog.cancel();
    }
}
//this is a wrapper to update the progress, you should make this better.    
public static class WrapperObject {
    public LatLng latlng;
    public LatLngBounds bounds;
    public String[] onlyAdressandZip;
}
公共类测试扩展了异步任务{
进程对话;
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
//背景任务之前要做什么
dialog=新建ProgressDialog(MapsActivity.this);
对话框.setTitle(“加载…”);
setMessage(“请稍候”);
对话框。setUndeterminate(true);
对话框。可设置可取消(false);
dialog.show();
}
@凌驾
受保护的Void doInBackground(Void…参数){
Geocoder coder=新的Geocoder(MapsActivity.this,Locale.getDefault());
名单地址;
板条p2;
试一试{
BufferedReader=新的BufferedReader(新的InputStreamReader(getAssets().open(“liste.txt”));
弦线;
而((line=reader.readLine())!=null){
String splittedLine[]=line.split(“,”);
int numberofElements=2;
字符串[]onlyAddressAndZip=Arrays.copyOf(splittedLine,numberofElements);
如果(address.size()!=0){
地址位置=地址。获取(0);
location.getLatitude();
location.getLongitude();
p2=新车床(location.getLatitude(),location.getLongitude());
建筑商。包括(p2);
WrapperObject WrapperObject=新的WrapperObject();
wrapperObject.bounds=builder.build();
wrapperObject.latlng=p2;
wrapperObject.onlyAddressAndZip=onlyAddressAndZip;
publishProgress(包装对象);
}
}