Null pointer Exception with google Maps V2 inside a Fragment - android

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.

Related

NullPointerException - I don't understand what's wrong

I am a complete newbie in android development. At the moment I am trying to replicate an app I saw on where it is possible to convert multiple images (jpeg, png, jpg) into a single pdf file. I have tried to do the most I can with debugging. But I don't understand why there are still this NullPointer Exception.
Oh and by the way please pardon me if I have some mistakes in placing proper tags or such in my question this is my first question thank you.
Here's my code for the ConvertToPDFConverter.java
package com.example.lenovo_thinkpad.mobilelectureboard;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
public class ConvertToPDFConverter extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
DrawerLayout drawer;
android.support.v7.app.ActionBar bar;
CustomActionBarDrawerToggle toggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_convert_to_pdfconverter);
bar = this.getSupportActionBar();
assert bar != null;
bar.setDisplayHomeAsUpEnabled(true);
bar.setHomeButtonEnabled(true);
bar.setDisplayShowTitleEnabled(false);
drawer = findViewById(R.id.drawer_layout);
drawer.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
try {
toggle = new CustomActionBarDrawerToggle(this, drawer);
} catch (RuntimeException e) {
e.printStackTrace();
}
drawer.addDrawerListener(toggle);
// Set navigation drawer
// Set com.example.lenovo_thinkpad.mobilelectureboard.Home fragment
Fragment fragment = new Home();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content, fragment).commit();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
Fragment fragment;
FragmentManager fragmentManager = getSupportFragmentManager();
switch (id) {
case R.id.nav_camera:
fragment = new Home();
fragmentManager.beginTransaction().replace(R.id.content, fragment).commit();
break;
case R.id.nav_gallery:
fragment = new ViewFiles();
fragmentManager.beginTransaction().replace(R.id.content, fragment).commit();
break;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
private class CustomActionBarDrawerToggle extends ActionBarDrawerToggle {
CustomActionBarDrawerToggle(Activity mActivity,
DrawerLayout mDrawerLayout) {
super(mActivity, mDrawerLayout, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
}
#Override
public void onDrawerClosed(View view) {
bar.setTitle(getString(R.string.navigation_drawer_close));
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
bar.setTitle(getString(R.string.navigation_drawer_open));
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
}
}
and for the layout activity_convert_to_pdfconverter.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".ConvertToPDFConverter">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<FrameLayout
android:layout_marginTop="20dp"
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"
android:background="#color/mb_white"
android:id="#+id/content"/>
</android.support.design.widget.CoordinatorLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
Here's the stacktrace
02-13 15:12:17.976 1548-1548/com.example.lenovo_thinkpad.mobilelectureboard E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.lenovo_thinkpad.mobilelectureboard, PID: 1548
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.lenovo_thinkpad.mobilelectureboard/com.example.lenovo_thinkpad.mobilelectureboard.ConvertToPDFConverter}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
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:5001)
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:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.lenovo_thinkpad.mobilelectureboard.ConvertToPDFConverter.onCreate(ConvertToPDFConverter.java:34)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233) 
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:5001) 
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:785) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601) 
at dalvik.system.NativeStart.main(Native Method) 
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature
android:name="android.hardware.camera.autofocus"
android:required="false" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme_picker">
<activity
android:name=".MainActivity"
android:screenOrientation="landscape">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".WhiteBoardActivity" />
<activity android:name=".ConvertToPDFConverter" />
</application>
Since you are extending the AppCompatActivity, try to get the actionbar via 'getSupportActionbar()'.

Bluetooth app crashes on button press

I'm new to Android & was trying out the Bluetooth APIs of Google. Whenever I run my app on my phone, it crashes for some reason. I'm following the Google Developer's tutorial for the APIs & have made changes to my MainActivity.java & content.xml accordingly, but no use. Please have a look.
Here's my MainActivity.java
import android.content.Intent;
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.bluetooth.*;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private Button btn;
private BluetoothAdapter BA = BluetoothAdapter.getDefaultAdapter();
private int REQUEST_ENABLE_BT = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
/* FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});*/
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void bluetoothDiscovery()
{
if(BA == null)
{
System.out.println("System Doesn't Support Bluetooth");
}
if(!BA.isEnabled())
{
Intent enableBTIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBTIntent,REQUEST_ENABLE_BT);
Toast.makeText(MainActivity.this,"Turned On!!", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(MainActivity.this, "ALREADY ON", Toast.LENGTH_LONG).show();
}
}
}
Here's my AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="vertex2016.mvjce.edu.bluetoothapptry">
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Here's my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="vertex2016.mvjce.edu.bluetoothapptry.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
<!-- <android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email"
android:onClick="bluetoothDiscovery"/> -->
</android.support.design.widget.CoordinatorLayout>
Here's my content.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="vertex2016.mvjce.edu.bluetoothapptry.MainActivity"
tools:showIn="#layout/activity_main">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="BTButton"
android:id="#+id/button"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:onClick="bluetoothDiscovery"/>
</RelativeLayout>
And here's my logcat
03-13 02:06:34.719 18759-18759/vertex2016.mvjce.edu.bluetoothapptry E/AndroidRuntime: FATAL EXCEPTION: main
Process: vertex2016.mvjce.edu.bluetoothapptry, PID: 18759
java.lang.IllegalStateException: Could not find method bluetoothDiscovery(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'button'
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:307)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:266)
at android.view.View.performClick(View.java:4789)
at android.view.View$PerformClick.run(View.java:19881)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5292)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
Thank you for your time
Your method bluetoothDiscovery must accept a parameter of type View, see View.onClick for reference.
public void bluetoothDiscovery(View v) {}
When this method is called, v will be the View object that was clicked.
i.e.
switch ( v.getId() ) {
case R.id.button:
// do something
break;
case R.id.other_button
// do something else
break;
}
Where r.id.button comes from your definition in XML,
android:id="#+id/button"
It is using this, you could have a single onClick method that is called by multiple buttons, each one with their own action.
You need a View parameter in your onClick method
public void bluetoothDiscovery(View v)
Personally, I try not to add onClick in the XML because they are hard to find as you add more classes and layouts. You can just set the OnClickListener from the Java code for clearer visibility.

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>

android backward compatability error- java.lang.NoSuchMethod error

I want to provide backward compatability to android 2.2 versions.I have two classes(NoteList.java & NoteEdit.java) and its main components are Navigation drawer and Actionbar. The app is running well on android 4.2 & above versions but it crashes(force closes) on android 2.2..I've tried changing minsdkversion in manifest file and also tried adding support libraries(android.support.v7.appcompat) to libs folder and added to build path, but the app keeps on crashing.
NoteList.java
package com.example.notepad;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class NoteList extends Activity
{
private String[] mPlanetTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ListView mainList;
private ActionBarDrawerToggle actionBarDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.notelist);
mPlanetTitles = getResources().getStringArray(R.array.planets);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
final Animation anim = AnimationUtils.loadAnimation(this, R.anim.scale);
mainList = (ListView)findViewById(R.id.listView1);
mainList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mPlanetTitles));
ActionBar actionBar = getActionBar();
actionBar.show();
mainList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, final View view, final int position, long id) {
anim.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationRepeat(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
view.startAnimation(anim);
}
});
view.startAnimation(anim);
}
});
mDrawerList.setAdapter(new ArrayAdapter<String>(this,R.layout.drawer_list_item, mPlanetTitles));
actionBarDrawerToggle = new ActionBarDrawerToggle(this,
mDrawerLayout,
R.drawable.ic_launcher,
R.string.drawer_open,
R.string.drawer_close
);
mDrawerLayout.setDrawerListener(actionBarDrawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menus, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch(item.getItemId())
{
case R.id.new_note:
Intent intent = new Intent(NoteList.this,NoteEdit.class);
startActivity(intent);
default:
return super.onOptionsItemSelected(item);
}
}
}
Manifest file
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.notepad"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/appicon"
android:label="#string/app_name"
android:theme="#style/Theme.AppCompat.Light" >
<activity android:name=".NoteList"
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=".NoteEdit"
android:label="#string/app_name">
</activity>
</application>
</manifest>
Error Log
06-06 07:44:15.508: E/AndroidRuntime(339): FATAL EXCEPTION: main
06-06 07:44:15.508: E/AndroidRuntime(339): java.lang.NoSuchMethodError: com.example.notepad.NoteList.getActionBar
06-06 07:44:15.508: E/AndroidRuntime(339): at com.example.notepad.NoteList.onCreate(NoteList.java:39)
06-06 07:44:15.508: E/AndroidRuntime(339): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
06-06 07:44:15.508: E/AndroidRuntime(339): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
06-06 07:44:15.508: E/AndroidRuntime(339): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
06-06 07:44:15.508: E/AndroidRuntime(339): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
06-06 07:44:15.508: E/AndroidRuntime(339): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
06-06 07:44:15.508: E/AndroidRuntime(339): at android.os.Handler.dispatchMessage(Handler.java:99)
06-06 07:44:15.508: E/AndroidRuntime(339): at android.os.Looper.loop(Looper.java:123)
06-06 07:44:15.508: E/AndroidRuntime(339): at android.app.ActivityThread.main(ActivityThread.java:4627)
06-06 07:44:15.508: E/AndroidRuntime(339): at java.lang.reflect.Method.invokeNative(Native Method)
06-06 07:44:15.508: E/AndroidRuntime(339): at java.lang.reflect.Method.invoke(Method.java:521)
06-06 07:44:15.508: E/AndroidRuntime(339): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
06-06 07:44:15.508: E/AndroidRuntime(339): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
06-06 07:44:15.508: E/AndroidRuntime(339): at dalvik.system.NativeStart.main(Native Method)
notelist.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/notelist"
android:orientation="vertical" >
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- The main content view -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- The navigation drawer -->
<ListView android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#111"/>
<RelativeLayout
android:layout_width="214dp"
android:layout_height="322dp"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="48dp" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true">
</ListView>
</RelativeLayout>
</android.support.v4.widget.DrawerLayout>
</RelativeLayout>
You have to use getSupportActionBar() instead of getActionBar() for android api < 11.
Quoting the doc
"
Removing the action bar
You can hide the action bar at runtime by calling hide(). For example:
ActionBar actionBar = getSupportActionBar();
actionBar.hide();
On API level 11 or higher
Get the ActionBar with the getActionBar() method.
"
create a actionbar object and use it instead of getActionBar and getSupportActionBar..
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
Also add appCompat V7 library to your project and import it.

java.lang.NullPointerException Google Maps Android API V2

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.

Categories

Resources