Action Bar null pointer exception - android

I am trying to change the title of an Action Bar but I am having the null pointer exception, I am not very expert so I don't really know how to catch the exception or do it properly, basically this is the line I am having problem with:
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getActionBar().setIcon(R.drawable.profile_banner_orange);
}
#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
switch (id){
case R.id.action_settings:
return true;
case R.id.profile_ic:
openItemManager();
return true;
}
return super.onOptionsItemSelected(item);
}
public void openItemManager(){
Intent myIntent = new Intent(MainActivity.this, ItemManagerActivity.class);
//myIntent.putExtra("key", value); //Optional parameters
MainActivity.this.startActivity(myIntent);
}
Android Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.blitzar.stiktag" >
<!-- To auto-complete the email text field in the login form with the user's emails -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<application
android:allowBackup="true"
android:icon="#drawable/icon_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".Activities.LoginActivity"
android:label="#string/app_name"
android:windowSoftInputMode="adjustResize|stateVisible" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Activities.ItemManagerActivity"
android:label="#string/title_activity_item_manager" >
</activity>
<activity
android:name=".Activities.MainActivity"
android:label="#string/title_activity_main"
android:icon="#drawable/profile_banner_orange" >
</activity>
</application>
</manifest>
and this is the activity_main XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.blitzar.stiktag.Activities.MainActivity">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="51dp">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/tag"
android:id="#+id/button3" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/search"
android:id="#+id/button4" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/found"
android:id="#+id/button" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/lost"
android:id="#+id/button2" />
</LinearLayout>
</RelativeLayout>
This is the log if that is any help:
08-12 21:37:39.113 450-450/com.blitzar.stiktag E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.blitzar.stiktag, PID: 450
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.blitzar.stiktag/com.blitzar.stiktag.Activities.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setIcon(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2394)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2452)
at android.app.ActivityThread.access$900(ActivityThread.java:172)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1302)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5586)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setIcon(int)' on a null object reference
at com.blitzar.stiktag.Activities.MainActivity.onCreate(MainActivity.java:20)
at android.app.Activity.performCreate(Activity.java:5451)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2358)
            
Any help will be highly appreciated

Please use the actionbar only after setting the views.
First use these,
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
then this,
getSupportActionBar().setIcon(R.drawable.profile_banner_orange);
UPDATE
Thanks for updating the question. Now the problem is obvious.
See, you are using the ActionBarActivity class which has long been deprecated. You should be seeing a strike-through in Android Studio. It is RECOMMENDED to use AppCompatActivity
Just extend AppCompatActivity and use getSupportActionBar(). You will not be getting any NullPointerException anymore.
If you have any problem displaying the icon, please try this,
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME |
ActionBar.DISPLAY_SHOW_TITLE | ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_USE_LOGO);
actionBar.setIcon(R.drawable.ic_launcher);

Before initializing any view please call setContentView()
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getActionBar();
actionBar.setIcon(R.drawable.profile_banner_orange);
Please update your style.xml
<resources>
<style name="AppBaseTheme" parent="#android:style/Theme.Holo.Light">
</style>
<style name="AppTheme" parent="android:Theme.Holo.Light"> </style>

You are using android.app.ActionBar. So you have to do the following
Remove the import statement import android.app.ActionBar;
Now import the support ActionBar class using import android.support.v7.app.ActionBar;
Then copy/paste the cody given below.
Done
getSupportActionBar() is used when your class extends from support library, ie AppCompatActivity or ActionBarActivity. In that case the proper way to get reference to ActionBar is
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setIcon(R.drawable.profile_banner_orange);
}
The Action Bar follows the material design guidelines and uses a Toolbar. As you can read here:
The use of application icon plus title as a standard layout is
discouraged on API 21 devices and newer. If you would like an
application icon, you can use the method setLogo().

You have called
getSupportActionBar().setIcon(R.drawable.profile_banner_orange);
before initilizing your activity's view. so at that time your actionbar is null.
you must call
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
first then your actionbar method.

try
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setIcon(R.drawable.profile_banner_orange);

Related

Add onclick listener to icons on toolbar [duplicate]

This question already has answers here:
Android, How to create option Menu
(11 answers)
Closed 5 years ago.
[my tool bar][1]
Do anyone have any solution?
I've seen your toolbar.
Here is my solution:
First create a menu xml resource file. (This will contain your "heart icon", res/menu/menu_example.xml)
Name it as you like, For example purpose I will name it menu_example.
menu_example.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/action_addfav"
android:title=""
app:showAsAction="always"
android:icon="#drawable/YOUR_ADDFAV_DRAWABLE" />
</menu>
Then create your activity code
activity_example.java
package com.example;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
public class activity_example extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Layout xml init
setContentView(R.layout.activity_example);
//Actionbar
//Back button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
//Inflate the menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_example, menu);
return true;
}
//Handling Action Bar button click
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
//Back button
case android.R.id.home:
//If this activity started from other activity
finish();
/*If you wish to open new activity and close this one
startNewActivity();
*/
return true;
case R.id.action_addfav:
//addfav (heart icon) was clicked, Insert your after click code here.
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void startNewActivity(){
Intent intent = new Intent(this,ACTIVITY_YOU_WANT_TO_START.class);
startActivity(intent);
finish();
}
}
Activity layout xml
(You can change the root layout to whatever layout you want)
<?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">
<!-- YOUR LAYOUT HERE -->
</RelativeLayout>
Last thing, make sure your app has toolbar in the theme
go to res/values/styles.xml
styles.xml
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<! -- Parent got to have actionbar in order for toolbat to appear -->
</style>
If you wish that the toolbar will be only in one specific activity take a look at: Apply a theme to an activity in Android?
You need to check R.id.img_bar_back. Weather it is the ImageView id you are finding or that is something else. This can happen due to finding wrong view id.
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/tool_bar_color"
android:theme="#style/ThemeOverlay.AppCompat.Dark">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:id="#+id/toolbar_iv_image1"
android:layout_width="?actionBarSize"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:layout_weight="1"
android:clickable="true"
android:gravity="center_vertical"
android:text="#string/e_wallet"
android:textColor="#android:color/white"
android:textSize="#dimen/font_20sp" />
<ImageButton
android:id="#+id/iv_invite"
android:layout_width="#dimen/padding_40dp"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="?selectableItemBackgroundBorderless"
android:clickable="true"
android:src="#drawable/invite_whit_icon" />
<ImageButton
android:id="#+id/iv_notifications"
android:layout_width="?actionBarSize"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="?selectableItemBackgroundBorderless"
android:clickable="true"
android:src="#drawable/notifiction_white" />
</LinearLayout>
</android.support.v7.widget.Toolbar>

Bluetooth app crashes on button press

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

button to show an image android app

I would like to make a simple app with a button that shows a picture when pressed.
Here is what I've written.
manifest:
<?xml version="1.0" encoding="utf-8"?>
<application
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name" >
<activity
android:label="#string/app_name"
android:name=".MainActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:theme="#style/AppTheme"
android:name="Activityfullscreen"></activity>
</application>
main:
package com.mycompany.button_show;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button_send);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent inf=new Intent(MainActivity.this,Activityfullscreen.class);
startActivity(inf);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
.java for the second activity:
public class Activityfullscreen extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_full_screen);
ImageView img = (ImageView) findViewById(R.id.widget45);
img.setBackgroundResource(R.drawable.aa);
}
}
activity_main:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="#+id/button_send"
android:layout_width="fill_parent"
android:layout_height="120dp"
/>
<TextView
android:id="#+id/widget45"
android:layout_width="fill_parent"
android:layout_height="120dp"
/>
</LinearLayout>
activity full screen:
<?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" >
<ImageView
android:id="#+id/widget45"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>
styles:
<!-- Base application theme. -->
<style name="AppTheme" parent="android:Theme.Material.Light">
<!-- Customize your theme here. -->
</style>
When I run, everything is fine, but when I launch the app I get the following error:
java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
Where is my mistake?
In Style.xml, you need to use AppCompat Theme - (RECOMMENDED)
<!-- Base application theme. -->
<style name="AppTheme" parent="android:Theme.AppCompat.Light">
<!-- Customize your theme here. -->
</style>
The above theme is Material Light theme.
Otherwise, you can leave AppCompat(But I don't recommend this as AppCompat is used for Material themes for lower Android versions like Jellybean, Honeycomb and Gingerbread) by using this code in Main - (NOT RECOMMENDED)
public class MainActivity extends Activity { // Changed from AppCompatActivity to just Activity
... Enter the code you use here
}
Change this too if you use the NOT RECOMMENDED method -
public class Activityfullscreen extends Activity { // Changed from AppCompatActivity to just Activity
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_full_screen);
ImageView img = (ImageView) findViewById(R.id.widget45);
img.setBackgroundResource(R.drawable.aa);
}
If you like this answer, please mark it as selected.
PS - Material.light is available only on Android 4.4 (Kitkat) +

Android application restarts when opened by clicking the application icon

I am new to the Android development world and I've built a simple "Hello World" app. First, activity requests a text. When the "Go" button is clicked, the app launches the second activity displaying the input text.
If I click the HOME button and then click the application icon, the app launches the first activity again but if I press-hold the home button and click the icon from the "Recent apps" bar, it resumes the app where I left.
How do I avoid this?
I need my app to resume even if the launcher icon is clicked.
MainActivity.java,
package com.example.myfirstandroidapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
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.main, menu);
return true;
}
/** Called when the user clicks the Send button */
public void sendMessage(View view){
// Do something in response to button
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.txtName);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
DisplayActivity.java,
package com.example.myfirstandroidapp;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class DisplayMessageActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.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);
// Show the Up button in the action bar.
setupActionBar();
}
/**
* Set up the {#link android.app.ActionBar}, if the API is available.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.display_message, menu);
return true;
}
#Override
public void onDestroy(){
super.onDestroy();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
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=".MainActivity" >
<EditText
android:id="#+id/txtName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="70dp"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="#+id/btnGo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/txtName"
android:layout_alignParentRight="true"
android:onClick="sendMessage"
android:text="Go!" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/txtName"
android:layout_alignParentTop="true"
android:layout_marginTop="18dp"
android:text="Please input your name:"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
activity_display_message.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=".DisplayMessageActivity" >
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
</RelativeLayout>
AndroidManifest.xml,
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myfirstandroidapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="9"
android:targetSdkVersion="10" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.myfirstandroidapp.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="com.example.myfirstandroidapp.DisplayMessageActivity"
android:label="#string/title_activity_display_message"
android:parentActivityName="com.example.myfirstandroidapp.MainActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.myfirstandroidapp.MainActivity" />
</activity>
</application>
</manifest>
Problem:
I'm not qualified to say this a bug, but there is a behaviour with release builds when starting the application from the launcher. It seems that instead of resuming the previous Activity, it adds a new Activity on top. There is a related bug report on this topic here.
Solution:
I'm working around this this by closing the Launcher Activity if it's not the root of the task, as a result the previous Activity in that task will be resumed.
if (!isTaskRoot()) {
finish();
return;
}
Issue for me was whenever app in installed by an apk with the click on 'Open' option it used to relaunch every time when we minimize it.
resolved it by
SplashActivity.java:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (!isTaskRoot
&& intent.hasCategory(Intent.CATEGORY_LAUNCHER)
&& intent.action != null
&& intent.action.equals(Intent.ACTION_MAIN)) {
finish()
return
}
}

Opening page on button click

I'm not sure why but the button doesn't work when clicked. It just says that the activity has stopped working and then exits out of program. Its being compiled with a level 8 api and targeting level 17 api.
package com.example.button;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
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.main, menu);
return true;
}
public void open(MainActivity view) {
view.loadUrl("http://www.yahoo.org");
}
private void loadUrl(String string) {
// TODO Auto-generated method stub
}
}
<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=".MainActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/textView1"
android:layout_below="#+id/textView1"
android:layout_marginTop="38dp"
android:onClick="open"
android:text="Button" />
public void open(MainActivity view) {
view.loadUrl("http://www.yahoo.org");
}
Activity has no method loadUrl. Seems like you're trying to use a WebView here.
--
Still, this shouldn't crash the app since you're not calling open anywhere. Is this all your code?
If your method open is used for the onClick property, set in the XML, then the parameters are incorrect. An onClick method should take View view not an activity like so:
XML:
<Button onClick="onClick"/>
Java:
public void onClick(View view)
{
//do something when button is clicked
}
This view passed is the button which was clicked.
To open a specific url in a WebView use the following code in the onClick method:
((WebView)findViewById(android.R.id.WebView)).loadUrl("http://slashdot.org/");
More information on the WebView can be found here
where is the button?? where is the webview (is used when you are calling a webpage or url to view in your activity)?? share your code, also check android manifest file .. if you are moving from one activity to another activity need to mention there like this :
<activity
android:name=".main"
android:label="#string/title_activity_main"
android:screenOrientation="landscape"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondPage"
android:screenOrientation="landscape"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen">
</activity>

Categories

Resources