MapsActivity 标记将不会第二次显示

问题描述 投票:0回答:1

我的应用程序中有一个 MapsActivity,它通过单击 MainActivity 中的按钮启动,当活动开始时,我将通过 JSON 获取标记坐标并在 MapsActivity 中显示它们,但这只会在第一次发生,一旦我按下返回并转到MainActivity 并再次按下按钮 MapsActivity 启动,但标记不会显示在其中。我试图结束或破坏活动,但这没有帮助。 任何帮助将不胜感激

这是我的 MapsActivity 代码:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
check_activity = 1;
backgroundTask2 = new BackgroundTask2(textView);
backgroundTask2.execute();
ma_fin = this;
MainActivity.maps_adv = 1;
if (flag == 1) {
  map_update();
  maps_adv = 0;
}
getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
checkLocationPermission();
setUpMapIfNeeded();
map_update();
mGoogleApiClient = new GoogleApiClient.Builder(this)
  .addConnectionCallbacks(this)
  .addOnConnectionFailedListener(this)
  .addApi(LocationServices.API)
  .build();

// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
  .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
  .setInterval(10 * 1000)        // 10 seconds, in milliseconds
  .setFastestInterval(1 * 1000); // 1 second, in milliseconds

  }
  @Override
  protected void onResume() {
    super.onResume();
    setUpMapIfNeeded();
    mGoogleApiClient.connect();
  }
  @Override
  protected void onPause() {
    super.onPause();

if (mGoogleApiClient.isConnected()) {
  LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, 
this);
  mGoogleApiClient.disconnect();
    }
  }
  }

  private void setUpMap() {
    mMap.addMarker(new MarkerOptions().position(new LatLng(0,         
0)).title("Marker"));
  }

  private void handleNewLocation(Location location) {
Log.d(TAG, location.toString());

double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();

LatLng latLng = new LatLng(currentLatitude, currentLongitude);

MarkerOptions options = new MarkerOptions()
  .position(latLng)
  .title("Your Location");
mMap.addMarker(options);
float zoomLevel = 13.0f; //This goes up to 21
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoomLevel));
  }
  @Override
  public void onConnected(Bundle bundle) {
    if (ActivityCompat.checkSelfPermission(this, 
Manifest.permission.ACCESS_FINE_LOCATION) != 
PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 
Manifest.permission.ACCESS_COARSE_LOCATION) != 
PackageManager.PERMISSION_GRANTED) {
      return;
    }
Location location =     LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

if (location == null) {
  LocationServices.FusedLocationApi.requestLocationUpdates(
    mGoogleApiClient, mLocationRequest, this);
} else {
  handleNewLocation(location);
}
  }
  @Override
  public void onConnectionSuspended(int i) {
  }
  @Override
 public void onConnectionFailed(ConnectionResult connectionResult) {
    /*
     * Google Play services can resolve some errors it detects.
     * If the error has a resolution, try sending an Intent to
     * start a Google Play services activity that can resolve
     * error.
     */
if (connectionResult.hasResolution()) {
  try {
    // Start an Activity that tries to resolve the error
    connectionResult.startResolutionForResult(
      this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
            /*
             * Thrown if Google Play services canceled the original
             * PendingIntent
             */
  } catch (IntentSender.SendIntentException e) {
    // Log the error
    e.printStackTrace();
  }
} else {
        /*
         * If no resolution is available, display a dialog to the
         * user with the error.
         */
  Log.i(TAG, "Location services connection failed with code " +
    connectionResult.getErrorCode());
}
  }


  @Override
  public void onLocationChanged(Location location) {
 handleNewLocation(location);
  }

  public static final int MY_PERMISSIONS_REQUEST_LOCATION = 1;

  public boolean checkLocationPermission() {
    if (ContextCompat.checkSelfPermission(this,
      android.Manifest.permission.ACCESS_COARSE_LOCATION)
      != PackageManager.PERMISSION_GRANTED) {
      if (ActivityCompat.shouldShowRequestPermissionRationale(this,
        android.Manifest.permission.ACCESS_COARSE_LOCATION)) {
        requestPermissions(new String[]{
        android.Manifest.permission.ACCESS_COARSE_LOCATION
      },
      MY_PERMISSIONS_REQUEST_LOCATION);
  } else {
    requestPermissions(new String[]{
        android.Manifest.permission.ACCESS_COARSE_LOCATION
      },
      MY_PERMISSIONS_REQUEST_LOCATION);
  }
  return false;
} else {
  return true;
}
  }

@Override
  public void onMapReady(GoogleMap googleMap) {
    try {
      final ArrayList myList;
      if (checker==0) {
       myList = (ArrayList<Object>) getIntent().getSerializableExtra("maps");
      }
      else
      {
        checker = 0;
        myList = maps;
      }
      mMap = googleMap;
      mMap.clear();
  for (int i = 0; i < myList.size(); i++) {
    LatLng sydney = new LatLng(((Double) (((ArrayList) myList.get(i))).get(2)).doubleValue(), ((Double) (((ArrayList) myList.get(i))).get(3)).doubleValue());
    mMap.addMarker(new MarkerOptions().position(sydney).title((String) (((ArrayList) myList.get(i))).get(1)).icon(BitmapDescriptorFactory.fromResource(R.drawable.location_icon)));
  }

  mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
    @Override
    public boolean onMarkerClick(Marker marker) {


      String position = "0";
      String title = marker.getTitle();
      for (int i = 0; i < myList.size(); i++) {
        if (title.equals(((ArrayList) myList.get(i)).get(1).toString())) {
          position = ((ArrayList) myList.get(i)).get(0).toString();
          titlename = ((ArrayList) myList.get(i)).get(1).toString();
          address = ((ArrayList) myList.get(i)).get(4).toString();
        }
      }
      foo = Integer.valueOf(position);
      a = ((ArrayList) myList.get(foo)).get(0).toString();
      backgroundTask = new BackgroundTask(textView);
      backgroundTask.execute();
        map_check = 1;
        MainActivity.maps_adv = 0;
      return true;
    }
  });
} catch (RuntimeException e) {
  e.printStackTrace();
}
    }
  private class BackgroundTask extends AsyncTask<Void, Void, String> {
    private final WeakReference<TextView> messageViewReference;

private BackgroundTask(TextView textView) {
  this.messageViewReference = new WeakReference<>(textView);
}
@Override
protected String doInBackground(Void... voids) {
  HttpClient httpclient = new DefaultHttpClient();
  HttpPost httppost = new HttpPost(MainActivity.url);
  try {
    jsonobj = new JSONObject();
    jsonobj.put("hotel_id_post", foo);
    Log.i("EEE", a);
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("req", jsonobj.toString()));
    nameValuePairs.add(new BasicNameValuePair("func", "2"));
    nameValuePairs.add(new BasicNameValuePair("adv", MainActivity.features.toString()));
    nameValuePairs.add(new BasicNameValuePair("adv_cont", ("" + features_count).toString()));
    nameValuePairs.add(new BasicNameValuePair("date", MainActivity.current_date));
    nameValuePairs.add(new BasicNameValuePair("during", "1"));
    Log.e("mainToPost", "mainToPost" + nameValuePairs.toString());
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    HttpResponse response = httpclient.execute(httppost);
    InputStream inputStream = response.getEntity().getContent();
    InputStreamToStringExample str = new InputStreamToStringExample();
    responseServerhotel = str.getStringFromInputStream(inputStream);
    Log.e("responseqqqqqqq", "response -----" + responseServerhotel);
    HotelList.jsonroom = new JSONObject(responseServerhotel);
  } catch (Exception e) {
    e.printStackTrace();
  }
  return null;
}
@Override
protected void onPostExecute(String s) {
  super.onPostExecute(s);
  TextView textView = messageViewReference.get();
  if (textView != null) {
    textView.setText(s);
  }
  if (responseServerhotel.equals("{\"types\":null}"))
  {
    MainActivity.nothing = "no room to show";
    Intent intent = new Intent(MapsActivity.this,Nothing.class);
    startActivity(intent);
  }
  else
  {
    Intent intent = new Intent(MapsActivity.this, RoomList.class);
    startActivity(intent);
  }
    }
  }
  private class BackgroundTask1 extends AsyncTask<Void, Void, String> {

private final WeakReference<TextView> messageViewReference;

private BackgroundTask1(TextView textView) {
  this.messageViewReference = new WeakReference<>(textView);
}
@Override
protected String doInBackground(Void... voids) {
  HttpClient httpclient = new DefaultHttpClient();
  HttpPost httppost = new HttpPost(MainActivity.url);
  try {
    //mMap.clear();
    jsonadv = new JSONObject();
    jsonadv_cont = new JSONObject();
    jsonobj = new JSONObject();
    jsonads = new JSONObject();
    MainActivity.features = "";
    features_count = 0;
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("func", "11"));
    nameValuePairs.add(new BasicNameValuePair("adv", 
    MainActivity.features.toString()));
    nameValuePairs.add(new BasicNameValuePair("adv_cont", ("" + 
    features_count).toString()));
    nameValuePairs.add(new BasicNameValuePair("date", 
    MainActivity.current_date));
    nameValuePairs.add(new BasicNameValuePair("during", num));
    Log.e("mainToPost", "mainToPost" + nameValuePairs.toString());
    // Use UrlEncodedFormEntity to send in proper format which we need
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    // Execute HTTP Post Request
    HttpResponse response = httpclient.execute(httppost);
    InputStream inputStream = response.getEntity().getContent();
    InputStreamToStringExample str = new InputStreamToStringExample();
    responseServer = str.getStringFromInputStream(inputStream);
    Log.e("response", "response -----" + responseServer);
    jsonmap = new JSONObject(responseServer);
  } catch (Exception e) {
    e.printStackTrace();
  }
  return null;
}
@Override
protected void onPostExecute(String s) {
  super.onPostExecute(s);
  TextView textView = messageViewReference.get();
  if (textView != null) {
    textView.setText(s);
  }
  backgroundTask2 = new BackgroundTask2(textView);
  backgroundTask2.execute();
}
  }
  @Override
  protected void onDestroy() {
    super.onDestroy();
    if (backgroundTask != null) {
      backgroundTask.cancel(true);
    }
    if (backgroundTask1 != null) {
      backgroundTask1.cancel(true);
    }
    if (backgroundTask2 != null) {
      backgroundTask2.cancel(true);
    }
    finish();
  }
  private class BackgroundTask2 extends AsyncTask<Void, Void, String> {

private final WeakReference<TextView> messageViewReference;

private BackgroundTask2(TextView textView) {
  this.messageViewReference = new WeakReference<>(textView);
}
@Override
protected String doInBackground(Void... voids) {
  HttpHandler sh = new HttpHandler();
  // Making a request to url and getting response
  String jsonStr = sh.makeServiceCall(MainActivity.url);
  Log.e(TAG, "Response from url: " + jsonStr);
  if (jsonStr != null) {
    try {
      JSONArray mapsarr = jsonmap.getJSONArray("maps");
      for (int i = 0; i < mapsarr.length(); i++) {
        ArrayList<Object> mapping = new ArrayList<>();
        JSONObject c = mapsarr.getJSONObject(i);
        String id = c.getString("hotel_id");
        String name = c.getString("hotel_name");
        Double x = c.getDouble("hotel_x");
        Double y = c.getDouble("hotel_y");
        String address = c.getString("hotel_address");
        mapping.add(0, id);
        mapping.add(1, name);
        mapping.add(2, x);
        mapping.add(3, y);
        mapping.add(4, address);
        maps.add(i, mapping);
      }
      Log.i("MAPTEST", mapsarr.toString());
    } catch (final JSONException e) {
      Log.e(TAG, "Json parsing error: " + e.getMessage());
      runOnUiThread(new Runnable() {
        @Override
        public void run() {
        }
      });
    }
  } else {
    Log.e(TAG, "Couldn't get json from server.");
    runOnUiThread(new Runnable() {
      @Override
      public void run() {
      }
    });
  }
  return null;
}
@Override
protected void onPostExecute(String s) {
  super.onPostExecute(s);
  final TextView textView = messageViewReference.get();
  if (textView != null) {
    textView.setText(s);
  }
  onMapReady(mMap);
  checker = 1;
}
  }
  public static class InputStreamToStringExample {

public static void main(String[] args) throws IOException {

  // intilize an InputStream
  InputStream is =
    new ByteArrayInputStream("file content..blah blah".getBytes());

  String result = getStringFromInputStream(is);

  System.out.println(result);
  System.out.println("Done");

}
// convert InputStream to String
private static String getStringFromInputStream(InputStream is) {

  BufferedReader br = null;
  StringBuilder sb = new StringBuilder();

  String line;
  try {

    br = new BufferedReader(new InputStreamReader(is));
    while ((line = br.readLine()) != null) {
      sb.append(line);
    }

  } catch (IOException e) {
    e.printStackTrace();
  } finally {
    if (br != null) {
      try {
        br.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
  return sb.toString();
}
      }
  }
  public void map_update() {
maps.clear();
backgroundTask1 = new BackgroundTask1(textView);
backgroundTask1.execute();
  }
  public static void refresh()
  {
   flag = 0;
   MapsActivity ma = new MapsActivity();
   ma.map_update();
  }
android google-maps android-activity google-maps-markers
1个回答
0
投票

我面临同样的问题(我退出应用程序并重新打开标记仍然不会显示),你是如何解决的?

© www.soinside.com 2019 - 2024. All rights reserved.