0
我正在開發一個應用程序,使用AsyncTask繪製標記。我試圖在onPostExeution()上標記當前位置的標記,並將我的相機移動到當前位置。我嘗試了很多方法來實現這一點,但不幸的是應用程序崩潰。所以,您可以引導我在當前位置繪製標記並移動我的一旦我在onPostExecute()中收到位置更新,相機就會到達那個位置。在異步任務onPostExecution後在當前位置繪製標記
這裏是我的代碼 -
MainActivity.java
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener,OnMapReadyCallback {
SupportMapFragment sMapFragment;
public GoogleMap mMap;
private HttpURLConnection urlConnection = null;
private BufferedReader reader = null;
private String forecastJsonStr = null;
private String url = "my_url";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
sMapFragment = SupportMapFragment.newInstance();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
sMapFragment.getMapAsync(this);
android.support.v4.app.FragmentManager sFM = getSupportFragmentManager();
sFM.beginTransaction().add(R.id.Map, sMapFragment).commit();
}
//Search option
public void onMapSearch(View view) throws IOException {
//hide button when button is pressed
InputMethodManager inputManager = (InputMethodManager) getSystemService(this.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
//preview the entered address as an Tost in bar
EditText locationSearch = (EditText) findViewById(R.id.editText);
String location = locationSearch.getText().toString();
//this will animate camera and zoom 12.0f
mMap.animateCamera(CameraUpdateFactory.zoomTo(12.0f));
//further address search codes
List<Address> addressList = null;
//if nothing will be entered in the edit-text will not show a toast rather than crashing of thekha app
if (locationSearch.getText().toString().equals("")) {
Toast.makeText(this, "Please enter an Address", Toast.LENGTH_LONG).show();
} else {
//process of exception handling and finding location
if (location != null || !location.equals("")) {
Geocoder geocoder = new Geocoder(this);
try {
addressList = geocoder.getFromLocationName(location, 1);
} catch (IOException e) {
e.printStackTrace();
}
//if address is greater than one then these processes will happen
if (addressList.size() > 0) {
Address address = addressList.get(0);
LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
mMap.addMarker(new MarkerOptions()
.position(latLng)
.title(location + " is Here ")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
Toast.makeText(this, location + " is here, Zoom In or Zoom Out to make your Thekha Visible ", Toast.LENGTH_LONG)
.show(); //popup type to show entered data
} else {
//process where entered entry will not gonna find , this will gonna a toast to show popup
Toast.makeText(this, "Entered Address Not Found", Toast.LENGTH_LONG).show();
}
}
}
}
//Async task
ProgressDialog pd = null;
private class RetriveMarkerTask extends AsyncTask<String, Void, String> {
private Context context;
public RetriveMarkerTask(Context context) {
this.context = context;
}
@Override
protected void onPreExecute() {
pd = new ProgressDialog(MainActivity.this);
pd.setTitle("Please wait ...");
pd.setMessage("Connecting to Loofre Network");
pd.setCancelable(false);
pd.show();
}
protected String doInBackground(String... markerGetUrl) {
try {
// Construct the URL for the OpenWeatherMap query
// Possible parameters are avaiable at OWM's forecast API page, at
// http://openweathermap.org/API#forecast
URL url1 = new URL(url);
// Create the request to OpenWeatherMap, and open the connection
urlConnection = (HttpURLConnection) url1.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
forecastJsonStr = buffer.toString();
} catch (IOException e) {
Log.e("PlaceholderFragment", "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
forecastJsonStr = "Error, an exception was raised.";
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("PlaceholderFragment", "Error closing stream", e);
}
}
}
return forecastJsonStr;
}
//on post execution
protected void onPostExecute(String markers) {
Log.d("string response", markers);
Toast.makeText(MainActivity.this, "Plotting Thekha", Toast.LENGTH_LONG).show();
try {
JSONArray jsonArray = new JSONArray(markers);
for (int i = 0; i < jsonArray.length(); i++) {
//create marker of each place in the json data
JSONObject jsonObject = jsonArray.getJSONObject(i);
String placeName = jsonObject.getString("name");
String placeAddress = jsonObject.getString("address");
double latitude = jsonObject.getJSONArray("latlang").getDouble(0);
double longitude = jsonObject.getJSONArray("latlang").getDouble(1);
LatLng loc = new LatLng(latitude, longitude);
//marker size change code
int height = 150;
int width = 150;
BitmapDrawable bitmapDrawable = (BitmapDrawable) getResources().getDrawable(R.drawable.thekhaicon);
Bitmap b = bitmapDrawable.getBitmap();
Bitmap smallMarker = Bitmap.createScaledBitmap(b, width, height, false);
//marker size change code ends here
//mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(loc, 13));
mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromBitmap(smallMarker))
.title(placeName)
.snippet(placeAddress)
.position(loc)
);
LatLng dwarka = new LatLng(28.570317, 77.32182);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(dwarka, 13));
mMap.addMarker(
new MarkerOptions()
.title("Wine Beer Liquor Shop, Sector 18, Noida")
.snippet("Sector 18, Near Centre Stage Mall, Noida")
.position(dwarka));
}
pd.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@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;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.call_us) {
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:+919717001947"));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return true;
}
startActivity(intent);
} else if (id == R.id.about_us) {
Intent intent = new Intent(this,ScrollingActivity.class);
this.startActivity(intent);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
@Override
public void onMapReady(GoogleMap googleMap) {
Toast.makeText(this, "Connecting Server", Toast.LENGTH_LONG).show();
mMap = googleMap;
try {
RetriveMarkerTask markerTask = new RetriveMarkerTask(MainActivity.this);
markerTask.execute(url);
}catch (Exception e){
Toast.makeText(this,"Can not fetch data",Toast.LENGTH_LONG).show();
}
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission
(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
}
//tool bar and other tool related on map uiSettings
// mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setMapToolbarEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
}
我manifest.xml文件 -
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSWEVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:name="android.support.multidex.MultiDexApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="Thekha"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar"></activity>
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="AIzaSyAma5WZ9H5yskkt3AsQwc3aeQOFCyc9aGo" />
<activity android:name=".LoginActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".ScrollingActivity"
android:label="@string/title_activity_scrolling"
android:theme="@style/AppTheme.NoActionBar"></activity>
</application>