App crashing in Android emulator in android studio (2.2.3) - java

I am trying to make an app whcih displays the values of x,y,z of accelerometer.
I have this code in my activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="92dp"
android:layout_marginTop="114dp"
android:text="TextView" />
</RelativeLayout>
The following is the MainActivity.java code:
package com.example.sensorsimple;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import android.hardware.SensorManager;
import android.hardware.SensorEventListener;
import android.hardware.SensorEvent;
import android.hardware.Sensor;
import java.util.List;
public class MainActivity extends Activity {
SensorManager sm = null;
TextView accText = null;
List list;
/* This responds to sensor events */
SensorEventListener sel = new SensorEventListener(){
public void onAccuracyChanged(Sensor sensor, int accuracy) {
/* Isn't required for this example */
}
public void onSensorChanged(SensorEvent event) {
/* Write the accelerometer values to the TextView */
float[] values = event.values;
accText.setText("x: "+values[0]+"\ny: "+values[1]+"\nz: "+values[2]);
}
};
/* Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* Get a SensorManager instance */
sm = (SensorManager)getSystemService(SENSOR_SERVICE);
/* This corresponds to a TextView element in main.xml with android:id="#+id/accText" */
accText = (TextView)findViewById(R.id.textView1);
/* Get list of accelerometers */
list = sm.getSensorList(Sensor.TYPE_ACCELEROMETER);
/* If there are any accelerometers register a listener to the first else
print a little error message */
if(list.size()>0){
sm.registerListener(sel, (Sensor) list.get(0), SensorManager.SENSOR_DELAY_NORMAL);
}else{
Toast.makeText(getBaseContext(), "Error: No Accelerometer.", Toast.LENGTH_LONG);
}
}
#Override
protected void onStop() {
/* Always a good idea to unregister, disconnect, close, etc things */
if(list.size()>0){
/* This actually unregisters a listener for all sensors, but it can be done
on a sensor by sensor basis */
sm.unregisterListener(sel);
}
super.onStop();
}
When I run this AVD in the android studio (API 24, Android N), the app crashes with the error [APP name] has stopped on the emulator screen.How to run this?
This is what I get as error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.sid.javatpoint_sensor_values, PID: 15266
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.sid.javatpoint_sensor_values/com.example.sid.javatpoint_sensor_values.MainActivity}: java.lang.ClassNotFoundException: Didn't find class "com.example.sid.javatpoint_sensor_values.MainActivity" on path: DexPathList[[zip file "/data/app/com.example.sid.javatpoint_sensor_values-2/base.apk"],nativeLibraryDirectories=[/data/app/com.example.sid.javatpoint_sensor_values-2/lib/x86, /system/lib, /vendor/lib]]
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2548)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.example.sid.javatpoint_sensor_values.MainActivity" on path: DexPathList[[zip file "/data/app/com.example.sid.javatpoint_sensor_values-2/base.apk"],nativeLibraryDirectories=[/data/app/com.example.sid.javatpoint_sensor_values-2/lib/x86, /system/lib, /vendor/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2538)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 

You should check your AndroidManifest.xml file, because it tries to find com.example.sid.javatpoint_sensor_values.MainActivity and your MainActivity is placed in com.example.sensorsimple package.
If your AndroidManifest.xml is ok, try to clean your project

Related

Android app crash(Media Player)

I am trying to make a simple media player app which has three buttons play,pause and stop,but when i launch the app on emulator and if i click any of the buttons,app crashes.I am not able to figure out where is the error.
below is my .java and .xml file...
.Java
package com.example.android.songdemo;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
MediaPlayer mp;
public void songPlay(View view){
mp.start();
}
public void songPause(View view){
mp.pause();
}
public void songStop(View view){
mp.stop();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MediaPlayer mp=MediaPlayer.create(this,R.raw.laugh);
}
}
.xml
<?xml version="1.0" encoding="utf-8"?>
<android.widget.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"
tools:context="com.example.android.songdemo.MainActivity">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/button2"
android:layout_toStartOf="#+id/button2"
android:onClick="songPlay"
android:text="play"
/>
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/button"
android:layout_marginEnd="65dp"
android:layout_marginRight="65dp"
android:layout_marginTop="110dp"
android:onClick="songPause"
android:text="pause"
tools:layout_editor_absoluteX="117dp"
tools:layout_editor_absoluteY="76dp" />
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/button2"
android:layout_alignBottom="#+id/button2"
android:layout_toLeftOf="#+id/button"
android:layout_toStartOf="#+id/button"
android:onClick="songStop"
android:text="stop"
tools:layout_editor_absoluteX="117dp"
tools:layout_editor_absoluteY="145dp" />
Can someone find out what is the error.
Below is the Log....
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:6294)
at android.view.View$PerformClick.run(View.java:24770)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:6294) 
at android.view.View$PerformClick.run(View.java:24770) 
at android.os.Handler.handleCallback(Handler.java:790) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6494) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) 
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference
at com.example.android.songdemo.MainActivity.songPlay(MainActivity.java:16)
As you are creating MediaPlayer mp=MediaPlayer.create(this,R.raw.laugh); in your onCreate() callback it will be local to onCreate() callback
Change:-
package com.example.android.songdemo;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
MediaPlayer mp;
public void songPlay(View view){
mp.start();
}
public void songPause(View view){
mp.pause();
}
public void songStop(View view){
mp.stop();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mp=MediaPlayer.create(this,R.raw.laugh);
}
}
You need to remove the local initialization of MediaPlayer as if you initialize it locally the scope will be null when you click on the buttons as it is not globally initialized.
If you initialize the MediaPlayer locally and you try to do the operations of MediaPlayer outside the scope it will give you null object reference
package com.example.android.songdemo;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
private MediaPlayer mp;
public void songPlay(View view){
mp.start();
}
public void songPause(View view){
mp.pause();
}
public void songStop(View view){
mp.stop();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mp=MediaPlayer.create(this,R.raw.laugh); // removed the local initialization
}
}

How do I add a LinearLayoutCompat view to an existing xml layout dynamically?

I have a database containing of Texts.My activity has a TextView at the top(this should be constantly intact throughout) and below that I have a RelativeLayout which will be my container. In my code, as soon as the activity (in which I will be inserting view dynamically) launches, I create a LinearLayoutCompact object and set some properties. Then I process the cursor to the table data and I create a TextView for each database element and add it to the LinearLayoutCompat object. Finally I try to add this object into the RelativeLayout container where the app crashes. I am using LayoutInflater and treating the RelativeLayout container as a ViewGroup (I found this way after doing some research). However, if I simply use setContentView on the LinearLayoutCompat object it works fine but also replaces that TextView I want to be present. Here are the files I think will be necessary :
veg_option.xml (layout of my activity)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView <!-- The one I want intact throughout -->
android:id="#+id/narrowText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Let's narrow down now !"
android:textSize="20sp"
android:textColor="#color/wineBrown"
android:gravity="center"
android:padding="10dp"
android:layout_marginTop="30dp"
android:elevation="4dp"/>
<RelativeLayout <!-- Trying to use this as container -->
android:id="#+id/dataCont"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
</RelativeLayout>
</LinearLayout>
VegOptions.java (The activity where all action is supposed to happen)
package com.techpappy.whattoeat;
/**
* Created by Mehul on 31-05-2017.
*/
import android.content.Context;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Typeface;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.AppCompatTextView;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.util.ArrayList;
public class VegOptions extends AppCompatActivity{
protected DBSource vegDBSource;
private Cursor cursor;
protected ArrayList<String> mTypes;
LayoutInflater li = (LayoutInflater)getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = li.inflate(R.layout.veg_option, null);
ViewGroup dataConPt = (ViewGroup) findViewById(R.id.dataCont);
#Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.veg_option);
vegDBSource = new DBSource(VegOptions.this);
disp();
}
private void disp()
{
vegDBSource.open();
cursor = vegDBSource.getInfo();
LinearLayoutCompat linearLayoutCompat = defaultPage(cursor);
//setContentView(linearLayoutCompat); Works fine but replaces all
dataConPt.addView(linearLayoutCompat);
}
//Here my LinearLayoutCompat object is prepared and returned
public LinearLayoutCompat defaultPage(Cursor mCursor) {
LinearLayoutCompat layout = new LinearLayoutCompat(this);
LinearLayoutCompat.LayoutParams params = new LinearLayoutCompat.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT);
layout.setLayoutParams(params);
layout.setGravity(Gravity.CENTER);
layout.setOrientation(LinearLayoutCompat.VERTICAL);
mCursor.moveToFirst(); //Each iteration adds one TextView
do {
AppCompatTextView defaultText = new AppCompatTextView(this);
defaultText.setText(mCursor.getString(mCursor.getColumnIndex(DataBaseHelper.COLUMN_TYPES)));
defaultText.setTextAppearance(getApplicationContext(), R.style.TextFontMain);
defaultText.setTextSize(30);
defaultText.setPadding(0,30,0,30);
final String temp = (String) defaultText.getText();
defaultText.setGravity(Gravity.CENTER);
defaultText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(getApplicationContext(), temp, Toast.LENGTH_SHORT).show();
}
});
layout.addView(defaultText);
mCursor.moveToNext();
} while(mCursor.isAfterLast() == false);
return layout; //LinearLayoutCompat containing all Texts returned
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
vegDBSource.close();
overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
}
}
My previous questions have been downvoted but this time I have done a fair amount of research and found the correct way but I can't get it to work in my unique case
stacktrace
6-05 19:32:17.679 3450-3450/com.techpappy.whattoeat E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.techpappy.whattoeat, PID: 3450
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.techpappy.whattoeat/com.techpappy.whattoeat.VegOptions}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2567)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:106)
at com.techpappy.whattoeat.VegOptions.<init>(VegOptions.java:33)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2557)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6119) 
at java.lang.reflect.Method.invoke(Native Method) 
Simply initialized the LayoutInflator, View and the ViewGroup inside the onCreate() method and the problem was fixed.

Physical Device only - Google Maps - 'File.mkdir()' on a null object reference

I am running my code and getting this error when using app on mobile devide, but on emulator it is working.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.nirbhaym.Indoor, PID: 17543
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.nirbhaym.Indoor/com.example.nirbhaym.indoor.MapsActivity}: android.view.InflateException: Binary XML file line #62: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2335)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2397)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1310)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5268)
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:902)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697)
Caused by: android.view.InflateException: Binary XML file line #62: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:763)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:256)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109)
at com.example.nirbhaym.indoor.MapsActivity.onCreate(MapsActivity.java:50)
at android.app.Activity.performCreate(Activity.java:6033)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2288)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2397) 
at android.app.ActivityThread.access$800(ActivityThread.java:151) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1310) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5268) 
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:902) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697) 
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.io.File.mkdir()' on a null object reference
at com.google.maps.api.android.lib6.gmm6.m.ad.a(Unknown Source)
at com.google.maps.api.android.lib6.gmm6.c.h.a(Unknown Source)
at com.google.maps.api.android.lib6.gmm6.c.y.a(Unknown Source)
at com.google.maps.api.android.lib6.e.bd.a(Unknown Source)
at com.google.maps.api.android.lib6.e.ev.a(Unknown Source)
at com.google.maps.api.android.lib6.e.z.a(Unknown Source)
at com.google.maps.api.android.lib6.e.y.a(Unknown Source)
at com.google.android.gms.maps.internal.u.onTransact(SourceFile:107)
at android.os.Binder.transact(Binder.java:380)
at com.google.android.gms.maps.internal.IMapFragmentDelegate$zza$zza.onCreateView(Unknown Source)
at com.google.android.gms.maps.SupportMapFragment$zza.onCreateView(Unknown Source)
at com.google.android.gms.dynamic.zza$4.zzb(Unknown Source)
at com.google.android.gms.dynamic.zza.zza(Unknown Source)
at com.google.android.gms.dynamic.zza.onCreateView(Unknown Source)
at com.google.android.gms.maps.SupportMapFragment.onCreateView(Unknown Source)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1036)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1226)
at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1328)
at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2284)
at android.support.v4.app.FragmentController.onCreateView(FragmentController.java:111)
at android.support.v4.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:314)
at android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:31)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:79)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:733)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:806) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:504) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:414) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:365) 
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:256) 
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109) 
at com.example.nirbhaym.indoor.MapsActivity.onCreate(MapsActivity.java:50) 
at android.app.Activity.performCreate(Activity.java:6033) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2288) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2397) 
at android.app.ActivityThread.access$800(ActivityThread.java:151) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1310) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5268) 
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:902) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697) 
I/Process: Sending signal. PID: 17543 SIG: 9
Application terminated.
Main activity code
package com.example.nirbhaym.indoor;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.GroundOverlay;
import com.google.android.gms.maps.model.GroundOverlayOptions;
import com.google.android.gms.maps.model.LatLng;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import java.util.ArrayList;
import java.util.List;
/**
* This shows how to add a ground overlay to a map.
*/
public class MapsActivity extends AppCompatActivity
implements OnSeekBarChangeListener, OnMapReadyCallback,
GoogleMap.OnGroundOverlayClickListener {
private static final int TRANSPARENCY_MAX = 100;
private static final LatLng NEWARK = new LatLng(28.544594, 77.272486);
private static final LatLng NEAR_NEWARK =
new LatLng(NEWARK.latitude - 0.001, NEWARK.longitude - 0.025);
private final List<BitmapDescriptor> mImages = new ArrayList<BitmapDescriptor>();
private GroundOverlay mGroundOverlay;
private GroundOverlay mGroundOverlayRotated;
private SeekBar mTransparencyBar;
private int mCurrentEntry = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
mTransparencyBar = (SeekBar) findViewById(R.id.transparencySeekBar);
mTransparencyBar.setMax(TRANSPARENCY_MAX);
mTransparencyBar.setProgress(0);
SupportMapFragment mapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap map) {
// Register a listener to respond to clicks on GroundOverlays.
map.setOnGroundOverlayClickListener(this);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(NEWARK, 11));
mImages.clear();
mImages.add(BitmapDescriptorFactory.fromResource(R.drawable.fourth_floor_app));
//mImages.add(BitmapDescriptorFactory.fromResource(R.drawable.newark_prudential_sunny));
// Add a small, rotated overlay that is clickable by default
// (set by the initial state of the checkbox.)
mGroundOverlayRotated = map.addGroundOverlay(new GroundOverlayOptions()
.image(mImages.get(0)).anchor(0, 1)
.position(NEAR_NEWARK, 4300f, 3025f)
.bearing(30)
.clickable(((CheckBox) findViewById(R.id.toggleClickability)).isChecked()));
// Add a large overlay at Newark on top of the smaller overlay.
mGroundOverlay = map.addGroundOverlay(new GroundOverlayOptions()
.image(mImages.get(mCurrentEntry)).anchor(0, 1)
.position(NEWARK, 8600f, 6500f));
mTransparencyBar.setOnSeekBarChangeListener(this);
// Override the default content description on the view, for accessibility mode.
// Ideally this string would be localised.
map.setContentDescription("Google Map with ground overlay.");
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (mGroundOverlay != null) {
mGroundOverlay.setTransparency((float) progress / (float) TRANSPARENCY_MAX);
}
}
public void switchImage(View view) {
mCurrentEntry = (mCurrentEntry + 1) % mImages.size();
mGroundOverlay.setImage(mImages.get(mCurrentEntry));
}
/**
* Toggles the visibility between 100% and 50% when a {#link GroundOverlay} is clicked.
*/
#Override
public void onGroundOverlayClick(GroundOverlay groundOverlay) {
// Toggle transparency value between 0.0f and 0.5f. Initial default value is 0.0f.
mGroundOverlayRotated.setTransparency(0.5f - mGroundOverlayRotated.getTransparency());
}
/**
* Toggles the clickability of the smaller, rotated overlay based on the state of the View that
* triggered this call.
* This callback is defined on the CheckBox in the layout for this Activity.
*/
public void toggleClickability(View view) {
if (mGroundOverlayRotated != null) {
mGroundOverlayRotated.setClickable(((CheckBox) view).isChecked());
}
}
}
Layout file
<?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">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/fourth_floor_app"
android:padding="5dp">
<TextView
android:id="#+id/transparency_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:text="string/transparency" />
<SeekBar
android:id="#+id/transparencySeekBar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toEndOf="#+id/transparency_text"
android:layout_toRightOf="#+id/transparency_text" />
<Button
android:id="#+id/switchImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/transparencySeekBar"
android:onClick="switchImage"
android:text="string/switch_image" />
<CheckBox
android:id="#+id/toggleClickability"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/switchImage"
android:layout_toEndOf="#+id/switchImage"
android:layout_toRightOf="#+id/switchImage"
android:checked="true"
android:onClick="toggleClickability"
android:text="string/clickable" />
</RelativeLayout>
<fragment
android:id="#+id/map"
class="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
FragmentManager fmanager = getSupportFragmentManager();
Fragment fragment = fmanager.findFragmentById(R.id.map);
SupportMapFragment supportmapfragment = (SupportMapFragment)fragment;
GoogleMap supportMap = supportmapfragment.getMap();
try this code. For this the tutorial is here hope this helps you. The problem is in fragment only. You need to check permissions also in above tutorial. Hope it helps you
http://www.truiton.com/2013/05/android-supportmapfragment-example/
EDIT:
Check permission for External Storage:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Android - Trying to instantiate a class that is not a fragment

So I'm trying to create a fragment in my app that contains a toolbar (as an action bar) using appcompat activity so I can reuse it across multiple views.
I've tested a simple text-only fragment using a class that extends fragment only and got that to work, but to include a toolbar I need to extend AppCompatActivity in the view (I think).
When I try to get this to work, I get an error that says that my action_bar_fragment is not a Fragment.
I fell like I'm missing something basic here. Any ideas?
Main Activity:
package com.example.aaron.personaldataassistant;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.support.v7.widget.Toolbar;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.view.Menu;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// action_bar_fragment = (Toolbar) findViewById(R.id.action_bar_fragment);
// setSupportActionBar(action_bar_fragment);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater mi=getMenuInflater();
mi.inflate(R.menu.action_bar, menu);
return super.onCreateOptionsMenu(menu);
}
Main Activity Layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:id="#+id/activity_main"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.aaron.personaldataassistant.MainActivity">
<fragment
android:id="#+id/action_bar_fragment"
android:layout_width="wrap_content"
android:layout_height="match_parent"
class="com.example.aaron.personaldataassistant.action_bar_fragment"
tools:layout="#layout/action_bar_fragment" />
</LinearLayout>
Action Bar Fragment:
package com.example.aaron.personaldataassistant;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
public class action_bar_fragment extends AppCompatActivity {
public action_bar_fragment() {
}
Toolbar action_bar;
#Nullable
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.action_bar_fragment, container, false);
}
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.action_bar_fragment);
action_bar = (Toolbar) findViewById(R.id.action_bar);
setSupportActionBar(action_bar);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.action_bar, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int i = item.getItemId();
if (i == R.id.item1) {
Toast.makeText(action_bar_fragment.this, "Item 1", Toast.LENGTH_SHORT).show();
} else if (i == R.id.item2) {
Toast.makeText(action_bar_fragment.this, "Item 2", Toast.LENGTH_SHORT).show();
} else if (i == R.id.item3) {
Toast.makeText(action_bar_fragment.this, "Item 3", Toast.LENGTH_SHORT).show();
}
//replace toasts with desired actions: Settings, Help and Exit. Settigns is blank, help is context-dependent, exit gives possibility to exit
return super.onOptionsItemSelected(item);
}
}
Fragment Layout:
<FrameLayout 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"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="layout.Fragment_1">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/hello_blank_fragment" />
<android.support.v7.widget.Toolbar
android:id="#+id/action_bar"
android:layout_width="300dp"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimaryDark"
android:elevation="8dp"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
/>
</FrameLayout>
And of course the error message:
--------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.aaron.personaldataassistant, PID: 2481
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.aaron.personaldataassistant/com.example.aaron.personaldataassistant.MainActivity}: android.view.InflateException: Binary XML file line #19: Binary XML file line #19: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: android.view.InflateException: Binary XML file line #19: Binary XML file line #19: Error inflating class fragment
Caused by: android.view.InflateException: Binary XML file line #19: Error inflating class fragment
Caused by: android.app.Fragment$InstantiationException: Trying to instantiate a class com.example.aaron.personaldataassistant.action_bar_fragment that is not a Fragment
at android.app.Fragment.instantiate(Fragment.java:617)
at android.app.Fragment.instantiate(Fragment.java:593)
at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2302)
at android.app.FragmentController.onCreateView(FragmentController.java:98)
at android.app.Activity.onCreateView(Activity.java:5884)
at android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:36)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:75)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:777)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:858)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
at android.view.LayoutInflater.inflate(LayoutInflater.java:426)
at android.view.LayoutInflater.inflate(LayoutInflater.java:377)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:284)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at com.example.aaron.personaldataassistant.MainActivity.onCreate(MainActivity.java:24)
at android.app.Activity.performCreate(Activity.java:6662)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.ClassCastException
at android.app.Fragment.instantiate(Fragment.java:618)
at android.app.Fragment.instantiate(Fragment.java:593) 
at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2302) 
at android.app.FragmentController.onCreateView(FragmentController.java:98) 
at android.app.Activity.onCreateView(Activity.java:5884) 
at android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:36) 
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:75) 
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:777) 
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727) 
at android.view.LayoutInflater.rInflate(LayoutInflater.java:858) 
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:518) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:426) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:377) 
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:284) 
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140) 
at com.example.aaron.personaldataassistant.MainActivity.onCreate(MainActivity.java:24) 
at android.app.Activity.performCreate(Activity.java:6662) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
Application terminated.
Thank you for your time.
UPDATE
This is great, the top answer helped me figure out that doing things in a fragment can require different methods than doing them in an Activity. Googling "How do I do X in a fragment" turned out to give me almost everything I needed. There is only one problem left now: I changed the Action Bar Fragment line 37 to
setHasOptionsMenu(true);
action_bar = (Toolbar) getView().findViewById(R.id.action_bar);
This is giving me a null object reference, but the layout definitely exists! Any idea what's going on?
The relevant part of the error message is:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
Sorry for the long delay getting back to you, I had work. Should be faster this time!
I will also clean up the comment I made on your reply.
This is because your intended fragment is not a Fragment but an Activity, where:
action_bar_fragment extends AppCompatActivity {
}
is an Activity, so you should be extends action_bar_fragment with Fragment:
action_bar_fragment extends Fragment {
}
And please change your code style, where action_bar_fragment should be something like ActionBarFragment. A class name should be started with uppercase.
Please read Creating and Using Fragments.
I came upon this question because of the main title "Trying to instantiate a class that is not a Fragment". So maybe my solution can help. I'm using Android Studio 2.2.3 and targeting API 15.
I got that error:
...
Caused by: android.app.Fragment$InstantiationException: Trying to instantiate a class com.xyz.tuv.MyFragment that is not a Fragment
because I was importing:
import android.support.v4.app.Fragment;
instead of
import android.app.Fragment;
Since API 11, you can use a regular activity (android.app.Activity) for inserting fragments as documented here. But in that case you also have to use android.app.Fragment, contrary to what the main example shows.
In your MainActivity class, you have to change the order of some of code, they are:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater mi=getMenuInflater();
mi.inflate(R.menu.action_bar, menu);
return super.onCreateOptionsMenu(menu);
}
Change it to :
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.action_bar, menu);
return true;
}
and try again.

Class not found when unmarshalling: android.support.v7.widget.Toolbar$SavedState

i am using Maps API to create a simple android app and i get a wierd error i can't solve. It usually happens when i rotate my device. I'm using google services 8.4.0
4-23 15:39:47.503 9419-9419/com.licenta.vladut.mmap E/Parcel: Class not found when unmarshalling: android.support.v7.widget.Toolbar$SavedState
java.lang.ClassNotFoundException: android.support.v7.widget.Toolbar$SavedState
at java.lang.Class.classForName(Native Method)
at java.lang.Class.forName(Class.java:308)
at android.os.Parcel.readParcelableCreator(Parcel.java:2275)
at android.os.Parcel.readParcelable(Parcel.java:2239)
at android.os.Parcel.readValue(Parcel.java:2146)
at android.os.Parcel.readSparseArrayInternal(Parcel.java:2540)
at android.os.Parcel.readSparseArray(Parcel.java:1868)
at android.os.Parcel.readValue(Parcel.java:2203)
at android.os.Parcel.readArrayMapInternal(Parcel.java:2479)
at android.os.BaseBundle.unparcel(BaseBundle.java:221)
at android.os.Bundle.getBundle(Bundle.java:782)
at com.google.android.gms.maps.internal.ao.a(:com.google.android.gms.alldynamite:74)
at maps.ei.bu.a(Unknown Source)
at maps.ei.n.a(Unknown Source)
at com.google.android.gms.maps.internal.i$a.onTransact(:com.google.android.gms.alldynamite:107)
at android.os.Binder.transact(Binder.java:380)
at com.google.android.gms.maps.internal.IMapFragmentDelegate$zza$zza.onCreateView(Unknown Source)
at com.google.android.gms.maps.SupportMapFragment$zza.onCreateView(Unknown Source)
at com.google.android.gms.dynamic.zza$4.zzb(Unknown Source)
at com.google.android.gms.dynamic.zza.zza(Unknown Source)
at com.google.android.gms.dynamic.zza.onCreateView(Unknown Source)
at com.google.android.gms.maps.SupportMapFragment.onCreateView(Unknown Source)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1036)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1230)
at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2315)
at android.support.v4.app.FragmentController.onCreateView(FragmentController.java:120)
at android.support.v4.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:357)
at android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:31)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:80)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:733)
at android.view.LayoutInflater.inflate(LayoutInflater.java:482)
at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:276)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:136)
at com.licenta.vladut.mmap.MainActivity.onCreate(MainActivity.java:54)
at android.app.Activity.performCreate(Activity.java:6020)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2259)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2368)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3947)
at android.app.ActivityThread.access$900(ActivityThread.java:149)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1290)
at android.os.Handler.dispatchMessage(Handler.java:102)
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:908)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)
Caused by: java.lang.ClassNotFoundException: Didn't find class "android.support.v7.widget.Toolbar$SavedState" on path: DexPathList[[zip file "/data/data/com.google.android.gms/app_chimera/m/00000000/DynamiteModules-prod.apk"],nativeLibraryDirectories=[/data/data/com.google.android.gms/app_chimera/m/00000000/n/armeabi-v7a, /vendor/lib, /system/lib]]
at dalvik.system.BaseDexClassLoader.f
04-23 15:39:47.503 9419-9419/com.licenta.vladut.mmap D/AndroidRuntime: Shutting down VM
04-23 15:39:47.505 9419-9419/com.licenta.vladut.mmap E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.licenta.vladut.mmap, PID: 9419
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.licenta.vladut.mmap/com.licenta.vladut.mmap.MainActivity}: android.view.InflateException: Binary XML file line #2: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2306)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2368)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3947)
at android.app.ActivityThread.access$900(ActivityThread.java:149)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1290)
at android.os.Handler.dispatchMessage(Handler.java:102)
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:908)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)
Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:763)
at android.view.LayoutInflater.inflate(LayoutInflater.java:482)
at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:276)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:136)
at com.licenta.vladut.mmap.MainActivity.onCreate(MainActivity.java:54)
at android.app.Activity.performCreate(Activity.java:6020)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2259)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2368) 
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3947) 
at android.app.ActivityThread.access$900(ActivityThread.java:149) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1290) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
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:908) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703) 
Caused by: android.os.BadParcelableException: ClassNotFoundException when unmarshalling: android.support.v7.widget.Toolbar$SavedState
at android.os.Parcel.readParcelableCreator(Parcel.java:2289)
at android.os.Parcel.readParcelable(Parcel.java:2239)
at android.os.Parcel.readValue(Parcel.java:2146)
at android.os.Parcel.readSparseArrayInternal(Parcel.java:2540)
at android.os.Parcel.readSparseArray(Parcel.java:1868)
at android.os.Parcel.readValue(Parcel.java:2203)
at android.os.Parcel.readArrayMapInternal(Parcel.java:2479)
at android.os.BaseBundle.unparcel(BaseBundle.java:221)
at android.os.Bundle.getBundle(Bundle.java:782)
at com.google.android.gms.maps.internal.ao.a(:com.google.android.gms.alldynamite:74)
at maps.ei.bu.a(Unknown Source)
at maps.ei.n.a(Unknown Source)
at com.google.android.gms.maps.internal.i$a.onTransact(:com.google.android.gms.alldynamite:107)
at android.os.Binder.transact(Binder.java:380)
at com.google.android.gms.maps.internal.IMapFragmentDelegate$zza$zza.onCreateView(Unknown Source)
at com.google.android.gms.maps.SupportMapFragment$zza.onCreateView(Unknown Source)
at com.google.android.gms.dynamic.zza$4.zzb(Unknown Source)
at com.google.android.gms.dynamic.zza.zza(Unknown Source)
at com.google.android.gms.dynamic.zza.onCreateView(Unknown Source)
at com.google.android.gms.maps.SupportMapFragment.onCreateView(Unknown Source)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1036)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1230)
at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2315)
at android.support.v4.app.FragmentController.onCreateView(FragmentController.java:120)
at android.support.v4.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:357)
at android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:31)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:80)
at android.view.LayoutInf
My MainActivity.java is
package com.licenta.vladut.mmap;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
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.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
public class MainActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener, OnMapReadyCallback {
GoogleMap mMap;
private static final double BM_LAT = 47.6595076, BM_LNG = 23.5631243;
private Toolbar toolbar;
private GoogleApiClient mGoogleApiClient;
private static final String TAG = "SignInActivity";
private static final int ERROR_DIALOG_REQUEST = 9001;
private static final int RC_SIGN_IN = 9002;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.addApi(AppIndex.API).build();
if (checkPlayServices()) {
setContentView(R.layout.activity_map);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
(MainActivity.this).setSupportActionBar(toolbar);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
} else {
setContentView(R.layout.activity_main);
}
}
#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.sign_out) {
signOut();
return true;
}
return super.onOptionsItemSelected(item);
}
private void signOut() {
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
toSignIn();
}
});
}
private void toSignIn() {
Intent i = new Intent(this, SignInActivity.class);
startActivity(i);
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
// An unresolvable error has occurred and Google APIs (including Sign-In) will not
// be available.
Log.d(TAG, getString(R.string.onConnectionFailed) + connectionResult);
}
private boolean checkPlayServices() {
GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
int result = googleAPI.isGooglePlayServicesAvailable(this);
if (result != ConnectionResult.SUCCESS) {
if (googleAPI.isUserResolvableError(result)) {
googleAPI.getErrorDialog(this, result,
ERROR_DIALOG_REQUEST).show();
} else {
Toast.makeText(this, "Nu se poate conecta la Google Play Services!", Toast.LENGTH_SHORT).show();
}
return false;
}
return true;
}
#Override
public void onMapReady(final GoogleMap map) {
this.mMap = map;
gotoLocation(BM_LAT,BM_LNG,18);
}
private void gotoLocation(double lat, double lng, float zoom){
LatLng latLng = new LatLng(lat, lng);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(latLng,zoom);
mMap.moveCamera(update);
}
}
Activity_main.xml is
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="match_parent"
tools:context="com.licenta.vladut.mmap.MainActivity">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar"
/>
</RelativeLayout>
activity_map.xml is
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar"
/>
</fragment>
and finally, toolbar.xml is
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
android:background="?attr/colorPrimary"
android:id="#+id/toolbar"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:minHeight="?attr/actionBarSize"
android:layout_width="match_parent"
android:layout_alignParentStart="true"
android:elevation="4dp"
app:popupTheme="#style/AppTheme.PopupOverlay"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
</android.support.v7.widget.Toolbar>
I didn't like provided solutions as it imposed on my layouts and architecture.
Here's what I did to make it work. If you look at your stacktrace the ClassNotFoundException is coming from the line on GoogleMaps. So if we just fix that, the issue is gone.
GoogleMaps pukes/throw an error when the savedInstanceState has other items in it besides it's own. The solution is to just give GoogleMaps it's own dedicated bundle.
// class property
private static final String KEY_MAP_SAVED_STATE = "mapState";
// class methods
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mapView = findMapView(); // make your own method here
Bundle mapState = (savedInstanceState != null)
? savedInstanceState.getBundle(KEY_MAP_SAVED_STATE): null;
mapView.onCreate(mapState);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Bundle mapState = new Bundle();
mapView.onSaveInstanceState(mapState);
outState.putBundle(KEY_MAP_SAVED_STATE, mapState);
}
One thing to note is I'm not using the SupportMapFragment. I'm using a MapView directly. You may have to extend the SupportMapFragment so you can catch the hook methods and provide a blank/clean bundle
Upon rotation, your SupportMapFragment gets destroyed and recreated. Before it's destroyed, it writes its current state to a Parcel, to be used in restoring its state when recreated. The Fragment's saved state will include the state of its child Views, and since you've nested a Toolbar within it, it attempts to save and restore that, as well. The Toolbar class does not have an inner class SavedState necessary for that, so this process fails when trying to restore the Toolbar instance from the Parcel.
The solution is to not nest the Toolbar - or any other View, for that matter - within the <fragment> element. Instead, pull the <include> out of the <fragment>, and put them both in another ViewGroup; for example, a vertical LinearLayout, or a RelativeLayout.
Changing activity_map.xml to this worked, thanks again Mike.
<?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">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar" />
<fragment xmlns:map="http://schemas.android.com/apk/res-auto"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent">
</fragment>
</RelativeLayout>
I had a similar problem with my custom view and found this solution.
I noticed that this crash occurred when I extended RecyclerView or AppCompatSpinner and needed to save the state. The crash will probably happen for other views as well.
Basically the crash is caused by a bug in AbsSavedState as mentioned here.
And the crash only occurs when the constructor of the SavedState is called without a class loader. It seemed like this was an old issue however I started getting crash reports for Android 9 and 10.
So the fix was to change:
public SavedState(Parcel source) {
super(source);
//...
}
to:
public SavedState(Parcel source) {
super(source, LinearLayoutManager.class.getClassLoader());
//...
}
Edit
I was on the right track, but then I was looking at some Android code and found out that there was actually a constructor missing that caused the crash. So I had the following constructor for the SavedState:
SavedState(Parcel in)
{
super(in);
//...
}
And I needed to add the following:
#RequiresApi(Build.VERSION_CODES.N)
SavedState(Parcel in, ClassLoader loader)
{
super(in, loader);
//...
}
And then I needed to change the creator:
public static final Creator<SavedState> CREATOR = new ClassLoaderCreator<SavedState>()
{
#Override
public SavedState createFromParcel(Parcel source, ClassLoader loader)
{
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.N ? new SavedState(source, loader) : new SavedState(source);
}
#Override
public SavedState createFromParcel(Parcel source)
{
return createFromParcel(source, null);
}
public SavedState[] newArray(int size)
{
return new SavedState[size];
}
};

Categories