onPostExecute无法正常启动活动

时间:2016-08-22 02:17:53

标签: android mysql android-asynctask mapbox

我正在使用AsyncTask在我的在线mySQL数据库中运行信息。然后我使用JSON解析将数据库中的信息作为标记添加到MapBox地图上。目前,当用户在代码中上传新标记(washroom)时,它会将信息上传到数据库,然后运行onPostExecute方法并返回MapsActivity.javaMapsActivity.java应该重新加载地图并显示新添加的标记,但它不会;它只显示添加新标记之前添加的标记。如果您关闭并打开应用程序,标记会更新,显示所有标记,包括新标记!任何帮助将不胜感激!

MapsActivity.java的一部分

public class MapsActivity extends FragmentActivity  {


private MapView mapView;
private MapboxMap map;
private ImageButton locationToggle;
private LocationServices locationServices;
private String json_string;
private JSONObject jsonObject;
private JSONArray jsonArray;

public static String WASHROOMINFO;

public static String CURRENT_LOCATION;

private static final int PERMISSIONS_LOCATION = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    MapboxAccountManager.start(this, getString(R.string.accessToken));
    setContentView(R.layout.activity_maps);


    //getting location services
    locationServices = com.mapbox.mapboxsdk.location.LocationServices.getLocationServices(MapsActivity.this);

    //onClick to go to add washroom activity
    findViewById(R.id.addWashroom).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            if (CURRENT_LOCATION != null) {

                Intent intent = new Intent(getBaseContext(), AddWashroom.class);
                startActivity(intent);

            } else {

                Toast.makeText(getBaseContext(),"You Must Turn on User Location Before Adding a Washroom!",Toast.LENGTH_LONG).show();

            }

        }
    });

    //washrooms have not been loaded in yet
    if (!BackgroundTask.WASHROOMS_LOADED) {
        //getting database info
        String method = "getWashroom";
        BackgroundTask backgroundTask = new BackgroundTask(getBaseContext());
        backgroundTask.execute(method);
        finish();

    }

    mapView = (MapView) findViewById(R.id.mapview);
    mapView.onCreate(savedInstanceState);
    mapView.getMapAsync(new OnMapReadyCallback() {
        @Override
        public void onMapReady(MapboxMap mapboxMap) {
            //when map is ready assign mapboxMap variable
            map = mapboxMap;

            //Washroom loading has been requested and JSON data is ready
            if (BackgroundTask.WASHROOMS_LOADED) {

                //Getting JSON data from intent
                json_string = getIntent().getExtras().getString("json_data");
                try {
                    //new JSON object from JSON data
                 jsonObject = new JSONObject(json_string);
                    //gets JSON array from JSON object
                    jsonArray = jsonObject.getJSONArray("server_response");

                    //Marker list for buffering markers
                    List<Marker> markers = new ArrayList<Marker>();

                    //do this for all markers!
                    for (int i = 0; i < jsonArray.length(); i++) {
                        //Single JSON object of single marker
                        JSONObject JO = jsonArray.getJSONObject(i);

                        //Dividing location field into lat & lng
                        String latlng = JO.getString("location");
                        String[] latlngSplit = latlng.split(" , ",2);
                        double lat = Double.valueOf(latlngSplit[0]);
                      double lng = Double.valueOf(latlngSplit[1]);


                        //adding marker
                        Marker marker = map.addMarker(new MarkerOptions()
                       .title(JO.getString("name"))
                               .setSnippet(JO.getString("price"))
                               .position(new LatLng(lat,lng))
                        );

                        //add marker to markers list.
                        markers.add(marker);

                    }

                    BackgroundTask.WASHROOMS_LOADED = false;

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

        }
    });

    locationToggle = (ImageButton) findViewById(R.id.location_toggle);
    locationToggle.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (map != null) {
                //toggle GPS when clicking show location button
                toggleGps(!map.isMyLocationEnabled());
            }
        }
    });

}

BackgroundTask(AsyncTask)

class BackgroundTask extends AsyncTask<String, Void, String> {
Context ctx;
public static boolean WASHROOMS_LOADED;
private String JSON_STRING;
private String json_string;

BackgroundTask(Context ctx) {
    this.ctx = ctx.getApplicationContext();


}

@Override
protected void onPreExecute() {
    super.onPreExecute();
}
String add_url = "http://appart-software.com/add_washroom.php";
String get_url = "http://appart-software.com/get_washroom.php";
@Override
protected String doInBackground(String... params) {
    String method = params[0];
    if (method.equals("addWashroom")) {

        String location = params[1];
        String name = params[2];
        String price = params[3];

        try {
            URL url = new URL(add_url);
            HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
            httpUrlConnection.setRequestMethod("POST");
            httpUrlConnection.setDoOutput(true);
            OutputStream outputStream = httpUrlConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
            String data_string = URLEncoder.encode("WClocation","UTF-8")+"="+URLEncoder.encode(location,"UTF-8")+"&"+
                    URLEncoder.encode("WCname","UTF-8")+"="+URLEncoder.encode(name,"UTF-8")+"&"+
                    URLEncoder.encode("WCprice","UTF-8")+"="+URLEncoder.encode(price,"UTF-8");
            bufferedWriter.write(data_string);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            InputStream inputStream = httpUrlConnection.getInputStream();
            inputStream.close();
            httpUrlConnection.disconnect();
            return "Washroom Added!";

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


        //You want to get washroom info
    } else if (method.equals("getWashroom")){

        try {

            URL url = new URL(get_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
            StringBuilder stringBuilder = new StringBuilder();
            while ((JSON_STRING = bufferedReader.readLine())!=null) {

                stringBuilder.append(JSON_STRING+"\n");
            }

            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            //Return JSON formatted info
            return stringBuilder.toString().trim();


        } catch (MalformedURLException e){
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    return null;
}

@Override
protected void onProgressUpdate(Void... values) {
    super.onProgressUpdate(values);
}

@Override
protected void onPostExecute(String result) {

    if (result.equals("Washroom Added!")) {

        Toast.makeText(ctx,result,Toast.LENGTH_LONG).show();

        WASHROOMS_LOADED = false;


    } else {

        //setting result as a movable string
        json_string = result;

        //intent and sending JSON data
        Intent intent = new Intent(ctx,MapsActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra("json_data",json_string);
        ctx.startActivity(intent);

        WASHROOMS_LOADED = true;


    }
}
}

如果您需要我的代码,我很乐意再展示一些代码。

1 个答案:

答案 0 :(得分:0)

您正在重新打开应用程序时获得新标记,因为您在onCreate()方法中获取的数据库信息仅在活动开始时触发。尝试在位置更改时尝试获取数据库信息或尝试覆盖onNewIntent方法。要覆盖onNewIntent首先将您的活动launchmode设置为清单中的singleTop