NullPointerException - I don't understand what's wrong - android

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()'.

Related

Android: Default Tabbed Activity wont start when button is clicked

I know this has been asked a lot, already have done search on this particular topic. and all of them returns the same answer but doesn't solve my problem, I have a button created on separate xml, used as a fragment. TabbedActivity just wont fire up, App is crashing when button is clicked, even throws NPE on first code used. just don't know what to do.
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
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.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Set HomeFragment as user starts the app.
if (savedInstanceState == null){
InitStartFrag();
}
//-----BUG!-----//
1st:Code Used
android.support.v7.widget.AppCompatButton myButton = (android.support.v7.widget.AppCompatButton)findViewById(R.id.myButton);
myButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
Intent intent = new Intent(MainActivity.this, TabbedActivity.class);
startActivity(intent);
}
});
2nd Code:
public void doThis(View view){
Intent intent = new Intent(this, TabbedActivity.class);
MainActivity.this.startActivity(intent);
}
3rd Code:
public void doThis(View view){
setContentView(R.layout.activity_tabbed);
}
//-----Bug Ends-----//
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();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
private void InitStartFrag() {
android.app.FragmentManager fragmentManager = getFragmentManager();
android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
.....
.....
}
The Log Cat:
Process: com.my_app.app_one, PID: 3799
java.lang.IllegalStateException: Could not find a method doThis(View) in the activity class android.support.v7.widget.TintContextWrapper for onClick handler on view class android.support.v7.widget.AppCompatButton with id 'myButton'
at android.view.View$1.onClick(View.java:3843)
at android.view.View.performClick(View.java:4471)
at android.view.View$PerformClick.run(View.java:18778)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5324)
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:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NoSuchMethodException: doThis [class android.view.View]
at java.lang.Class.getConstructorOrMethod(Class.java:472)
at java.lang.Class.getMethod(Class.java:864)
at android.view.View$1.onClick(View.java:3836)
at android.view.View.performClick(View.java:4471) 
at android.view.View$PerformClick.run(View.java:18778) 
at android.os.Handler.handleCallback(Handler.java:808) 
at android.os.Handler.dispatchMessage(Handler.java:103) 
at android.os.Looper.loop(Looper.java:193) 
at android.app.ActivityThread.main(ActivityThread.java:5324) 
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:824) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640) 
at dalvik.system.NativeStart.main(Native Method) 
The Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.my_app.app_one">
<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:configChanges="keyboardHidden|orientation"
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>
<activity
android:name=".TabbedActivity"
android:label="#string/title_activity_tabbed"
android:parentActivityName=".MainActivity"
android:theme="#style/AppTheme.NoActionBar">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.my_app.app_one.MainActivity" />
</activity>
</application>
</manifest>
The XML, used as Fragment : buttons_layout.xml
<?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" >
<android.support.percent.PercentRelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!--Upper Buttons-->
<android.support.v7.widget.AppCompatButton
android:id="#+id/myButton"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_gravity="center_horizontal"
android:text="Fire"
android:textSize="15sp"
app:layout_heightPercent="25%"
app:layout_widthPercent="50%"
app:backgroundTint="#color/colorBtn1"
android:textColor="#color/colorBtnText1"
android:drawableStart="#drawable/fire_icon"
android:drawablePadding="-62dip"
android:paddingLeft="30dip"
android:paddingRight="26dip"
android:singleLine="true"
android:gravity="center"
android:onClick="doThis"/>
<android.support.v7.widget.AppCompatButton
android:id="#+id/myButton1"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_gravity="center_horizontal"
android:layout_below="#id/myButton"
android:text="Flood"
android:textSize="15sp"
app:layout_heightPercent="25%"
app:layout_widthPercent="50%"
app:backgroundTint="#color/colorBtn3"
android:textColor="#color/colorBtnText3"/>
<!-- Divider -->
<android.support.v7.widget.AppCompatButton
android:id="#+id/myButton2"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_gravity="center_horizontal"
android:layout_toEndOf="#id/myButton1"
android:text="Thunder"
android:textSize="15sp"
app:layout_heightPercent="25%"
app:layout_widthPercent="50%"
app:backgroundTint="#color/colorBtn2"
android:textColor="#color/colorBtnText2"/>
<android.support.v7.widget.AppCompatButton
android:id="#+id/myButton4"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_below="#id/myButton2"
android:layout_gravity="center_horizontal"
android:layout_toEndOf="#id/myButton1"
android:text="Civil Defense Operation Center"
android:textSize="15sp"
app:layout_heightPercent="25%"
app:layout_widthPercent="50%"
app:backgroundTint="#color/colorBtn4"
android:textColor="#color/colorBtnText4"/>
<!--Lower Buttons-->
<android.support.v7.widget.AppCompatButton
android:id="#+id/myButton5"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_gravity="center_horizontal"
android:layout_below="#id/myButton3"
android:text="Landslide"
android:textSize="15sp"
app:layout_heightPercent="25%"
app:layout_widthPercent="50%"
app:backgroundTint="#color/colorBtn5"
android:textColor="#color/colorBtnText5"/>
<android.support.v7.widget.AppCompatButton
android:id="#+id/myButton7"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_gravity="center_horizontal"
android:layout_below="#id/myButton5"
android:text="Women and Children Protection Center"
android:textSize="15sp"
app:layout_heightPercent="25%"
app:layout_widthPercent="50%"
app:backgroundTint="#color/colorBtn7"
android:textColor="#color/colorBtnText7"/>
<!-- Divider -->
<android.support.v7.widget.AppCompatButton
android:id="#+id/myButton6"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_gravity="center_horizontal"
android:layout_below="#id/myButton4"
android:layout_toEndOf="#id/myButton3"
android:text="Storm"
android:textSize="15sp"
app:layout_heightPercent="25%"
app:layout_widthPercent="50%"
app:backgroundTint="#color/colorBtn6"
android:textColor="#color/colorBtnText6"/>
<android.support.v7.widget.AppCompatButton
android:id="#+id/myButton8"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_below="#id/myButton6"
android:layout_gravity="center_horizontal"
android:layout_toEndOf="#id/myButton5"
android:text="Earthquake"
android:textSize="15sp"
app:layout_heightPercent="25%"
app:layout_widthPercent="50%"
app:backgroundTint="#color/colorBtn8"
android:textColor="#color/colorBtnText8"/>
</android.support.percent.PercentRelativeLayout>
</LinearLayout>
New Code Used:
private void InitBtnListener(){
LayoutInflater layoutInflater = this.getLayoutInflater();
View view = layoutInflater.inflate(R.layout.buttons_layout,null);
android.support.v7.widget.AppCompatButton myButton = (android.support.v7.widget.AppCompatButton)view.findViewById(R.id.myButton);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, TabbedActivity.class);
startActivity(intent);
}
});
}
TabbedFragment.java Code
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
public class TabbedFragment extends Fragment implements OnClickListener {
View myView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.survival_tips_layout,container,false);
android.support.v7.widget.AppCompatButton myButton = (android.support.v7.widget.AppCompatButton)myView.findViewById(R.id.myButton);
myButton.setOnClickListener(this);
return myView;
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.myButton:
//--Missing Code:--//
After Btn Click Fire up that TabbedActivity.
//--Ends--//
// Can I do intents Here?
Intent intent = new Intent(MainActivity.this,TabbedActivity.class);
startActivity(intent);
break;
}
}
}
This line needs to be above any findViewById
setContentView(R.layout.activity_main);
If the android:onClick is defined from the XML, you need a public method that accepts a View parameter with that name.
For example, android:onClick="doThis" means you need this method
public void doThis(View view) {
// TODO: Handle click
}
i have a button created on separate xml, used as a fragment
Then you need to find that button from the Fragment class. You can't find it from the Activity.
For example
public class MyFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
// Inflate the layout
View rootView = inflater.inflate(R.layoutbuttons_layout, parentViewGroup, false);
Button button = (Button) rootView.findViewById(R.id.button);
// TODO: button.setOnClickListener();
return rootView;
}
// OR... if you have android:onclick="doThis"
public void doThis(View view) {
// TODO: Handle click
}
}

Getting error while running an activity with custom navigation drawer

Im getting error when i try to run the below activity.
The activity has a custom navigation drawer.
I'm new to android ....
The error is occuring at places where actionbar is involved.
Im getting error when i try to run the below activity.
The activity has a custom navigation drawer.
I'm new to android ....
The error is occuring at places where actionbar is involved.
Im getting error when i try to run the below activity.
The activity has a custom navigation drawer.
I'm new to android ....
The error is occuring at places where actionbar is involved.
Activity
import android.app.ActionBar;
import android.content.Context;
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.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class HomeActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
DrawerLayout drawer_layout;
ListView drawer_list;
ActionBarDrawerToggle drawer_toggle;
ActionBar abar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
drawer_layout= (DrawerLayout) findViewById(R.id.drawer_layout);
drawer_list= (ListView) findViewById(R.id.drawer_list);
drawer_list.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1));
drawer_list.setOnItemClickListener(this);
abar=getActionBar();
/*drawer_toggle = new ActionBarDrawerToggle(this, drawer_layout,
R.drawable.tick, R.string.app_name, R.string.app_name) {
*//** Called when a drawer has settled in a completely closed state. *//*
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getActionBar().setTitle("Yuride");
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
*//** Called when a drawer has settled in a completely open state. *//*
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActionBar().setTitle("Yuride");
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};*/
abar.setHomeButtonEnabled(true);
abar.setDisplayHomeAsUpEnabled(true);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
class Myadapter extends BaseAdapter
{
Context context;
String[] drawer_items;
public Myadapter(Context context)
{
this.context=context;
drawer_items=context.getResources().getStringArray(R.array.drawer_items);
}
#Override
public int getCount() {
return drawer_items.length;
}
#Override
public Object getItem(int position) {
return drawer_items[position];
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row=null;
if(convertView==null)
{
LayoutInflater inflater= (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row=inflater.inflate(R.layout.drawer_row,parent,false);
}
else
{
row=convertView;
}
ImageView drawer_icon= (ImageView) row.findViewById(R.id.drawer_icon);
TextView drawer_text= (TextView) row.findViewById(R.id.drawer_text);
drawer_text.setText(drawer_items[position]);
drawer_icon.setImageResource(R.drawable.tick);
return null;
}
}
}
xml
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawer_layout">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
<ListView
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="left"
android:id="#+id/drawer_list">
</ListView>
</android.support.v4.widget.DrawerLayout>
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="in.yusoft.yuride.yuride">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".SplashActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Entrance" />
<activity android:name=".HomeActivity"></activity>
</application>
</manifest>
Error
java.lang.RuntimeException: Unable to start activity ComponentInfo{in.yusoft.yuride.yuride/in.yusoft.yuride.yuride.HomeActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setHomeButtonEnabled(boolean)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2622)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2683)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1440)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:6066)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:770)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:660)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setHomeButtonEnabled(boolean)' on a null object reference
at in.yusoft.yuride.yuride.HomeActivity.onCreate(HomeActivity.java:52)
at android.app.Activity.performCreate(Activity.java:6584)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2575)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2683) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1440) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:6066) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:770) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:660) 
The problem is in setting up ActionBar.
Instead of
abar=getActionBar();
abar.setHomeButtonEnabled(true);
abar.setDisplayHomeAsUpEnabled(true);
Write in XML:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawer_layout">
<android.support.design.widget.AppBarLayout
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
android:theme="#style/MyMaterialTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="#style/MyMaterialTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
<ListView
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="left"
android:id="#+id/drawer_list">
</ListView>
</android.support.v4.widget.DrawerLayout>
And in Java Class right after setContentView(R.layout.activity_home);:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if(getSupportActionBar()!=null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

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>

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.

Categories

Resources