java.lang.NullPointerException Google Maps Android API V2 - android

I would like to begin by saying I know this error has been posted about 2,000 times, but after looking through pages and pages of people with the same issue and trying all of their fixes, none of them have worked so I decided to make a new question. I apologize if there is a thread with a solution for my specific problem, I was not able to locate it.
With that out of the way, I believe the error is that there is a NullPointerException on line 41 of MainActivity.Java, because the Google Map is null and not being initialized.
Line 41 is as follows:
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapU)).getMap();
If I remove all of my code from MainActivity.Java, leaving only the code generated by Android Studio, the app starts up fine and will display a Google Map of the World, so I don't think it has anything to do with my API key or Google Play Services not being updated.
Some stuff I have tried is:
-Switching from FragmentManager to SupportFragmentManager on line 41 (When I did this I changed the map from FragmentMap to SupportMapFragment)
-Adding permissions to the Manifest file, you can see everything I have ended up with.
-Different devices (Doesn't work on a Samsung Galaxy S2 or a Galaxy S4)
-I was originally on minSDK 12, decided to change to 16 just to see if it would help, nothing
NOTE: When I first created this project, for some reason the MainActivity.Java said extends ActionBarActivity instead of FragmentActivity, so I changed it to say FragmentActivity, but I was having this issue both before and after.
Manifest.XML
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.hasan.maps" >
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="com.google.android.providers.gsf.permission.MAPS_RECIEVE"></uses-permission>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<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" >
<activity
android:name="com.hasan.maps.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="APIKEY_IS_INSERTED_HERE"/>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
</application>
</manifest>
MainActivity.Java
package com.hasan.maps;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
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;
import android.os.Build;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
public class MainActivity extends FragmentActivity {
private GoogleMap map;
private final LatLng Location_NJIT = new LatLng(40.7406517, -74.1792757);
private final LatLng Location_Stevens = new LatLng(40.7469309, -74.0258336);
#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();
}
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapU)).getMap();
}
#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);
}
public void onClick_city (View v){
}
public void onClick_njit (View v){
CameraUpdate update = CameraUpdateFactory.newLatLng(Location_NJIT);
map.animateCamera(update);
}
public void onClick_stevens (View v){
}
/**
* 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;
}
}
}
Logcat
Logcat
01-31 00:08:42.050 14353-14353/com.hasan.maps E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.hasan.maps/com.hasan.maps.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2110)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135)
at android.app.ActivityThread.access$700(ActivityThread.java:140)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1237)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4938)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
atcom.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.hasan.maps.MainActivity.onCreate(MainActivity.java:41)
at android.app.Activity.performCreate(Activity.java:5188)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2074)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135)
            at android.app.ActivityThread.access$700(ActivityThread.java:140)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1237)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4938)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
Fragment_Main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.hasan.maps.MainActivity$PlaceholderFragment">
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/mapU"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_below="#+id/stevens" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="City"
android:id="#+id/city"
android:layout_above="#+id/map"
android:layout_toRightOf="#+id/header"
android:onClick="onClick_city" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="NJIT"
android:id="#+id/njit"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/city"
android:onClick="onClick_njit" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stevens"
android:id="#+id/stevens"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/njit"
android:onClick="onClick_stevens" />
</RelativeLayout>
Thanks in advance!

//Actually you have declared frafment id android:id="#+id/mapU" in layout Fragment_Main.xml
but your are calling in MainActivity.java with layout activity_main.xml
make sure that you are declared map fragment in activity_mail.xml.
or call the map in your
PlaceholderFragment
map = ((SupportMapFragment) getSupportFragmentManager()rootView.findFragmentById(R.id.mapU)).getMap();

ANSWER:
I figured it out finally after hours of tearing my hair out. The code had to be moved under the Fragment Activity Class.

Related

Facebook Sharing with android studio

Dear people of the stackoverflow,
I'm afraid im in dire need of help. There is one problem that I keep encountering with my app.
I'm making an app that has three buttons: One to see a link, one for intent and one for sharing stuff on facebook (the reason is due to that you cant send stuff with intent anymore, or so i've been told)
However, according to the Facebook Developer website, i should get a share button. With my code , everything crashes and the only thing i can see, is the share dialog. My question is, what is the main mistake i've made?
My main activity code:
package things;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.view.View.OnClickListener;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.share.ShareApi;
import com.facebook.share.Sharer;
import com.facebook.share.model.ShareLinkContent;
import com.facebook.share.widget.ShareButton;
import com.facebook.share.widget.ShareDialog;
import java.util.Random;
public class MainActivity extends ActionBarActivity {
private Button btnScore;
private Button btnShare;
private static String APP_ID = "things";
CallbackManager callbackManager;
ShareDialog shareDialog;
//ms = mobile Scores
WebView msWebView;
WebView mfWebView;
ShareLinkContent content = new ShareLinkContent.Builder()
.setContentTitle("Test")
.setContentUrl(Uri.parse("http://developers.facebook.com/android"))
.setContentDescription("Play Something with your facebook friends and many more people!")
.build();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
//Facebook for sharing
callbackManager = CallbackManager.Factory.create();
shareDialog = new ShareDialog(this);
final ShareButton shareButton = (ShareButton) findViewById(R.id.fb_share_button);
int score = 64;
//Searches the phone for apps that can share simple data
final Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.setType("text/plain");
sendIntent.putExtra(Intent.EXTRA_TEXT, "My score of the last game was: " + score + " \n Can you beat my score?");
//This is for the share dialog to show
//an iff statement if it shows
if (ShareDialog.canShow(ShareLinkContent.class)) {
ShareLinkContent linkContent = new ShareLinkContent.Builder()
.setContentTitle("Hello Facebook")
.setContentDescription(
"The 'Hello Facebook' sample showcases simple Facebook integration")
.setContentUrl(Uri.parse("http://developers.facebook.com/android"))
.build();
shareDialog.show(linkContent);
}
shareButton.setShareContent(content);
//The buttons
btnScore=(Button)findViewById(R.id.btnScores);
btnShare =(Button)findViewById(R.id.btnShare);
//the score Webview link
msWebView = new WebView(this);
msWebView.loadUrl("Thing");
msWebView.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
view.loadUrl(url);
return true;
}
});
ShareDialog.show(this, content);
btnScore.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View vw) {
setContentView(msWebView);
}
});
//the share button
btnShare.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View vw) {startActivity(Intent.createChooser(sendIntent, "share..."));
}
});
shareButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
shareButton.setShareContent(content);
}
} );
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu.
// Adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
// Access the Share Item defined in menu XML
return true;
}
//special method to handle the callbackmanager
#Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
ShareDialog.show(this, content);
}
#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.menu_item_share) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
My Activity_Main.XML:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity"
android:background="#ffd2e489">
<TextView android:text="Results"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/text"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="View"
android:id="#+id/btnScores"
android:background="#ffff7878"
android:layout_marginTop="40dp"
android:layout_below="#+id/text"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_toLeftOf="#+id/text"
android:layout_toStartOf="#+id/text" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Share"
android:id="#+id/btnShare"
android:background="#ff20f6ff"
android:layout_alignTop="#+id/btnScores"
android:layout_toRightOf="#+id/text"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<com.facebook.share.widget.ShareButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/fb_share_button"
android:text="SHARE"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="175dp" />
</RelativeLayout>
And just in case my Android: Manifest:
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name=".MyApplication"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="#string/app_id"/>
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<provider android:authorities="com.facebook.app.FacebookContentProviderthings"
android:name="com.facebook.FacebookContentProvider"
android:exported="true"/>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/plain"/>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.facebook.FacebookActivity"
android:configChanges=
"keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:theme="#android:style/Theme.Translucent.NoTitleBar"
android:label="#string/app_name" />
android:debuggable="true"
</application>
</manifest>
Sorry for the long post, I know the answer is there but can't find the greemly error and this has been bothering me for a week.
Thanks for reading!
Frederick
Edit: I'm using facebookSDK 4.0.
Edit 2.0: the error:
Caused by: java.lang.NullPointerException
at things.MainActivity.onCreate(MainActivity.java:93)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2201)
Edit 3.0 The Logcat:
Process: nl.test.test, PID: 12287
java.lang.ExceptionInInitializerError
at java.lang.reflect.Constructor.constructNative(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at android.view.LayoutInflater.createView(LayoutInflater.java:594)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:696)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at android.support.v7.app.ActionBarActivityDelegateBase.setContentView(ActionBarActivityDelegateBase.java:240)
at android.support.v7.app.ActionBarActivity.setContentView(ActionBarActivity.java:102)
at nl.test.test.MainActivity.onCreate(MainActivity.java:60)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2201)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2286)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1246)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:212)
at android.app.ActivityThread.main(ActivityThread.java:5135)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:878)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
at dalvik.system.NativeStart.main(Native Method)
Caused by: null
at com.facebook.internal.Validate.sdkInitialized(Validate.java:99)
at com.facebook.FacebookSdk.getCallbackRequestCodeOffset(FacebookSdk.java:735)
at com.facebook.internal.CallbackManagerImpl$RequestCodeOffset.toRequestCode(CallbackManagerImpl.java:109)
at com.facebook.share.widget.ShareButton.<clinit> (ShareButton.java:36)
at java.lang.reflect.Constructor.constructNative(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at android.view.LayoutInflater.createView(LayoutInflater.java:594)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:696)
android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
android.view.LayoutInflater.inflate(LayoutInflater.java:492)
android.view.LayoutInflater.inflate(LayoutInflater.java:397)
android.view.LayoutInflater.inflate(LayoutInflater.java:353)
android.support.v7.app.ActionBarActivityDelegateBase.setContentView(ActionBarActivityDelegateBase.java:240)
android.support.v7.app.ActionBarActivity.setContentView(ActionBarActivity.java:102)
test.MainActivity.onCreate(MainActivity.java:60)
at android.app.Activity.performCreate(Activity.java:5231)
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2201)
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2286)
android.app.ActivityThread.access$800(ActivityThread.java:144) android.app.ActivityThread$H.handleMessage(ActivityThread.java:1246)
android.os.Handler.dispatchMessage(Handler.java:102)
android.os.Looper.loop(Looper.java:212)
android.app.ActivityThread.main(ActivityThread.java:5135)
java.lang.reflect.Method.invokeNative(Native Method)
java.lang.reflect.Method.invoke(Method.java:515)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:878)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
dalvik.system.NativeStart.main(Native Method)
Alright, after some work, I found the answer. The answer is very simple:
instead of this:
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
But what you need to do is this:
FacebookSdk.sdkInitialize(getApplicationContext());
super.onCreate(savedInstanceState);
The reason to do this, is because you want to initialize the Facebook SDK before you create the app instance, otherwise, the Facebook SDK can never be used by the app.
I hope that if someone has the same problem as I had, can use this!

Can't draw Google Maps v2 with Navigation Drawer

Ok, so I just begun with Android Development and basically my issue is what title describes. What I tried until now is to create a default Drawer Navigation Activity project and write a Google Maps Fragment class and lastly inflate this to the main content.
The reason I want this to work is because Drawer Nav Activity looks nice and it would be nice to have google maps in the main screen of it.
By reading the Docs: http://developer.android.com/guide/components/fragments.html I understand that in order to successfully display a fragment inside another activity you need to firstly create a Google Maps Class that extends MapFragment or Fragment and secondly declare the fragment inside the activity's layout file.
No matter what I tried, it just never works. I have managed to draw Google Maps successfully but its Class code is not being invoked, thus Maps actions do not exist.
The google maps responsible GMapsFragment Class (I think that the marked line below (35) is causing the error in conjuction with the maps xml file):
package com.example.s0me0n3.ytgooglemapstut;
import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class GMapsFragment extends Fragment {
public MapView mapView;
private static GoogleMap googleMap;
public GMapsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
Log.w("GMAPS", "Map place 1");
// **********************************************************************************
// The line below throws an inflation error when trying to parse the fragment_map xml
// **********************************************************************************
View rootView = inflater.inflate(R.layout.fragment_map, container, false);
// Log.w("GMAPS", "Map place 1");
if (googleMap != null)
setUpMap();
if (googleMap == null) {
googleMap = ((MapFragment) MyActivity.fragmentManager.findFragmentById(R.id.ContactMapView)).getMap();
if (googleMap != null) {
setUpMap();
}
}
return rootView;
}
private static void setUpMap() {
googleMap.setMyLocationEnabled(true);
googleMap.addMarker(new MarkerOptions().position(new LatLng(41.009471, 28.916134)).title("baslik"));
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(41.009471, 28.916134), 12.0f));
}
#Override
public void onDestroyView() {
super.onDestroyView();
if (googleMap != null) {
MyActivity.fragmentManager.beginTransaction()
.remove(MyActivity.fragmentManager.findFragmentById(R.id.ContactMapView))
.commit();
googleMap = null;
}
}
}
and the main activity class MyActivity:
package com.example.s0me0n3.ytgooglemapstut;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.maps.MapFragment;
public class MyActivity extends Activity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
public static FragmentManager fragmentManager;
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
// private GMapsFragment _gmaps;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// _gmaps = (GMapsFragment)
// getFragmentManager().findFragmentById(R.id.ContactMapView);
// FragmentTransaction fragmentTransaction = _gmaps.beginTransaction();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
// *** The Note below is pointing here! ***
GMapsFragment fragment = new GMapsFragment();
fragmentTransaction.add(R.id.container, fragment);
fragmentTransaction.commit();
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.my, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#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) {
// showMsg("Settings reeee");
// Log.w("MyActivity", "Will now log u out...");
Intent intent = new Intent();
intent.setClass(MyActivity.this, SetPreferenceActivity.class);
startActivityForResult(intent, 0);
// return true;
}
return super.onOptionsItemSelected(item);
}
private void showMsg(String msg) {
Toast toast = Toast.makeText(this, msg, Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, toast.getXOffset() / 2, toast.getYOffset() / 2);
toast.show();
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_my, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MyActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
Note: If I change the line 73 "GMapsFragment fragment = new GMapsFragment();" in the MyActivity Class with something like this "Fragment fragment = new MapFragment();" then it works fine, but of course the GMapsFragment is not being run. Instead a default gmaps is being displayed with no functionalities at all. However, I do not understand why the inflation of my own gmaps fragment will not work.
After that, I understand that I have to include the Google Maps fragment inside the main xml.. so here is the activity_my.xml:
<!-- A DrawerLayout is intended to be used as the top-level content view using match_parent for both width and height to consume the full space available. -->
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MyActivity">
<!-- As the main content view, the view below consumes the entire
space available using match_parent in both dimensions. -->
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- android:layout_gravity="start" tells DrawerLayout to treat
this as a sliding drawer on the left side for left-to-right
languages and on the right side for right-to-left languages.
If you're not building against API 17 or higher, use
android:layout_gravity="left" instead. -->
<!-- The drawer is given a fixed width in dp and extends the full height of
the container. -->
<fragment android:id="#+id/navigation_drawer"
android:layout_width="#dimen/navigation_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
android:name="com.example.s0me0n3.ytgooglemapstut.NavigationDrawerFragment"
tools:layout="#layout/fragment_navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
and the fragment_map.xml:
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:id="#+id/ContactMapView"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
Here is my AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.s0me0n3.ytgooglemapstut" >
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<permission android:name="com.example.s0me0n3.ytgooglemapstut.permission.MAPS_RECEIVE" android:protectionLevel="signature" />
<uses-permission android:name="com.example.s0me0n3.ytgooglemapstut.permission.MAPS_RECEIVE" />
<uses-permission android:name="com.example.s0me0n3.ytgooglemapstut.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-feature android:glEsVersion="0x00020000" android:required="true"/>
<uses-permission android:name="com.example.s0me0n3.ytgooglemapstut.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="com.example.s0me0n3.ytgooglemapstut.permission.ACCESS_FINE_LOCATION" />
<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=".MyActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".SetPreferenceActivity"
android:label="User Settings" >
</activity>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyCoyacHtM9Nl0rjDYFJqV9wUQfiN6OlDOU"/>
</application>
</manifest>
The Logcat errors that I am receiving after running the app is:
10-10 12:44:55.420 8017-8017/com.example.s0me0n3.ytgooglemapstut E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.s0me0n3.ytgooglemapstut, PID: 8017
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.s0me0n3.ytgooglemapstut/com.example.s0me0n3.ytgooglemapstut.MyActivity}: android.view.InflateException: Binary XML file line #1: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #1: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:714)
at android.view.LayoutInflater.inflate(LayoutInflater.java:469)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at com.example.s0me0n3.ytgooglemapstut.GMapsFragment.onCreateView(GMapsFragment.java:35)
at android.app.Fragment.performCreateView(Fragment.java:1700)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:890)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1040)
at android.app.Activity.onCreateView(Activity.java:4805)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:690)
at android.view.LayoutInflater.inflate(LayoutInflater.java:469)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at com.example.s0me0n3.ytgooglemapstut.GMapsFragment.onCreateView(GMapsFragment.java:35)
at android.app.Fragment.performCreateView(Fragment.java:1700)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:890)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062)
at android.app.BackStackRecord.run(BackStackRecord.java:684)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1447)
at android.app.Activity.performStart(Activity.java:5240)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2168)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
            at android.app.ActivityThread.access$800(ActivityThread.java:135)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5017)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
            at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalArgumentException: Binary XML file line #1: Duplicate id 0x7f050017, tag null, or parent id 0x7f050015 with another fragment for com.google.android.gms.maps.MapFragment
at android.app.Activity.onCreateView(Activity.java:4791)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:690)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:469)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
            at com.example.s0me0n3.ytgooglemapstut.GMapsFragment.onCreateView(GMapsFragment.java:35)
            at android.app.Fragment.performCreateView(Fragment.java:1700)
            at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:890)
            at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1040)
            at android.app.Activity.onCreateView(Activity.java:4805)
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:690)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:469)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
            at com.example.s0me0n3.ytgooglemapstut.GMapsFragment.onCreateView(GMapsFragment.java:35)
            at android.app.Fragment.performCreateView(Fragment.java:1700)
            at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:890)
            at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062)
            at android.app.BackStackRecord.run(BackStackRecord.java:684)
            at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1447)
            at android.app.Activity.performStart(Activity.java:5240)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2168)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
            at android.app.ActivityThread.access$800(ActivityThread.java:135)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5017)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
            at dalvik.system.NativeStart.main(Native Method)
Last words.. I tried running the GMapsFragment class from other xml files or the my_activity.xml but I always end up getting errors.
So, after that wall spam, let me explain to you my goal. I would like to use the default produced Drawer Nav code from Android Studio in conjuction with a Google Maps that is being displayed on the main content.
Any enlightenment would be awesome. I have been searching for the last 6 days for a solution with no luck. It has to be a really silly mistake, I know but I am stuck.
P.S: I have seen examples using the SupportMapFragment but I would like to make my above code work or understand why this is impossible if so.
Change your fragment_map.xml to :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="#+id/ContactMapView"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</RelativeLayout>

<Activity name> cannot be resolved or not a field

I'm trying to perform a simple navigation action using Intent.
I'm using the complete ADT bundle which includes eclipse, SDK and ADT plugins, so no need to configure ADT separately in eclipse.
1.) I started by creating two layouts named activity_main.xml and test2.xml.
2.) Corresponding java files are mainActivity.java and test2.java.
3.) Now activity_main.xml contains a button with id = "click" . Clicking this button should navigate to next activity i.e test2.xml.
4.) The code in mainActivity.java is as below
package com.example.test;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.os.Build;
public class MainActivity extends ActionBarActivity
{
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
if (savedInstanceState == null)
{
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
btn = (Button)findViewById(R.id.click);
//Listening to button event
btn.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0) {
//Starting a new Intent
Intent nextScreen = new Intent(getApplicationContext(), test2.class);
startActivity(nextScreen);
}
});
}
#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;
}
}
}
5.) But when i did so the findViewById(R.id.click) showed error saying "click cannot be resolved or is not a field"
6.) Eclipse suggested me to create a field click in id which i did. It modified the R.java file but it did not help. Though the errors were gone but the emulator threw error saying "the application has stopped"
7.) My manifest.xml file is as below
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.test"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.test.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>
<activity
android:name=".test2"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.example.test.test2" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
8.) Now my test2.java code is
package com.example.test;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
import com.example.test.R;
public class test2 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.test2);
TextView txtName = (TextView) findViewById(R.id.textView1);
txtName.setText("This is test2 activity");
}
}
Even here at setContentView(R.layout.test2) it shows the similar error as "test2 cannot be resolved or not a field" where as setContentView(R.layout.activity_main) did not show this error
9.) My fragment_main.xml code is as below
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.test.MainActivity$PlaceholderFragment" >
<Button
android:id="#+id/click"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_centerInParent="true"
android:layout_marginLeft="14dp"
android:layout_marginTop="65dp"
android:text="#string/button" />
</RelativeLayout>
10.) My test2.xml code is as below
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="second page"
android:layout_gravity="center"
/>
</LinearLayout>
The error displayed on running the application is as below
a.) [2014-04-15 18:39:03 - test] W/ResourceType( 8160): ResXMLTree_node header size 0 is too small.
b.) [2014-04-15 18:39:03 - test] C:\Users\KC\Desktop\Android-budle\test\res\menu\main.xml:6: error: Error: No resource found that matches the given name (at 'title' with value '#string/action_settings').
I'm not able to understand what am I missing. Please provide me a solution for this issue, Thanks in advance.
Firstly Check your layout xml. I there is any error then correct it.After that press alt+p then select clean after that it will be build again.
In your activity_main.xml>Button you need to put the android:onClick="methodName". The in your main_activity you schould implement methodName. There you can handle the activities once the Button is clicked.
Another way is to implement the onClickListener to sepertate the XML and the Java files.
Can you add your layout XML files?
Write the onClickListener for your button in your MainActivity onCreate() method and inside it redirect to test2 activity as below:
btn = (Button)findViewById(R.id.click);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(MainActivity.this,test2.class);
startActivity(intent);
}
});
EDITED:
You need to set your view as fragment_main.xml besides activity_main as your Button is inside fragment_main layout.
Just change the
setContentView(R.layout.activity_main);
to
setContentView(R.layout.fragment_main);
There is something wrong syntax wise with your xml files (test2 or activity_main) due to which the auto generated R file will no longer generate the id for the button view.
The main problem seems to be with activity_main as the button contained in it is no longer converted to its corresponding value in R file.
Check those files and if not able to figure out than put the code in order to get help.
Last but not the least check if you have the import statement like import android.R.
You don't need this to be there as it causes such errors if present.
UPDATE:
You are using -
1) setContentView(R.layout.activity_main);
2) btn = (Button)findViewById(R.id.click);
But your layout where you defined your button is setContentView(R.layout.fragment_main);
So btn is trying to find the view in activity_main which is not available.
Solution -
Set the content view to setContentView(R.layout.fragment_main).

Null pointer Exception with google Maps V2 inside a Fragment

I've recently started to develop something with android.
I am trying to create a activity with Drawer Navigation and google map.
I have read how to do, I searched for a solution but have not been able to solve the problem.
This is the main activity. and 'also responsible for the error:
package it.kytech.linkess;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
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 MainActivity extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
#Override
public void onNavigationDrawerItemSelected(int position) {
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#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 {
static final LatLng HAMBURG = new LatLng(53.558, 9.927);
static final LatLng KIEL = new LatLng(53.551, 9.993);
private GoogleMap map;
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_main, null, false);
FragmentTransaction ft = getFragmentManager().beginTransaction();
map = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
SupportMapFragment fmap = (SupportMapFragment) getFragmentManager().findFragmentById(R.id.map);
if (fmap == null) {
fmap = SupportMapFragment.newInstance();
ft.add(R.id.map, fmap);
}
ft.commit();
Marker hamburg = map.addMarker(new MarkerOptions().position(HAMBURG)
.title("Hamburg"));
Marker kiel = map.addMarker(new MarkerOptions()
.position(KIEL)
.title("Kiel")
.snippet("Kiel is cool"));
// Move the camera instantly to hamburg with a zoom of 15.
map.moveCamera(CameraUpdateFactory.newLatLngZoom(HAMBURG, 15));
// Zoom in, animating the camera.
map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
return v;
}
}
}
This is the main xml.
<!-- A DrawerLayout is intended to be used as the top-level content view using match_parent for both width and height to consume the full space available. -->
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="it.kytech.linkess.MainActivity">
<!-- As the main content view, the view below consumes the entire
space available using match_parent in both dimensions. -->
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- android:layout_gravity="start" tells DrawerLayout to treat
this as a sliding drawer on the left side for left-to-right
languages and on the right side for right-to-left languages.
If you're not building against API 17 or higher, use
android:layout_gravity="left" instead. -->
<!-- The drawer is given a fixed width in dp and extends the full height of
the container. -->
<fragment android:id="#+id/navigation_drawer"
android:layout_width="#dimen/navigation_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
android:name="it.kytech.linkess.NavigationDrawerFragment" />
</android.support.v4.widget.DrawerLayout>
This is the xml for the map:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="it.kytech.linkess.MainActivity$PlaceholderFragment">
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.MapFragment"/>
</RelativeLayout>
This is the xml of the drawer:
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#cccc"
tools:context="it.kytech.myapplication2.app.NavigationDrawerFragment" />
I also attach my manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="it.kytech.linkess" >
<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.maps.v2.API_KEY"
android:value="my hidden key"/>
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity
android:name="it.kytech.linkess.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>
</application>
</manifest>
The error occurs on this line:
map = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
Full log:
04-15 22:21:08.325 30251-30251/it.kytech.linkess E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: it.kytech.linkess, PID: 30251
java.lang.RuntimeException: Unable to start activity ComponentInfo{it.kytech.linkess/it.kytech.linkess.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2215)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2265)
at android.app.ActivityThread.access$800(ActivityThread.java:145)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1206)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5149)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:605)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at it.kytech.linkess.MainActivity$PlaceholderFragment.onCreateView(MainActivity.java:110)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1500)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:938)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1115)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1478)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:570)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1171)
at android.app.Activity.performStart(Activity.java:5241)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2178)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2265)
            at android.app.ActivityThread.access$800(ActivityThread.java:145)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1206)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5149)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:605)
            at dalvik.system.NativeStart.main(Native Method)
Obviously the key to the generated code has been hidden.
I hope you can help me.
the problem is that your are getting the map before you initialized ur sopportmapfragment thats why your map is null.. try to switch it initialized the map fragment first and get the map.
Your null pointer is likely because it can not find R.id.map in the current layout (activity_main.xml).
After looking through your code, I don't see where you ever inflate the map xml file and add it to your layout.
Perhaps you meant to add an include statement
<include layout="#layout/map"/>
instead of the frame layout so that it is actually instantiated?
Either that, or inflate the map.xml file, attach it to your layout, and then call findViewById.

Cannot resolve method maps

I am using android studio and trying to bring in google maps. In my android manifest I have added these lines:
<uses-library android:name="com.google.android.maps" />/>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="myKEY" />
And when I try and create a map in my xml I get the error:
Cannot resolve method maps
My xml I created looks like this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.MapFragment" />
</RelativeLayout>
The cannot resolve method maps is on this line:
class="com.google.android.gms.maps.MapFragment" />
Code:
package com.beerportfolio.beerportfoliopro;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SearchView;
/**
* Created by Mike on 3/17/14.
*/
public class BreweryMap extends Fragment {
public BreweryMap(){}
String beerId = "";
SearchView searchView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_brewmap, container, false);
setHasOptionsMenu(true);
return rootView;
}
}
try to this instead:
class="com.google.android.gms.maps.SupportMapFragment"
and in the Fragment you can do this
public class MyFragment extends SupportMapFragment
this worked for me. Everything else seems to be correct. Maybe its your code but try to extend SupportMapFragment.

Categories

Resources