Java 初始化谷歌地图后重新绘制视图中的片段-Android
我想在我的个人资料视图的半屏幕上显示谷歌地图。在我的Java 初始化谷歌地图后重新绘制视图中的片段-Android,java,android,google-maps,android-fragments,Java,Android,Google Maps,Android Fragments,我想在我的个人资料视图的半屏幕上显示谷歌地图。在我的onCreate方法中,我创建了一个AsyncTask的新实例,通过JSON从Google服务器检索纬度和经度。收到结果后,我呼叫: GoogMapHandler gmh = new GoogMapHandler(fragmentManager, applicationContext); gmh.initilizeMap(coord, "Username", "addressInfo"); 这是我的GoogMapHandler课程: impo
onCreate
方法中,我创建了一个AsyncTask
的新实例,通过JSON从Google服务器检索纬度和经度。收到结果后,我呼叫:
GoogMapHandler gmh = new GoogMapHandler(fragmentManager, applicationContext);
gmh.initilizeMap(coord, "Username", "addressInfo");
这是我的GoogMapHandler
课程:
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.content.Context;
import android.widget.Toast;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import com.google.android.gms.internal.fm;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class GoogMapHandler {
// Google Map
private GoogleMap googleMap;
private android.support.v4.app.FragmentManager fragmentManager;
private Context applicationContext;
public GoogMapHandler(FragmentManager fmanager, Context applicationContext) {
this.fragmentManager = fmanager;
this.applicationContext = applicationContext;
}
public void initilizeMap(LatLng coord, String username, String addrInfo) {
if (googleMap == null) {
Fragment fragment = this.fragmentManager.findFragmentById(R.id.map);
FragmentTransaction fragTransaction = this.fragmentManager
.beginTransaction();
fragTransaction.detach(fragment);
SupportMapFragment supportmapfragment = (SupportMapFragment) fragment;
googleMap = supportmapfragment.getMap();
if (googleMap == null) {
Toast.makeText(applicationContext,
"Sorry! Unable to create map.", Toast.LENGTH_SHORT)
.show();
} else {
Marker loc = googleMap.addMarker(new MarkerOptions()
.position(coord).title("User: " + username)
.snippet(addrInfo));
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(coord,
15));
fragTransaction.attach(fragment);
fragTransaction.commit();
}
}
}
}
现在的问题是,我看不到地图,尽管我没有得到任何错误。由于视图已经创建,我试图“重画”片段以显示地图,但它不起作用
我怎样才能做到这一点
任何帮助都将不胜感激
编辑:
这是我的档案活动
。正如建议的那样,我使用了onResume
来创建AsyncTask
public class ProfileActivity extends BaseActivity {
private String username, address, postalCode, country;
@Override
protected void onResume() {
Log.i("URL",
"http://maps.googleapis.com/maps/api/geocode/json?address="
+ address.replaceAll("\\s+", "+") + ",+" + postalCode
+ ",+" + country + "&sensor=false");
new LocationTask(getSupportFragmentManager(),
getApplicationContext())
.execute("http://maps.googleapis.com/maps/api/geocode/json?address="
+ address.replaceAll("\\s+", "+")
+ ",+"
+ postalCode
+ ",+" + country + "&sensor=false");
super.onResume();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
Intent intent = getIntent();
username = intent.getStringExtra(SearchResultsActivity.USERNAME);
if (username != null) {
setTitle("User: " + username);
}
address = intent.getStringExtra(SearchResultsActivity.ADDRESS);
postalCode = intent
.getStringExtra(SearchResultsActivity.POSTALCODE);
country = intent.getStringExtra(SearchResultsActivity.COUNTRY);
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(username);
setContentView(textView);
}
}
剖面布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<FrameLayout
android:id="@+id/map_frame"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1.2" >
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="fill_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
</FrameLayout>
<TextView
android:id="@+id/textView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:text="TextView" />
</LinearLayout>
位置任务:
public class LocationTask extends
AsyncTask<String, String, StringBuilder> {
private EditText address = null;
private EditText postalCode = null;
private EditText country = null;
private Context applicationContext;
private FragmentManager fragmentManager;
private LatLng coord;
public LocationTask(FragmentManager fmanager,
Context applicationContext) {
this.fragmentManager = fmanager;
this.applicationContext = applicationContext;
}
@Override
protected StringBuilder doInBackground(String... params) {
HttpGet httpGet = new HttpGet(params[0]);
HttpClient client = new DefaultHttpClient();
HttpResponse response;
try {
response = client.execute(httpGet);
StringBuilder stringBuilder = new StringBuilder();
try {
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return stringBuilder;
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(StringBuilder result) {
JSONObject jsonObject = new JSONObject();
try {
jsonObject = new JSONObject(result.toString());
} catch (JSONException e) {
e.printStackTrace();
}
String postal_code = null;
String street_address = null;
String country = null;
try {
String status = jsonObject.getString("status").toString();
if (status.equalsIgnoreCase("OK")) {
JSONArray results = jsonObject.getJSONArray("results");
JSONObject r = results.getJSONObject(0);
JSONArray addressComponentsArray = r
.getJSONArray("address_components");
JSONObject geometry = r.getJSONObject("geometry");
JSONObject locationObj = geometry.getJSONObject("location");
coord = new LatLng(locationObj.getDouble("lat"), locationObj.getDouble("lng"));
}
} catch (JSONException e) {
e.printStackTrace();
}
GoogMapHandler gmh = new GoogMapHandler(fragmentManager, applicationContext);
gmh.initilizeMap(coord, "Username", "addressInfo");
}
}
公共类定位任务扩展
异步任务{
私有编辑文本地址=空;
私有EditText postalCode=null;
私有EditText国家/地区=空;
私有上下文应用上下文;
私人碎片管理器碎片管理器;
私人拉丁合作社;
公共位置任务(碎片管理器fmanager,
上下文应用程序上下文){
this.fragmentManager=fmanager;
this.applicationContext=applicationContext;
}
@凌驾
受保护的StringBuilder doInBackground(字符串…参数){
HttpGet HttpGet=新的HttpGet(参数[0]);
HttpClient=new DefaultHttpClient();
HttpResponse响应;
试一试{
response=client.execute(httpGet);
StringBuilder StringBuilder=新的StringBuilder();
试一试{
HttpEntity=response.getEntity();
InputStream=entity.getContent();
int b;
而((b=stream.read())!=-1){
stringBuilder.append((char)b);
}
}捕获(客户端协议例外e){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}
返回stringBuilder;
}捕获(客户端协议例外e){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}
返回null;
}
@凌驾
PostExecute上受保护的void(StringBuilder结果){
JSONObject JSONObject=新的JSONObject();
试一试{
jsonObject=newJSONObject(result.toString());
}捕获(JSONException e){
e、 printStackTrace();
}
字符串邮政编码=空;
String street_address=null;
字符串country=null;
试一试{
String status=jsonObject.getString(“status”).toString();
if(状态相等信号情况(“正常”)){
JSONArray results=jsonObject.getJSONArray(“结果”);
JSONObject r=results.getJSONObject(0);
JSONArray地址组件数组=r
.getJSONArray(“地址组件”);
JSONObject几何体=r.getJSONObject(“几何体”);
JSONObject locationObj=geometry.getJSONObject(“位置”);
coord=新LatLng(位置OBJ.getDouble(“lat”)、位置OBJ.getDouble(“lng”);
}
}捕获(JSONException e){
e、 printStackTrace();
}
GoogMapHandler gmh=新的GoogMapHandler(fragmentManager,applicationContext);
gmh.initilizeMap(坐标,“用户名”,“地址信息”);
}
}
我无法发表评论
你确定你的代码在IF块中吗:
public void initilizeMap(LatLng coord, String username, String addrInfo) {
if (googleMap == null) {
//are you getting upto here?
....
}
}
如果在布局中声明了SupportMapFragment,我认为detach在这里不会做任何有意义的事情。以下方面应起作用:
public void initilizeMap(LatLng coord, String username, String addrInfo) {
if (googleMap == null) {
Fragment fragment = this.fragmentManager.findFragmentById(R.id.map);
SupportMapFragment supportmapfragment = (SupportMapFragment) fragment;
googleMap = supportmapfragment.getMap();
if (googleMap == null) {
Toast.makeText(applicationContext,
"Sorry! Unable to create map.", Toast.LENGTH_SHORT)
.show();
} else {
Marker loc = googleMap.addMarker(new MarkerOptions()
.position(coord).title("User: " + username)
.snippet(addrInfo));
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(coord, 15));
}
} else {
Marker loc = googleMap.addMarker(new MarkerOptions()
.position(coord).title("User: " + username)
.snippet(addrInfo));
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(coord, 15));
}
如果上述方法不起作用,那么问题不太可能出现在代码块中,相反,它可能在map准备就绪之前被调用。
请给我们更多的信息;告诉我们在调用
onResume()
之前,AsyncTask是否会返回结果。我忘了在我的档案活动中删除这个:
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(username);
setContentView(textView);
卸下它,解决了我的问题。谢谢您的帮助。我100%确信我进入了IF区块。我认为问题在于我不能在活动的onCreate
方法中调用AsyncTask。因为它不会等到AsyncTask
完成(在我从AsyncTask
获得结果之后,我创建了GoogMapHandler
的一个实例,然后初始化活动的映射。是否有类似于onBeforeCreate
的方法?为什么不尝试在onResume()中调用AsyncTask
?我尝试过,但得到了相同的结果(没有显示谷歌地图,也没有警告或错误)。您是否可以发布更多代码?我想看看是否可以运行它很高兴您修复了它。我们正忙着查找地图中的问题:)