I am pretty new to coding and am currently a student. I am trying to create a simple timer app. When I run the timer app in the emulator, it opens for a split second and than force stops.
I have tried:
1. Clean Project
2. Adding android:hasCode = "true";
3. Downloading AppCompat
Here is my MainActivity code:
package com.example.timer2;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.os.CountDownTimer;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView countdownText;
private Button countdownButton;
private CountDownTimer countDownTimer;
private long timeLeftInMilliseconds = 600000; //10 mins
private boolean timerRunning;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
countdownText = findViewById(R.id.countdown_text);
countdownButton = findViewById(R.id.countdown_button);
countdownButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startStop();
}
});
}
public void startStop () {
if (timerRunning) {
stopTimer ();
} else {
startTimer ();
}
}
public void startTimer () {
countDownTimer = new CountDownTimer(timeLeftInMilliseconds, 1000) {
#Override
public void onTick(long l) {
timeLeftInMilliseconds = l;
updateTimer ();
}
#Override
public void onFinish() {
}
}.start();
countdownButton.setText("PAUSE");
timerRunning = true;
}
public void stopTimer () {
countDownTimer.cancel();
countdownButton.setText("START");
timerRunning = false;
}
public void updateTimer () {
int minutes = (int) timeLeftInMilliseconds / 600000;
int seconds = (int) timeLeftInMilliseconds % 600000 / 1000;
String timeLeftText;
timeLeftText = "" + minutes;
timeLeftText += ":";
if (seconds < 10) timeLeftText += "0";
timeLeftText += seconds;
countdownText.setText(timeLeftText);
}
}
Here is my manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.timer2">
<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"
android:hasCode="true">
<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 is my layout:
<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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".MainActivity"
tools:showIn="#layout/activity_main">
<TextView
android:id="#+id/countdown_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:text="10:00"
android:textSize="50sp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"/>
<com.google.android.material.button.MaterialButton
android:id="#+id/countdown_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerInParent="true"
android:layout_centerVertical="true"
android:layout_marginBottom="237dp"
android:text="#string/start" />
</RelativeLayout>
Here is the error message:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.timer2, PID: 2947
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.timer2/com.example.timer2.MainActivity}: android.view.InflateException: Binary XML file line #23 in com.example.timer2:layout/activity_main: Binary XML file line #20 in com.example.timer2:layout/content_main: Error inflating class com.google.android.material.button.MaterialButton
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3268)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3407)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7343)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:933)
Caused by: android.view.InflateException: Binary XML file line #23 in com.example.timer2:layout/activity_main: Binary XML file line #20 in com.example.timer2:layout/content_main: Error inflating class com.google.android.material.button.MaterialButton
Caused by: android.view.InflateException: Binary XML file line #20 in com.example.timer2:layout/content_main: Error inflating class com.google.android.material.button.MaterialButton
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
at android.view.LayoutInflater.createView(LayoutInflater.java:854)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:1006)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:961)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:1123)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1084)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:1263)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:1119)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1084)
at android.view.LayoutInflater.inflate(LayoutInflater.java:682)
at android.view.LayoutInflater.inflate(LayoutInflater.java:534)
at android.view.LayoutInflater.inflate(LayoutInflater.java:481)
at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:545)
at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:161)
at com.example.timer2.MainActivity.onCreate(MainActivity.java:31)
at android.app.Activity.performCreate(Activity.java:7802)
at android.app.Activity.performCreate(Activity.java:7791)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3243)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3407)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7343)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:933)
Caused by: java.lang.IllegalArgumentException: This component requires that you specify a valid TextAppearance attribute. Update your app theme to inherit from Theme.MaterialComponents (or a descendant).
at com.google.android.material.internal.ThemeEnforcement.checkTextAppearance(ThemeEnforcement.java:170)
at com.google.android.material.internal.ThemeEnforcement.obtainStyledAttributes(ThemeEnforcement.java:75)
at com.google.android.material.button.MaterialButton.<init>(MaterialButton.java:140)
at com.google.android.material.button.MaterialButton.<init>(MaterialButton.java:133)
... 31 more
Thank you in advance for any help with this.
tl;dr
Change your app theme to inherit from Theme.MaterialComponents or Bridge theme. Also be aware that your activity sets its own theme settings in AndroidManifest.xml.
Welcome to StackOverflow! According to the error message, the MaterialButton you are using in your layout requires an application theme which inherits from Theme.MaterialComponents. Your application most likely uses the default AppCompat theme. To fix the error go to your src/main/res/values/styles.xml file and change the theme to a MaterialComponents theme. For example:
<style name="AppTheme" parent="Theme.MaterialComponents.Light">
<!-- ... -->
</style>
You can pick from the following themes:
Theme.MaterialComponents
Theme.MaterialComponents.NoActionBar
Theme.MaterialComponents.Light
Theme.MaterialComponents.Light.NoActionBar
Theme.MaterialComponents.Light.DarkActionBar
Theme.MaterialComponents.DayNight
Theme.MaterialComponents.DayNight.NoActionBar
Theme.MaterialComponents.DayNight.DarkActionBar
If you must use the AppCompat theme (for example, for compatibility with API level below Lollipop), you can inherit from a Bridge theme.
Bridge themes inherit from AppCompat themes, but also define the new
Material Components theme attributes for you.
The following Bridge themes are available:
Theme.MaterialComponents.Bridge
Theme.MaterialComponents.Light.Bridge
Theme.MaterialComponents.NoActionBar.Bridge
Theme.MaterialComponents.Light.NoActionBar.Bridge
Theme.MaterialComponents.Light.DarkActionBar.Bridge
You can find more information regarding the Material Themes here.
Be aware that your Activity sets its own theme settings in the AndroidManifest.xml:
<activity
...
android:theme="#style/AppTheme.NoActionBar">
...
</activity>
This means that if you set the theme in styles.xml to inherit from Theme.MaterialComponents.Light.NoActionBar, your activity will now look for a theme called Theme.MaterialComponents.Light.NoActionBar.NoActionBar, which doesn't exist. You can either delete this line or make your app inherit from Theme.MaterialComponents.Light.
Related
This question already has answers here:
Android 1.6: "android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application"
(16 answers)
Closed 5 years ago.
Whenever I launch my activity it crashes. I don't know what the problem is. My code, xml resources and Android manifest looks fine. If anyone could
help me that would be appreciated!
The issue is caused by a android.view.WindowManager$BadTokenException, which is mentioned in the LogCat
Java Code
package com.example.hp.machine;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class Machine extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.machine);
Button click = (Button) findViewById(R.id.click);
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(Machine.this);
builder.setTitle("Warning")
.setIcon(R.drawable.bomb)
.setMessage("Do you want to Die ?")
.setCancelable(false) ;
AlertDialog alert = builder.create();
alert.show();
}
});
}
}
XML
<?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:id="#+id/machine"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.hp.machine.Machine"
android:background="#drawable/splash_screen"
>
<Button
android:layout_height="wrap_content"
android:layout_width="130dp"
android:text="click"
android:layout_marginTop="200dp"
android:id="#+id/click"
android:textColor="#android:color/white"
android:textStyle="bold"
android:fontFamily="serif"
android:background="#android:color/background_dark"
/>
</RelativeLayout>
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.hp.machine">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".Machine">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
LogCat
Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
at android.view.ViewRootImpl.setView(ViewRootImpl.java:789)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:298)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
at android.app.Dialog.show(Dialog.java:325)
at com.example.hp.machine.Machine.onCreate(Machine.java:46)
at android.app.Activity.performCreate(Activity.java:6609)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1134)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3113)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3275)
at android.app.ActivityThread.access$1000(ActivityThread.java:218)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1744)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:7007)
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:1404) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
07-19 17:13:23.830 28841-28841/com.example.hp.machine I/Process: Sending signal. PID: 28841 SIG: 9
You can not write AlertDialog in onCreate() method.
Replace it at onResume() method.
Change the getBaseContext() to Machine.this
package com.example.hp.machine;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class Machine extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.machine);
Button click = (Button) findViewById(R.id.click);
AlertDialog.Builder builder = new AlertDialog.Builder(Machine.this);
builder.setTitle("Warning")
.setIcon(R.drawable.bomb)
.setMessage("Do you want to Die ?")
.setCancelable(false) ;
AlertDialog alert = builder.create();
alert.show();
}
}
I assume the space in AppCompatActivity (the extend part) is an SO import issue.
You use getBaseContext, when you should reference the context to the current object:
AlertDialog.Builder builder = new AlertDialog.Builder(Machine.this
/*Inside nested classes, this refers to that class. This is just good practice to do even
if you aren't inside a nested class/thread*/);
When showing dialogs, you need to do it:
On the UI thread
With the application context
Using outside the UI thread ends up with leaked window.
Just saw now, you run on a different thread.
Inside the onClick method, you add this:
runOnUiThread(new Runnable() {
#Override
public void run() {
//Add your dialog code here
}
});
and add the dialog code inside.
One thing I do not understand how come onClick get called while activity is being created.
onClick should be called on clicking event.
I'm trying to enable the back button in this really simple activity (that is instantiated by another activity), but I always get the null pointer exception and therefore my app crashes when I launch the activity (without the back button in the action bar the activity works great).
I tried many different solution posted in the internet, but none worked...
I'm following this guide : Android Developer providing up navigation
Here the manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.projectcalculator">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/Theme.AppCompat.Light.NoActionBar"
android:screenOrientation="portrait">
<!--attività principale-->
<activity
android:name=".MainActivity"
android:launchMode="singleInstance">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!--attività infixToPostfix-->
<activity
android:name=".InfixToPostfixActivity"
android:launchMode="singleTask"
android:label="#string/infix_to_postfix"/>
<!--attività figlia di infixToPostfix-->
<activity
android:name=".ShowPostfixProcedureActivity"
android:launchMode="standard"
android:label="#string/postfix_procedure"
android:parentActivityName=".InfixToPostfixActivity" />
</application>
</manifest>
Here the java file of the activity (ShowPostfixProcedureActivity):
package com.example.android.projectcalculator;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import java.util.Stack;
import static java.lang.Character.isDigit;
public class ShowPostfixProcedureActivity extends AppCompatActivity {
private static String equation;
private static int openBracket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_infix_to_postfix_jurney);
Toolbar myToolbar = (Toolbar) findViewById(R.id.infix_to_postfix_toolbar_procedure);
setSupportActionBar(myToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
TextView txview = (TextView)findViewById(R.id.postfix_jurney_text_wall);
Stack<String> s = new Stack<String>();
s = DataProcessor.ReturnProcess();
txview.setText(s.pop());
while (!s.empty())
{
if (s.peek().charAt(0) == '<')
{
txview.append(Html.fromHtml(s.pop()));
}
else
{
txview.append(s.pop());
}
}
//Log.d("SPPA/onCreate","text = "+DataProcessor.ReturnProcess());
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.action_bar_postfix_procedure, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
The XML file related to the layout (show_infix_to_postfix_jurney):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical">
<!--ActionBar in alto-->
<android.support.v7.widget.Toolbar
android:id="#+id/infix_to_postfix_toolbar_procedure"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#42f480"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical">
<TextView
android:id="#+id/postfix_jurney_text_wall"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10sp"
android:textSize="20sp"
android:gravity="center"
android:background="#f2f2f2"/>
</ScrollView>
</LinearLayout>
And finally the XML file related to the Navigation bar (action_bar_postfix_procedure):
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
</menu>
Here the error message:
10-29 17:14:43.841 18822-18822/com.example.android.projectcalculator E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.projectcalculator, PID: 18822
Theme: themes:{}
java.lang.NullPointerException: Attempt to invoke interface method 'android.view.MenuItem android.view.MenuItem.setEnabled(boolean)' on a null object reference
at com.example.android.projectcalculator.ShowPostfixProcedureActivity.onCreateOptionsMenu(ShowPostfixProcedureActivity.java:51)
at android.app.Activity.onCreatePanelMenu(Activity.java:2852)
at android.support.v4.app.FragmentActivity.onCreatePanelMenu(FragmentActivity.java:340)
at android.support.v7.view.WindowCallbackWrapper.onCreatePanelMenu(WindowCallbackWrapper.java:85)
at android.support.v7.app.AppCompatDelegateImplBase$AppCompatWindowCallbackBase.onCreatePanelMenu(AppCompatDelegateImplBase.java:258)
at android.support.v7.view.WindowCallbackWrapper.onCreatePanelMenu(WindowCallbackWrapper.java:85)
at android.support.v7.app.ToolbarActionBar.populateOptionsMenu(ToolbarActionBar.java:454)
at android.support.v7.app.ToolbarActionBar$1.run(ToolbarActionBar.java:61)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5461)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
I don't know what the line NavUtils.navigateUpFromSameTask(this); is supposed to do. If you want to close the activity on the press of the back button replace it with the method call onBackPressed()
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
onBackPressed()
return true;
}
return super.onOptionsItemSelected(item);
}
I am making an android project by targetting api 13+. I need to have a appbar/toolbar instead of actionbar at the top of each activity I have in my app. I have tried searching over many blogs and SO itself but without any success.
I have created a base activity class and all my activities inherit from this class:
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.support.v7.widget.Toolbar;
public class BaseActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Toolbar tb = (Toolbar) findViewById(R.id.appToolbar);
setSupportActionBar(tb);
getSupportActionBar().setDisplayShowTitleEnabled(true);
getSupportActionBar().setTitle("oh yeah");
}
...
}
I have done the housekeeping stuff for the toolbar in this class and the following class is the activity which shows up when the app is launched:
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
public class SplashScreen extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// api level < 16 and > 16 have different
// ways of removing the status bar
if(Build.VERSION.SDK_INT < 16) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
} else {
View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
}
setContentView(R.layout.activity_splash_screen);
// Create a new thread and delay for 3 sec
// to handle the start of the main screen.
Handler h = new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent().setClass(getApplicationContext(), MainScreen.class);
startActivity(i);
}
}, 3000);
}
And this is the activity which is launched after the splash screen:
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
public class MainScreen extends BaseActivity {
private ImageButton btnLoyaltyForm;
private ImageButton btnFeedbackForm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
btnLoyaltyForm = (ImageButton) findViewById(R.id.btnLoyaltyForm);
btnFeedbackForm = (ImageButton) findViewById(R.id.btnFeedbackForm);
btnLoyaltyForm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent().setClass(getApplicationContext(), LoyaltyFormScreen.class);
startActivity(i);
}
});
btnFeedbackForm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent().setClass(getApplicationContext(), FeedbackFormScreen.class);
startActivity(i);
}
});
}
}
Here is the XML for my appbar:
<android.support.v7.widget.Toolbar
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/actionbar_background_color"
android:minHeight="?attr/actionBarSize"
xmlns:android="http://schemas.android.com/apk/res/android" />
Here is the XML for my MainScreen activity:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context="com.tarz.MainScreen">
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<include
android:id="#+id/appToolbar"
layout="#layout/app_bar" />
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="false"
android:layout_alignParentBottom="false"
android:layout_alignWithParentIfMissing="false"
android:gravity="center">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btnLoyaltyForm"
android:layout_gravity="center_horizontal"
android:src="#drawable/btn_form1" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btnFeedbackForm"
android:layout_gravity="center"
android:src="#drawable/btn_form2" />
</LinearLayout>
</RelativeLayout>
Here is my app's manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tarz" >
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".SplashScreen"
android:label="#string/title_activity_splash_screen" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainScreen"
android:label="#string/title_activity_main_screen" >
</activity>
<activity
android:name=".BaseActivity"
android:label="#string/title_activity_base" >
</activity>
</application>
</manifest>
Here is my colors.xml:
n="1.0" encoding="utf-8"?>
<resources>
<color name="actionbar_background_color">#2d3135</color>
<color name="actionbar_text_color">#ffffff</color>
<color name="app_background_color">#f7f6f0</color>
<color name="button_background_color">#2d3135</color>
<color name="button_text_color">#ffffff</color>
</resources>
Here is my styles.xml:
<resources xmlns:tools="http://schemas.android.com/tools" xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="android:background">#color/app_background_color</item>
<!--<item name="colorPrimaryDark">#color/colorPrimaryDark</item>-->
<!--<item name="colorAccent">#color/colorAccent</item>-->
</style>
<style name="ActionBarTheme" parent="ThemeOverlay.AppCompat.ActionBar">
<item name="android:background">#color/actionbar_background_color</item>
<item name="colorPrimary">#color/actionbar_background_color</item>
</style>
</resources>
When I run the app, the splash screen shows up then it crashes with the following error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.app.ActionBar.setDisplayShowTitleEnabled(boolean)' on a null object reference
And
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.app.ActionBar.setDisplayShowTitleEnabled(boolean)' on a null object reference
This is the log:
4059-4059/com.tarz E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.tarz, PID: 4059
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.tarz/com.tarz.MainScreen}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.app.ActionBar.setDisplayShowTitleEnabled(boolean)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.app.ActionBar.setDisplayShowTitleEnabled(boolean)' on a null object reference
at com.tarz.MainScreen.onCreate(MainScreen.java:28)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
How do I use the colors I have defined in my colors.xml so that my toolbar could have a different color, my app could have a different color and my toolbar's text could have a different color.
Also, menu on each activity would be different so the toolbar should adjust according to the activity, how could I do that also?
Please help, thanks. :)
EDIT 1:
After #Rod said to initialize toolbar after setting contentView, it cleared the NPE but then no toolbar is being shown:
This method is added at the top of the BaseActivity class:
public void initToolbar() {
Toolbar tb = (Toolbar) findViewById(R.id.appToolbar);
setSupportActionBar(tb);
getSupportActionBar().setDisplayShowTitleEnabled(true);
getSupportActionBar().setTitle("oh yeah");
}
and the onCreate now just have the super call. Also, the MainScreen class now have the initToolbar(); called after setContentView(); in onCreate(); method.
A couple of things I would point out:
You are not inflating a layout in your onCreate() in BaseActivity.
I think the official Toolbar tutorials are all using AppCompatActivity instead of ActionBarActivity.
You could define different Toolbar themes and apply them in different activities. More info here.
Each activity has it's own toolbar, so you don't have to worry about supporting different menus for each activity. You simply inflate the menu XML for the activity in onCreateOptionsMenu().
EDIT 1: Inflating the appropriate layout in the base activity:
public abstract class BaseActivity extends AppCompatActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getLayoutResId());
final Toolbar toolbar = findViewById(<your toolbar id>);
// the rest of your logic
}
// This abstract method will provide a way for extending activities to give the id of their layout, so you can inflate it, before trying to set the toolbar
#LayoutRes
protected abstract getLayoutResId();
}
EDIT 2: Customising the toolbar
The Toolbar, like every other widget, can be customised using styles. To control the toolbar background colour, spacing, etc, you need to set a custom style to it. You can also change the toolbar title and subtitle appearance using the same mechanism. Here is a great link that shows all you need to know about creating and applying custom toolbar styles.
I am up to the "Start Another Activity" section of the Android tutorial and it simply won't work when I install and test it.
It compiles fine but running it breaks after I click the send button.
I am using the command line tools on Ubuntu 12.04 and installing to a real device, my Galaxy S5.
I am aware of logcat but haven't been able to get it working, it either shows no output at all, or gives a massive spam of output I can't keep up with. I would happily provide logcat information if I could manage to isolate my app's output and cut through everything else.
I have seen a lot of similar questions on this which leads me to believe the tutorial isn't very well written.
Here is "MyActivity.java"
package com.example.myfirstapp;
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.widget.EditText;
import android.view.View;
public class MyActivity extends Activity
{
public final static String EXTRA_MESSAGE = "com.mycompany.myfirstapp.MESSAGE";
/** Called when the activity is first created */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
/** Called when the user clicks the send button */
public void sendMessage(View view)
{
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
Here is DisplayMessageActivity
package com.example.myfirstapp;
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.support.v7.app.*;
import android.view.*;
import android.widget.*;
import com.example.myfirstapp.R;
public class DisplayMessageActivity extends ActionBarActivity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//Get the message from intent
Intent intent = getIntent();
String message = intent.getStringExtra(MyActivity.EXTRA_MESSAGE);
//Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
//Set the text view as the activity layout
setContentView(textView);
}
}
Here is AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myfirstapp"
android:versionCode="1"
android:versionName="1.0">
<application android:label="#string/app_name" android:icon="#drawable/ic_launcher">
<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="com.example.myfirstapp.DisplayMessageActivity"
android:label="#string/title_activity_display_message"
android:parentActivityName="com.example.myfirstapp.MyActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.myfirstapp.MyActivity"
/>
</activity>
</application>
</manifest>
EDIT: Here is Main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<EditText android:id="#+id/edit_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="#string/edit_message"
/>
<Button
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="#string/button_send"
android:onClick="sendMessage"
/>
</LinearLayout>
There was some code that I changed and took out as it said to add code in, but then would later show a "this is what your code should look like" and it was missing some of the original code. I also changed the manifest package names in the activities because at the beginning it uses com.example.myfirstapp but later uses com.mycompany.myfirstapp
Any help or advice on why this seemingly simple tutorial doesn't work is greatly appreciated.
EDIT:
Logcat output - (after pressing the send button)
I/Timeline( 3812): Timeline: Activity_launch_request id:com.example.myfirstapp time:74636924
D/AndroidRuntime( 3812): Shutting down VM
E/AndroidRuntime( 3812): FATAL EXCEPTION: main
E/AndroidRuntime( 3812): Process: com.example.myfirstapp, PID: 3812
E/AndroidRuntime( 3812): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myfirstapp/com.example.myfirstapp.DisplayMessageActivity}: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
E/AndroidRuntime( 3812): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2658)
E/AndroidRuntime( 3812): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2725)
E/AndroidRuntime( 3812): at android.app.ActivityThread.access$900(ActivityThread.java:172)
E/AndroidRuntime( 3812): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1422)
E/AndroidRuntime( 3812): at android.os.Handler.dispatchMessage(Handler.java:102)
E/AndroidRuntime( 3812): at android.os.Looper.loop(Looper.java:145)
E/AndroidRuntime( 3812): at android.app.ActivityThread.main(ActivityThread.java:5834)
E/AndroidRuntime( 3812): at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime( 3812): at java.lang.reflect.Method.invoke(Method.java:372)
E/AndroidRuntime( 3812): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1388)
E/AndroidRuntime( 3812): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)
E/AndroidRuntime( 3812): Caused by: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
E/AndroidRuntime( 3812): at android.support.v7.app.ActionBarActivityDelegate.onCreate(ActionBarActivityDelegate.java:151)
E/AndroidRuntime( 3812): at android.support.v7.app.ActionBarActivityDelegateBase.onCreate(ActionBarActivityDelegateBase.java:138)
E/AndroidRuntime( 3812): at android.support.v7.app.ActionBarActivity.onCreate(ActionBarActivity.java:123)
E/AndroidRuntime( 3812): at com.example.myfirstapp.DisplayMessageActivity.onCreate(DisplayMessageActivity.java:16)
E/AndroidRuntime( 3812): at android.app.Activity.performCreate(Activity.java:6221)
E/AndroidRuntime( 3812): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
E/AndroidRuntime( 3812): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2611)
E/AndroidRuntime( 3812): ... 10 more
I/Process ( 3812): Sending signal. PID: 3812 SIG: 9
I/ActivityManager( 871): Process com.example.myfirstapp (pid 3812)(adj 13) has died(104,205)
Here's the working code :
MainActivity.class
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends ActionBarActivity {
EditText et;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = (EditText) findViewById(R.id.editText1);
}
public void Go(View v)
{
Log.d("check", "Pressed");
String value = et.getText().toString();
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("key", value);
startActivity(intent);
}
}
SecondActivity.class
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.widget.TextView;
public class SecondActivity extends ActionBarActivity {
TextView textv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_activity);
String txt = getIntent().getStringExtra("key");
Log.d("check", "got : " +txt);
textv = (TextView) findViewById(R.id.textView1);
textv.setText(txt);
}
}
res/layout/activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android: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.testproject.MainActivity" >
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="67dp"
android:layout_marginTop="46dp"
android:ems="10" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:onClick="Go"
android:text="Button" />
</RelativeLayout>
res/layout/new_activity.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="74dp"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
AndroidManifest.xml
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivity"></activity> // Registered the newly created activity
</application>
Output :
Logcat :
BY SEEING YOUR LOGCAT, I got there is a problem in your Theme.
You didn't declared AppTheme in AndroidManifest.xml file
android:theme="#style/AppTheme"
Try by This Sample Code I have made For You.
mainactivity.xml Code
<EditText
android:id="#+id/edtMessage"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="message"
/>
<Button
android:id="#+id/btnSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send"
/>
MainActivity.class
Button btnSend;
EditText edtMessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtMessage=(EditText)findViewById(R.id.edtMessage);
btnSend=(Button)findViewById(R.id.btnSend);
btnSend.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String Message=edtMessage.getText().toString();
Intent intent=new Intent(getApplicationContext(),Second.class);
intent.putExtra("Message", Message);
startActivity(intent);
}
});
}
second.xml
<TextView
android:id="#+id/tviMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
/>
Second.class
TextView tviMessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
tviMessage=(TextView)findViewById(R.id.tviMessage);
Bundle extras = getIntent().getExtras();
String message = extras.getString("Message");
tviMessage.setText(message);
}
Manifesto.xml
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Second"
android:label="#string/app_name" >
</activity>
By using logcat with this command:
adb logcat | grep `adb shell ps | grep com.example.myfirstapp | cut -c10-15`
I was able to find the error causing the app to crash. It came from missing the line:
android:theme="#style/Theme.AppCompat.Light"
In the Manifest.xml file. This is required by the Activity bar compatibility class. This part was completely overlooked in the tutorial, presumably because IDEs do this part automatically.
Thank you to everybody for their help and suggestions, it helped me keep looking and trying things until I finally found my solution.
I am attempting to write get a handle on the new Shared Elements Animations API that google L preview is giving us.
I have been trying to use the code base as a point of reference along with: https://developer.android.com/preview/material/animations.html
For the life of me I cannot seem to get my app to work. However when I run the Demo App from google the transition works just fine.
MyActivity.java:
public class MyActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
final ImageView imageView = (ImageView)this.findViewById(R.id.img_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.my, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void showPhoto(View view) {
Intent intent = new Intent();
intent.setClass(this, MyActivity2.class);
ImageView hero = (ImageView) ((View) view.getParent()).findViewById(R.id.img_main);
((ViewGroup) hero.getParent()).setTransitionGroup(false);
ActivityOptions options =
ActivityOptions.makeSceneTransitionAnimation(this, hero, "robot");
startActivity(intent, options.toBundle());
}
}
activity_my.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MyActivity">
<ImageView
android:id="#+id/img_main"
android:viewName="photo1"
android:layout_width="64dp"
android:layout_height="64dp"
android:src="#drawable/test"
android:onClick="showPhoto"/>
</RelativeLayout>
styles.xml:
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
<item name="android:windowContentTransitions">true</item>
<item name="android:windowAllowEnterTransitionOverlap">true</item>
<item name="android:windowAllowExitTransitionOverlap">true</item>
<item name="android:windowActionBarOverlay">false</item>
<item name="android:windowContentOverlay">#null</item>
</style>
</resources>
manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.jms_m_000.transitionshit" >
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<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=".MyActivity2"
android:label="#string/title_activity_my_activity2" >
</activity>
</application>
</manifest>
The Error I am receiving:
07-06 18:54:42.153 24145-24145/com.example.jms_m_000.transitionshit
E/AndroidRuntime﹕FATAL EXCEPTION: main
Process: com.example.jms_m_000.transitionshit, PID: 24145
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3970)
at android.view.View.performClick(View.java:4598)
at android.view.View$PerformClick.run(View.java:19268)
at android.os.Handler.handleCallback(Handler.java:738)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5070)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at rnal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:836)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:631)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:3965)
at android.view.View.performClick(View.java:4598)
at android.view.View$PerformClick.run(View.java:19268)
at android.os.Handler.handleCallback(Handler.java:738)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5070)
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:836)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:631)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.app.ActivityOptions.toBundle()' on a null object reference
at com.example.jms_m_000.transitionshit.MyActivity.showPhoto(MyActivity.java:56)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:3965)
at android.view.View.performClick(View.java:4598)
at android.view.View$PerformClick.run(View.java:19268)
at android.os.Handler.handleCallback(Handler.java:738)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5070)
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:836)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:631)
Im not sure why but options is null after calling .makeSceneTransitionAnimation()...
Any Thoughts?
Try adding
requestFeature(Window.FEATURE_CONTENT_TRANSITIONS);
in the onCreate() method of your activity.
That surprisingly worked for me in making options non null.
Define a view name by calling setViewName() to 'hero' in your first Activity, and define a view name (same as defined in makeSceneTransitionAnimation) to your ImageView in your second Activity . That's worked for me