button to show an image android app - android

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) +

Related

How to create a drop-down list in Android Studio?

I am trying to create a drop-down list for an activity in Android Studio. I have tried using the Spinner.
Here is my xml code:
<Spinner
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:drawable/btn_dropdown"
android:spinnerMode="dropdown"/>
Here is my Java code:
Spinner dropdown = findViewById(R.id.spinner1);
String[] items = new String[]{"1", "2", "3"};
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, items);
dropdown.setAdapter(adapter);
This is a screenshot of what it looks like:
As you can see, the drop-down list appears as a pop-up, however, I want the drop-down list to appear in a different way. See the image below as an example of what I want:
Does anyone have any ideas on how I could do this?
Actually it does look like there is a way with the Material design library called ExposedDropdownMenu
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/menu"
style="#style/Widget.MaterialComponents.TextInputLayout.FilledBox.ExposedDropdownMenu"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/label">
<AutoCompleteTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="none"
/>
</com.google.android.material.textfield.TextInputLayout>
Obviously this is with TextInput and not a spinner so there will still be some custom logic to prevent typing if you dont want that
I personally have not tried it myself but it looks like what you want
Some ideas:
As #tyczj said, that is android's default layout that is showing, so there are some alternatives:
Create tour own custom layout
Use an external library like SearchableSpinner, it incorporates the search function and the item layout is similar from what you want.
Here I have found a useful example for a ComboBox/Spinner on Android:
https://abhiandroid.com/ui/spinner
Here is the code:
https://github.com/abhisheksaini4/SpinnerExamples/blob/master/SpinnerExamples.7z
The main codes include MainActivity.java:
package example.abhiandriod.spinnerexample;
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.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
String[] bankNames={"BOI","SBI","HDFC","PNB","OBC"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Getting the instance of Spinner and applying OnItemSelectedListener on it
Spinner spin = (Spinner) findViewById(R.id.simpleSpinner);
spin.setOnItemSelectedListener(this);
//Creating the ArrayAdapter instance having the bank name list
ArrayAdapter aa = new ArrayAdapter(this,android.R.layout.simple_spinner_item,bankNames);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Setting the ArrayAdapter data on the Spinner
spin.setAdapter(aa);
}
//Performing action onItemSelected and onNothing selected
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position,long id) {
Toast.makeText(getApplicationContext(), bankNames[position], Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
#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);
}
}
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">
<Spinner
android:id="#+id/simpleSpinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp" />
</RelativeLayout>
menu_main.xml:
<menu 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" tools:context=".MainActivity">
<item android:id="#+id/action_settings" android:title="#string/action_settings"
android:orderInCategory="100" app:showAsAction="never" />
</menu>
And AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="example.abhiandriod.spinnerexample" >
<application
android:allowBackup="true"
android:icon="#mipmap/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>
</application>
</manifest>

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>

Action Bar null pointer exception

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);

<Activity name> cannot be resolved or not a field

I'm trying to perform a simple navigation action using Intent.
I'm using the complete ADT bundle which includes eclipse, SDK and ADT plugins, so no need to configure ADT separately in eclipse.
1.) I started by creating two layouts named activity_main.xml and test2.xml.
2.) Corresponding java files are mainActivity.java and test2.java.
3.) Now activity_main.xml contains a button with id = "click" . Clicking this button should navigate to next activity i.e test2.xml.
4.) The code in mainActivity.java is as below
package com.example.test;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.os.Build;
public class MainActivity extends ActionBarActivity
{
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
if (savedInstanceState == null)
{
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
btn = (Button)findViewById(R.id.click);
//Listening to button event
btn.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0) {
//Starting a new Intent
Intent nextScreen = new Intent(getApplicationContext(), test2.class);
startActivity(nextScreen);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
5.) But when i did so the findViewById(R.id.click) showed error saying "click cannot be resolved or is not a field"
6.) Eclipse suggested me to create a field click in id which i did. It modified the R.java file but it did not help. Though the errors were gone but the emulator threw error saying "the application has stopped"
7.) My manifest.xml file is as below
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.test"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.test.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=".test2"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.example.test.test2" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
8.) Now my test2.java code is
package com.example.test;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
import com.example.test.R;
public class test2 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.test2);
TextView txtName = (TextView) findViewById(R.id.textView1);
txtName.setText("This is test2 activity");
}
}
Even here at setContentView(R.layout.test2) it shows the similar error as "test2 cannot be resolved or not a field" where as setContentView(R.layout.activity_main) did not show this error
9.) My fragment_main.xml code is as below
<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.test.MainActivity$PlaceholderFragment" >
<Button
android:id="#+id/click"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_centerInParent="true"
android:layout_marginLeft="14dp"
android:layout_marginTop="65dp"
android:text="#string/button" />
</RelativeLayout>
10.) My test2.xml code is as below
<?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
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="second page"
android:layout_gravity="center"
/>
</LinearLayout>
The error displayed on running the application is as below
a.) [2014-04-15 18:39:03 - test] W/ResourceType( 8160): ResXMLTree_node header size 0 is too small.
b.) [2014-04-15 18:39:03 - test] C:\Users\KC\Desktop\Android-budle\test\res\menu\main.xml:6: error: Error: No resource found that matches the given name (at 'title' with value '#string/action_settings').
I'm not able to understand what am I missing. Please provide me a solution for this issue, Thanks in advance.
Firstly Check your layout xml. I there is any error then correct it.After that press alt+p then select clean after that it will be build again.
In your activity_main.xml>Button you need to put the android:onClick="methodName". The in your main_activity you schould implement methodName. There you can handle the activities once the Button is clicked.
Another way is to implement the onClickListener to sepertate the XML and the Java files.
Can you add your layout XML files?
Write the onClickListener for your button in your MainActivity onCreate() method and inside it redirect to test2 activity as below:
btn = (Button)findViewById(R.id.click);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(MainActivity.this,test2.class);
startActivity(intent);
}
});
EDITED:
You need to set your view as fragment_main.xml besides activity_main as your Button is inside fragment_main layout.
Just change the
setContentView(R.layout.activity_main);
to
setContentView(R.layout.fragment_main);
There is something wrong syntax wise with your xml files (test2 or activity_main) due to which the auto generated R file will no longer generate the id for the button view.
The main problem seems to be with activity_main as the button contained in it is no longer converted to its corresponding value in R file.
Check those files and if not able to figure out than put the code in order to get help.
Last but not the least check if you have the import statement like import android.R.
You don't need this to be there as it causes such errors if present.
UPDATE:
You are using -
1) setContentView(R.layout.activity_main);
2) btn = (Button)findViewById(R.id.click);
But your layout where you defined your button is setContentView(R.layout.fragment_main);
So btn is trying to find the view in activity_main which is not available.
Solution -
Set the content view to setContentView(R.layout.fragment_main).

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
}
}

Categories

Resources