0

I'm new in android programmer. Recently, I trying to make project that using google map v2 in android app, but I'm getting a lot of error (I have add google play services to my library and find similar topic in here, but not solved my problem).Please see my log cat bellow :

UPDATED

03-22 13:52:29.331: E/AndroidRuntime(17708): FATAL EXCEPTION: main
03-22 13:52:29.331: E/AndroidRuntime(17708): java.lang.RuntimeException: Unable to resume activity {com.yai.testmap/com.yai.testmap.MainActivity}: java.lang.NullPointerException
03-22 13:52:29.331: E/AndroidRuntime(17708):    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2613)
03-22 13:52:29.331: E/AndroidRuntime(17708):    at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2641)
03-22 13:52:29.331: E/AndroidRuntime(17708):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2127)
03-22 13:52:29.331: E/AndroidRuntime(17708):    at android.app.ActivityThread.access$600(ActivityThread.java:140)
03-22 13:52:29.331: E/AndroidRuntime(17708):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1228)
03-22 13:52:29.331: E/AndroidRuntime(17708):    at android.os.Handler.dispatchMessage(Handler.java:99)
03-22 13:52:29.331: E/AndroidRuntime(17708):    at android.os.Looper.loop(Looper.java:137)
03-22 13:52:29.331: E/AndroidRuntime(17708):    at android.app.ActivityThread.main(ActivityThread.java:4895)
03-22 13:52:29.331: E/AndroidRuntime(17708):    at java.lang.reflect.Method.invokeNative(Native Method)
03-22 13:52:29.331: E/AndroidRuntime(17708):    at java.lang.reflect.Method.invoke(Method.java:511)
03-22 13:52:29.331: E/AndroidRuntime(17708):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:994)
03-22 13:52:29.331: E/AndroidRuntime(17708):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:761)
03-22 13:52:29.331: E/AndroidRuntime(17708):    at dalvik.system.NativeStart.main(Native Method)
03-22 13:52:29.331: E/AndroidRuntime(17708): Caused by: java.lang.NullPointerException
03-22 13:52:29.331: E/AndroidRuntime(17708):    at com.yai.testmap.MainActivity.setUpMapIfNeeded(MainActivity.java:93)
03-22 13:52:29.331: E/AndroidRuntime(17708):    at com.yai.testmap.MainActivity.onResume(MainActivity.java:187)
03-22 13:52:29.331: E/AndroidRuntime(17708):    at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1199)
03-22 13:52:29.331: E/AndroidRuntime(17708):    at android.app.Activity.performResume(Activity.java:5237)
03-22 13:52:29.331: E/AndroidRuntime(17708):    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2603)
03-22 13:52:29.331: E/AndroidRuntime(17708):    ... 12 more

UPDATE

my MainActivity.java :

package com.yai.testmap;

import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

/* FOR ERROR REPPORT */
import android.util.Log;

/* IMPORT FOR DROPDOWNLIST USED THIS PROJECT */
import android.widget.CheckBox;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AdapterView.OnItemSelectedListener;

/* IMPORT FOR GOOGLE MAP */
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;

/* FOR GOOGLE MAP TYPE */
import static com.google.android.gms.maps.GoogleMap.MAP_TYPE_HYBRID;
import static com.google.android.gms.maps.GoogleMap.MAP_TYPE_NONE;
import static com.google.android.gms.maps.GoogleMap.MAP_TYPE_NORMAL;
import static com.google.android.gms.maps.GoogleMap.MAP_TYPE_SATELLITE;
import static com.google.android.gms.maps.GoogleMap.MAP_TYPE_TERRAIN;

class PlaceholderFragment extends Fragment implements OnItemSelectedListener{
    private GoogleMap mGoogleMap;
    private CheckBox mTrafficCheckbox, mLocationCheckbox, mBuildingCheckbox, mIndoorCheckbox;

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_main, container, false);

    Spinner spinner = (Spinner) rootView.findViewById(R.id.spinnerOption);
    ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(), R.array.spinner_option_string, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);
    spinner.setOnItemSelectedListener((OnItemSelectedListener) getActivity());

    mTrafficCheckbox = (CheckBox) rootView.findViewById(R.id.checkbox_traffic);
    mLocationCheckbox = (CheckBox) rootView.findViewById(R.id.checkbox_location);
    mBuildingCheckbox = (CheckBox) rootView.findViewById(R.id.checkbox_building);
    mIndoorCheckbox = (CheckBox) rootView.findViewById(R.id.checkbox_indoor);

        return rootView;
    }

    @Override
    public void onItemSelected(AdapterView parent, View view, int position,
            long id) {
        // TODO Auto-generated method stub

    }
    @Override
    public void onNothingSelected(AdapterView parent) {
        // TODO Auto-generated method stub

    }
}


public class MainActivity extends ActionBarActivity implements OnItemSelectedListener {
    private GoogleMap mGoogleMap;
    private CheckBox mTrafficCheckbox, mLocationCheckbox, mBuildingCheckbox, mIndoorCheckbox;

    @Override
    protected void onCreate(Bundle savedInstanceState) {    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);         

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }   
    }   

    private void setUpMapIfNeeded(){
        if(mGoogleMap == null){
            mGoogleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
        }
    }

    private boolean checkReady(){
        if(mGoogleMap == null){
            Toast.makeText(this, R.string.map_not_ready, Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    private void updateTraffic(){
        if(!checkReady()){
            return;
        }
        mGoogleMap.setTrafficEnabled(mTrafficCheckbox.isChecked());
    }

    public void onTrafficToggled(View view){
        updateTraffic();
    }

    private void updateLocation(){
        if(!checkReady()){
            return;
        }
        mGoogleMap.setMyLocationEnabled(mLocationCheckbox.isChecked());
    }

    public void onLocationToggled(View view){
        updateLocation();
    }

    private void updateBuilding(){
        if(!checkReady()){
            return;
        }
        mGoogleMap.setBuildingsEnabled(mBuildingCheckbox.isChecked());
    }

    public void onBuildingToggled(View view){
        updateBuilding();
    }

    private void updateIndoor(){
        if(!checkReady()){
            return;
        }
        mGoogleMap.setIndoorEnabled(mIndoorCheckbox.isChecked());
    }

    public void onIndoorToggled(View view){
        updateIndoor();
    }

    @Override
    public void onItemSelected(AdapterView parent, View view, int position, long id){
         setLayer((String) parent.getItemAtPosition(position));
    }

    private void setLayer(String layerName){
        if(!checkReady()){
            return;
        }

        if(layerName.equals(getString(R.string.normal))){
            mGoogleMap.setMapType(MAP_TYPE_NORMAL);
        }
        else if(layerName.equals(getString(R.string.hybrid))){
            mGoogleMap.setMapType(MAP_TYPE_HYBRID);
        }
        else if(layerName.equals(getString(R.string.satellite))){
            mGoogleMap.setMapType(MAP_TYPE_SATELLITE);
        }
        else if(layerName.equals(getString(R.string.terrain))){
            mGoogleMap.setMapType(MAP_TYPE_TERRAIN);
        }
        else if(layerName.equals(getString(R.string.none_map))){
            mGoogleMap.setMapType(MAP_TYPE_NONE);
        }
        else{
            Log.i("LDA", "Error setting layer with name " + layerName);
        }
    }

    @Override
    public void onNothingSelected(AdapterView parent){

    }

    @Override
    protected void onResume() {
        super.onResume();
        setUpMapIfNeeded();
        if (mGoogleMap != null) {
            updateTraffic();
            updateLocation();
            updateBuilding();
            updateIndoor();
        }
    }



    @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();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container,
                    false);
            return rootView;
        }
    }

}

I'm using fragment here, so here is fragment_main.xml :

<?xml version="1.0" encoding="utf-8" ?>

    <Spinner
        android:id="@+id/spinnerOption"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <CheckBox 
        android:id="@+id/checkbox_traffic"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onTrafficToggled"
        android:text="@string/traffic" />

    <CheckBox
        android:id="@+id/checkbox_location"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onLocationToggled"
        android:text="@string/location" />

    <CheckBox
        android:id="@+id/checkbox_building"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:onClick="onBuildingsToggled"
        android:checked="true"
        android:text="@string/building" />

    <CheckBox
        android:id="@+id/checkbox_indoor"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onIndoorToggled"
        android:checked="true"
        android:text="@string/indoor" />
</LinearLayout>
</RelativeLayout>   

and my manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.yai.testmap"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="9"
    android:targetSdkVersion="17" />

<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_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true"
/>

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" 
    />

    <activity
        android:name="com.yai.testmap.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <meta-data 
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="SUPER SCREET CODE"
        />
</application>

</manifest>

here my activity_main.xml :

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.yai.testmap.MainActivity"
tools:ignore="MergeRootFrame" />

I'm curious for my Spinner and function setUpMapIfNeeded(), because when I'm commenting that parts of code, my app work. What I miss? Any idea? many thanks.

4
  • 1
    Use setContentView(R.layout.fragment_main); because all Views which you are trying to access in MainActivity is in fragment_main layout instead of in activity_main Commented Mar 22, 2014 at 6:28
  • hi, Thanks for your reply, even though I'm trying to change setContentView(R.layout.fragment_main); it still not solved my problem. Any idea? Commented Mar 22, 2014 at 6:33
  • ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)) is returning null... Commented Mar 22, 2014 at 6:39
  • and don't change your content view to R.layout.fragment_main. let it be activity_main because you need an FrameLayout with id R.id.container for Fragments transaction... Commented Mar 22, 2014 at 6:51

3 Answers 3

1

Try this..

Remove Spinner and all CheckBox from MainActivity to PlaceholderFragment like below

public static class PlaceholderFragment extends Fragment implements OnItemSelectedListener{

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container,
                false);

    Spinner spinner = (Spinner) rootView.findViewById(R.id.spinnerOption);
    ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(), R.array.spinner_option_string, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);
    spinner.setOnItemSelectedListener(getActivity());

    mTrafficCheckbox = (CheckBox) rootView.findViewById(R.id.checkbox_traffic);
    mLocationCheckbox = (CheckBox) rootView.findViewById(R.id.checkbox_location);
    mBuildingCheckbox = (CheckBox) rootView.findViewById(R.id.checkbox_building);
    mIndoorCheckbox = (CheckBox) rootView.findViewById(R.id.checkbox_indoor);

        return rootView;
    }
}

and

@Override
protected void onCreate(Bundle savedInstanceState) {    
    /* CREATE OPTION FOR DROPDOWN LIST*/
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment()).commit();
    }   
}
Sign up to request clarification or add additional context in comments.

2 Comments

Hi, thanks for your reply, I just updated my main_activity.java, is that what you mean? it still not solved. I really new in android programming so I'm very sorry if I didn't get you.
@CodingHorror map is null you are calling getMap() in null so that error
0

The problem is because Spinner and checkboxes and all others views are in

fragment_main.xml

file. You are trying to find id for that view in your MainActivity so every time it will give you Null Poniter exception because it is in PlaceHolderFragment So first add PlaceHolderFragment to your Activity and find ID for views. See this

public static class PlaceholderFragment extends Fragment implements OnItemSelectedListener{

public PlaceholderFragment() {
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_main, container,
            false);

Spinner spinner = (Spinner) rootView.findViewById(R.id.spinnerOption);
ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(), R.array.spinner_option_string, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(getActivity());

mTrafficCheckbox = (CheckBox) rootView.findViewById(R.id.checkbox_traffic);
mLocationCheckbox = (CheckBox) rootView.findViewById(R.id.checkbox_location);
mBuildingCheckbox = (CheckBox) rootView.findViewById(R.id.checkbox_building);
mIndoorCheckbox = (CheckBox) rootView.findViewById(R.id.checkbox_indoor);

    return rootView;
}
}

Comments

0

All your Views does not belong to your activity_main.xml. they are the part of your PlaceHolderFragment. So when you call findViewById() such as findViewById(R.id.spinnerOption), they simply returns null as they are not part of Activity view hierarchy...

So first add the PlaceHolderFragment to Activity, then call findViewById(), or else move all your Views declaration and their implementation into PlaceHolderFragment.

You can first add the Fragment add then call findViewById()s on your Views...

@Override
protected void onCreate(Bundle savedInstanceState) {    
    /* CREATE OPTION FOR DROPDOWN LIST*/
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment_main);

    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment()).commit();
    }   
}

7 Comments

How to do that? I just updated my post. Please check. is that what you mean? (main_activity.java). Thanks
I just updated my post. Please check it. I really need help ;) many thanks.
@CodingHorror as previously I said, ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)) is returning null and you are calling getMap() on null instance
Thanks for your help. I now its returning null in my function setUpMapIsNeeded, but what should I do? remove mGoogleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap(); ? or change it with what? many thanks.
@CodingHorror for that you need to add MapFragment or MapView to your Activity.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.