現在、Google Maps API v2 を使用する Android 用アプリを開発しています。外部 XML ファイルからカスタム マーカーを表示しています: http://dds.orgfree.com/DDS/landmarks_genxmlv2.php、マップ内のいくつかのランドマークを表示します。
以下のコードでわかるように、実際の電話でこのアプリをテストする際に StrictMode を使用して NetworkOnMainThreadException を回避しています。この方法を使用することはお勧めできません。これは、別のスレッドで、AsyncTask を介してバックグラウンドで実行する必要があります。このアプリに AsyncTask を実装しようとしましたが、うまくいきません。誰かが私のコードを提供するのを手伝ったり、これに役立つ良い提案をしたりできますか? よろしくお願いします。
public class MapViewActivity extends android.support.v4.app.FragmentActivity {
static final LatLng CITYHALL = new LatLng(07.0644444, 125.6077778);
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_mapview);
setUpMapIfNeeded();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mapview_options_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.normal_mapstyle) {
mMap.setMapType(MAP_TYPE_NORMAL);
} else if (item.getItemId() == R.id.hybrid_mapstyle) {
mMap.setMapType(MAP_TYPE_HYBRID);
} else if (item.getItemId() == R.id.satellite_mapstyle) {
mMap.setMapType(MAP_TYPE_SATELLITE);
} else if (item.getItemId() == R.id.terrain_mapstyle) {
mMap.setMapType(MAP_TYPE_TERRAIN);
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
Document doc = null;
try {
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
doc = builder
.parse("http://dds.orgfree.com/DDS/landmarks_genxmlv2.php");
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
NodeList markers = doc.getElementsByTagName("marker");
try {
for (int i = 0; i < markers.getLength(); i++) {
Element item = (Element) markers.item(i);
String name = item.getAttribute("name");
String address = item.getAttribute("address");
String stringLat = item.getAttribute("lat");
String stringLng = item.getAttribute("lng");
String icon = item.getAttribute("icon");
Double lat = Double.valueOf(stringLat);
Double lng = Double.valueOf(stringLng);
mMap = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
mMap.addMarker(new MarkerOptions()
.position(new LatLng(lat, lng))
.title(name)
.snippet(address)
.icon(BitmapDescriptorFactory.fromAsset(new String(icon
+ ".png"))));
// Move the camera instantly to City Hall with a zoom of 15.
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(CITYHALL, 15));
}
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
}
これが私が試したことです。
public class MapViewActivity extends android.support.v4.app.FragmentActivity {
static final LatLng CITYHALL = new LatLng(07.0644444, 125.6077778);
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_mapview);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
setUpMapIfNeeded();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mapview_options_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.map_menu_showlegend) {
Log.d("MENU", "Show Legend was CLICKED!");
} else if (item.getItemId() == R.id.map_menu_maptype) {
Log.d("MENU", "Map Type was CLICKED!");
} else if (item.getItemId() == R.id.normal_mapstyle) {
Log.d("MENU", "MAP_TYPE_NORMAL was CLICKED!");
mMap.setMapType(MAP_TYPE_NORMAL);
} else if (item.getItemId() == R.id.hybrid_mapstyle) {
Log.d("MENU", "MAP_TYPE_HYBRID was CLICKED!");
mMap.setMapType(MAP_TYPE_HYBRID);
} else if (item.getItemId() == R.id.satellite_mapstyle) {
Log.d("MENU", "MAP_TYPE_SATELLITE was CLICKED!");
mMap.setMapType(MAP_TYPE_SATELLITE);
} else if (item.getItemId() == R.id.terrain_mapstyle) {
Log.d("MENU", "MAP_TYPE_TERRAIN was CLICKED!");
mMap.setMapType(MAP_TYPE_TERRAIN);
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the
// map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
private Boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni != null && ni.isConnected())
return true;
return false;
}
private void setUpMap() {
new ParseXML().execute();
}
private class ParseXML extends AsyncTask<Void, Void, Document> {
Document doc = null;
@Override
protected Document doInBackground(Void... params) {
try {
Thread.sleep(2000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
if (isOnline()) {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
doc = builder
.parse("http://dds.orgfree.com/DDS/landmarks_genxmlv2.php");
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
NodeList markers = doc.getElementsByTagName("marker");
try {
for (int i = 0; i < markers.getLength(); i++) {
Element item = (Element) markers.item(i);
String name = item.getAttribute("name");
String address = item.getAttribute("address");
String stringLat = item.getAttribute("lat");
String stringLng = item.getAttribute("lng");
String icon = item.getAttribute("icon");
Double lat = Double.valueOf(stringLat);
Double lng = Double.valueOf(stringLng);
mMap = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
mMap.addMarker(new MarkerOptions()
.position(new LatLng(lat, lng))
.title(name)
.snippet(address)
.icon(BitmapDescriptorFactory
.fromAsset(new String(icon + ".png"))));
// Move the camera instantly to City Hall with a zoom of
// 15.
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
CITYHALL, 15));
}
} catch (NumberFormatException e) {
e.printStackTrace();
}
} else {
Toast.makeText(MapViewActivity.this, "No connection..",
Toast.LENGTH_LONG).show();
}
return doc;
}
@Override
protected void onPostExecute(Document doc) {
super.onPostExecute(doc);
}
}
}