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
}
}
Related
Error(s):
10-17 18:53:39.298: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.quizme/com.quizme.QuizMeActivity}: java.lang.ClassCastException: android.widget.ImageButton cannot be cast to android.widget.TextView
10-17 18:53:38.747: error opening trace file: No such file or directory (2)
Upon trying to run it I get the unfortunatly, the app does not work error as well.
Java file:
package com.quizme;
import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
public class QuizMeActivity extends Activity {
private TextView question;
private TextView result;
private ImageButton forward;
private ImageButton backward;
private Button bTrue;
private Button bFalse;
private TrueFalse mTrueFalse;
/*
* onCreate(Bundle savedInstanceState)
* Instantiates all private GUI elements to their corresponding Views
* in activity_quiz_me.xml
* Sets the string values of the questions in the TrueFalse object,
* and sets their truth values.
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz_me);
Resources res = this.getResources(); //this is to be able to get strings
bTrue=(Button)findViewById(R.id.true_button);
forward=(ImageButton)findViewById(R.id.forward_button);
bFalse=(Button)findViewById(R.id.false_button);
backward=(ImageButton)findViewById(R.id.back_button);
result=(TextView)findViewById(R.id.result);
result.setText("");
question=(TextView)findViewById(R.id.question);
question.setText(mTrueFalse.getmQuestionSet()[0]);
mTrueFalse.setmQuestionSet(0, (String) res.getText(R.string.q1));
mTrueFalse.setmQuestionSet(1, (String) res.getText(R.string.q2));
mTrueFalse.setmQuestionSet(2, (String) res.getText(R.string.q3));
mTrueFalse.setmQuestionSet(3, (String) res.getText(R.string.q4));
mTrueFalse.setmQuestionSet(4, (String) res.getText(R.string.q5));
mTrueFalse.setmArrOfBols(0, false);
mTrueFalse.setmArrOfBols(1, true);
mTrueFalse.setmArrOfBols(2, true);
mTrueFalse.setmArrOfBols(3, false);
mTrueFalse.setmArrOfBols(4, true);
}
public void checkTrue(View view) {
Resources res = this.getResources(); //this is to be able to get strings
if(mTrueFalse.getCurrentBolValue()==true)
{
result.setText((String) res.getText(R.string.right));
}
else
{
result.setText((String) res.getText(R.string.wrong));
}
}
public void checkFalse(View view) {
Resources res = this.getResources(); //this is to be able to get strings
if(mTrueFalse.getCurrentBolValue()==true)
{
result.setText((String) res.getText(R.string.wrong));
}
else
{
result.setText((String) res.getText(R.string.right));
}
}
public void goForward(View view) {
if(mTrueFalse.getmCurrentQ()<mTrueFalse.getmQuestionSet().length-1)
{
mTrueFalse.setmCurrentQ(mTrueFalse.getmCurrentQ()+1);
question.setText((String) (mTrueFalse.getCurrentQuestionStr()));
result.setText("");
}
else if(mTrueFalse.getmCurrentQ()==mTrueFalse.getmQuestionSet().length-1)
{
mTrueFalse.setmCurrentQ(0);
question.setText((String) (mTrueFalse.getCurrentQuestionStr()));
result.setText("");
}
}
public void goBack(View view) {
if(mTrueFalse.getmCurrentQ()>0)
{
mTrueFalse.setmCurrentQ(mTrueFalse.getmCurrentQ()-1);
question.setText((String) (mTrueFalse.getCurrentQuestionStr()));
result.setText("");
}
else if(mTrueFalse.getmCurrentQ()==0)
{
mTrueFalse.setmCurrentQ(mTrueFalse.getmQuestionSet().length-1); //for the purposes of the project, its setting currentQ to 4
question.setText((String) (mTrueFalse.getCurrentQuestionStr()));
result.setText("");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.quiz_me, 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);
}
}
layout xml file:
<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:orientation="vertical"
android:id="#+id/activity_view"
tools:context="com.quizme.QuizMeActivity">
<Button
android:id="#+id/true_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/sTrue"
android:layout_marginRight="180dp"
android:onClick="checkTrue"
/>
<ImageButton
android:id="#+id/forward_button"
android:contentDescription="#string/forward"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/back_button"
android:onClick="goForward"
android:src="#drawable/forward" />
<Button
android:id="#+id/false_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/question"
android:layout_toRightOf="#+id/true_button"
android:onClick="checkFalse"
android:text="#string/sFalse" />
<ImageButton
android:id="#+id/back_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="70dp"
android:contentDescription="#string/back"
android:onClick="goBack"
android:src="#drawable/back" />
<TextView
android:id="#+id/result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#string/resultStr"
android:textSize="30sp" />
<TextView
android:id="#+id/question"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/true_button"
android:layout_marginTop="34dp"
android:layout_toLeftOf="#+id/forward_button"
android:text="#string/questionStr"
android:textSize="25sp" />
</RelativeLayout>
Android Manifest:
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".QuizMeActivity"
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>
sorry for the pile of code, I am just frustrated and stuck
Try cleaning the project
Eclipse: Project->Clean
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).
When I ran the app the first activity worked but as soon as it went to the second activity it said treasure hunt has stopped working, and there was nothing under logcat or console. I am pretty sure it is a problem with level_1.java but can't figure out what. Please help thanks.
Main Activity:
package com.example.treasurehunt;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.Menu;
import android.view.View;
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 Start(View view) {
Log.d("hi", "hello");
Intent intent = new Intent(this, Level_1.class);
startActivity(intent);
finish();
}
}
Mainxml:
<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:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Treasure Hunt" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="82dp"
android:text="Start"
android:onClick="Start" />
</RelativeLayout>
`
level_1java:
package com.example.treasurehunt;
import android.os.Bundle;
import android.app.Activity;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.Menu;
import android.widget.EditText;
import android.widget.TextView;
public class Level_1 extends Activity {
private SharedPreferences settings;
private SharedPreferences.Editor editor;
TextView Clue = (TextView)findViewById(R.id.Clue);
EditText edittext = (EditText)findViewById(R.id.editText);
String hint;
String answer;
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d("hi","hello");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_level_1);
int level = settings.getInt("level", 1);
switch (level) {
case 1: level1();
break;
default:
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.level_1, menu);
return true;
}
public void level1() {
editor.putInt("level", 1); // only needs to be done for level 1
editor.commit();
Clue.setText("Bartholdi was my creator, I carry fire and knowledge, what am I?");
hint = "July IV MDCCLXXVI";
answer = "statue of liberty";
}
public void answer() {
String useranswer = edittext.toString();
if (useranswer.equalsIgnoreCase(answer)) {// if they get the correct answer
int leveltest = settings.getInt("level", 1);
editor.putInt("level", leveltest+1); //adds one level to the current level
editor.commit();
}
}
public void hint() { //function that displays the hint
}
}
level_1 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=".Level_1" >
<TextView
android:id="#+id/Clue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="116dp"
android:text="Clue" />
<EditText
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/Clue"
android:layout_centerHorizontal="true"
android:layout_marginTop="80dp"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="#+id/Submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignRight="#+id/editText"
android:layout_marginBottom="50dp"
android:text="Submit"
android:onClick="answer"/>
<Button
android:id="#+id/Hint"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/Submit"
android:layout_alignBottom="#+id/Submit"
android:layout_alignLeft="#+id/editText"
android:text="Hint"
android:onClick="Hint"/>
</RelativeLayout>
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.treasurehunt"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.treasurehunt.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.treasurehunt.Level_1"
android:label="#string/title_activity_level_1" >
</activity>
</application>
</manifest>
Seems you're having NullPointerException.
On the field declaration
TextView Clue = (TextView)findViewById(R.id.Clue);
EditText edittext = (EditText)findViewById(R.id.editText);
Move the assignments to in onCreate()
public class Level_1 extends Activity
{
// Other members ....
TextView Clue = (TextView)findViewById(R.id.Clue);
EditText edittext = (EditText)findViewById(R.id.editText);
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d("hi","hello");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_level_1);
// Assignemnts should be here
Clue = (TextView)findViewById(R.id.Clue);
edittext = (EditText)findViewById(R.id.editText);
int level = settings.getInt("level", 1);
switch (level) {
case 1: level1();
break;
default:
break;
}
}
}
I have 2 layouts in named first_activity and second_activity...
the first_activity has a single button button1 on which i have applied onclick listener to make a simple toast and i have used this first_activity in the FirstActivity...
the second_activity has a single button along with that i have included the first_activity in the second_activity so the second_activity has 2 buttons...
now have coded and run the application using FirstActivity has the main activity and the i am getting the toast onclick of 1st button...
Now the SecondActivity extends FirstActivity along its own button 2 click event...
now i have changed the start activity as SecondActivity and after running i am getting the click event of only 2nd button not of 1st button..
so where i am making mistake..
my intention is to make code reuse for example i have an app in which there are 30 layout and all the layout have common menu which is included in each layout so i just want to code for that menu once and reuse that code in all the other layout...
here are the code of my app....
first_activity:
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="200dip"
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=".FirstActivity" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1st Button" />
second_activity:
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=".FirstActivity" >
android:id="#+id/layout"/>
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/layout"
android:text="2nd Button" />
FirstActivity:
package com.example.codereuse;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class FirstActivity extends Activity {
Button b1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_activity);
b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Button 1 Clicked", Toast.LENGTH_LONG).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.main, menu);
return true;
}
}
SecondActivity:
package com.example.codereuse;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class SecondActivity extends FirstActivity {
Button b2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
b2 = (Button) findViewById(R.id.button2);
b2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Button 2 Clicked", Toast.LENGTH_LONG).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.main, menu);
return true;
}
}
AndroidMenifest:
package="com.example.codereuse"
android:versionCode="1"
android:versionName="1.0" >
android:minSdkVersion="8"
android:targetSdkVersion="17" />
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
android:name="com.example.codereuse.SecondActivity"
android:label="#string/app_name" >
android:name="com.example.codereuse.FirstActivity"
android:label="#string/app_name" >
Readers Reply very soon...
If you have 30 layouts which have the same content, then you can use one xml file for all those.
If you are using an id from one activity, there is no problem using the same id for the element in different activity.
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>