简体   繁体   中英

Redraw Fragment in View after initialising Google Map - Android

I want to display a Google Map on half screen of my profile view. In my onCreate method I created a new instance of an AsyncTask to retrieve latitude and longitude from Google servers via JSON. After receiving the result, I call:

GoogMapHandler gmh = new GoogMapHandler(fragmentManager, applicationContext);
gmh.initilizeMap(coord, "Username", "addressInfo");

Here is my GoogMapHandler class:

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();
            }
        }
    }
}

Now the problem is, that I can't see the map, although I get no errors. As the View is already created, I tried to to "redraw" the fragment to display the map, but it's not working.

How can I achieve this?

Any help would be greatly appreciated.

EDIT:

Here is my ProfileActivity . As suggested, I used onResume to create the 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);

    }
}

Profile Layout:

<?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>

Location Task:

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");

    }
}

I forgot to remove this in my ProfileActivity :

        TextView textView = new TextView(this);
        textView.setTextSize(40);
        textView.setText(username);

        setContentView(textView);

Removing it, solved my problem.

I cannot comment

Are you sure your code is going inside the IF block:

 public void initilizeMap(LatLng coord, String username, String addrInfo) {
    if (googleMap == null) {
       //are you getting upto here?
    ....
    }
 }

If SupportMapFragment is declared in your layout, I don't think detach will do anything meaningful here. The following should work:

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));
}

If the above is not working, the problem is unlikely to be in the block of code, rather, it's probably getting called before map is ready. Please give us more info; tell us whether the AsyncTask may be returning the results before onResume() is being called.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM