Why my app is crashing on clicking any of the buttons? - java

I am trying to use intents but on clicking any of the buttons,the app stops working and terminates.I am a beginner and I couldn't find the reason.I am providing my xml file,java file and menifest file.Please someone help.
here is my xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.shreya.intents.MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Set Alarm"
android:id="#+id/alarm"
android:onClick="setAlarm"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Map"
android:id="#+id/map"
android:onClick="seeMap"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Mail"
android:id="#+id/mail"
android:onClick="email"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Email ID"
android:inputType="textCapWords"
android:id="#+id/address"/>
</LinearLayout>
And here is my .java file:
package com.example.shreya.intents;
import android.content.Intent;
import android.net.Uri;
import android.provider.AlarmClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.util.Locale;
import static com.example.shreya.intents.R.id.alarm;
public class MainActivity extends AppCompatActivity {
private Button mail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void setAlarm(){
String message="Wake Up";
int hour=7;
int minutes=0;
Intent intent = new Intent(AlarmClock.ACTION_SHOW_ALARMS);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
public void seeMap(){
String uri = String.format(Locale.ENGLISH, "geo:%f,%f", 28.699884, 77.273075);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(uri));
if(intent.resolveActivity(getPackageManager())!=null)
startActivity(intent);
}
public void email(){
EditText mail=(EditText)findViewById(R.id.address);
String add=mail.getText().toString();
composeEmail(add,"shreya");
}
public void composeEmail(String addresses, String subject) {
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto:")); // only email apps should handle this
intent.putExtra(Intent.EXTRA_EMAIL, addresses);
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
intent.putExtra(Intent.EXTRA_TEXT,"hello");
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
}
And finally this is my menifest file:
<?xml version="1.0" encoding="utf-8"?>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

You have to add parameter View view to your onClick methods.
For example:
public void setAlarm(View view){
}
Add that parameter to other onClick methods also: email and seeMap.
Under the hood, the system uses reflection to figure out the exact onClick method in the Activity and the system uses the following exact pattern to find the method: a public void method with the specified method name in the xml onClick attribute and has a single parameter View.

Related

Android Widget freezes after some time

I have made a counter widget. There are two buttons, one to increase and one to decrease the number. The number is displayed on a TextView. At first everything works just fine, but after some time (usually around an hour) the Textview freezes i.e. I click the buttons but the number doesen't change.
When I click the buttons, the "clicking animation" is still played, so the buttons might still work.
When I remove the widget and replace it again, the widget starts to work again but the same problem occurs after around the same time.
The code is here:
WidgetProvider
package com.example.myapplication;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class WidgetProvider1 extends AppWidgetProvider {
String widgettextviewtext;
final String INCREASE= "sdfjkldjldkf";
final String DECREASE = "skdhbcvouweoaior";
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
MainActivity.zahl = 15;
remoteViews.setTextViewText(R.id.textView, ""+MainActivity.zahl);
remoteViews.setOnClickPendingIntent(R.id.button3,onClickPendingIntent(context,ZAHLGROESSER) );
remoteViews.setOnClickPendingIntent(R.id.button2,onClickPendingIntent(context,ZAHLKLEINER) );
appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
updateWidgetNow(context,remoteViews);
super.onUpdate(context, appWidgetManager, appWidgetIds);
}
#Override
public void onReceive(Context context, Intent intent) {
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
//if increase button is clicked
if(intent.getAction().equals(INCREASE)){
if(MainActivity.zahl == 15) {
Toast.makeText(context, "STOOOP!!!", Toast.LENGTH_SHORT).show();
}else{
MainActivity.number = MainActivity.number+1;
String text=""+ MainActivity.number;
remoteViews.setTextViewText(R.id.textView, text);
updateWidgetNow(context, remoteViews);
}
}
//if decrease button is clicked
if(intent.getAction().equals(DECREASE)) {
if (MainActivity.number == 0) {
Toast.makeText(context, "Hurray!", Toast.LENGTH_SHORT).show();
}else{
MainActivity.number = MainActivity.number - 1;
String text = "" + MainActivity.number;
remoteViews.setTextViewText(R.id.textView, text);
updateWidgetNow(context, remoteViews);
}
}
super.onReceive(context, intent);
}
public void updateWidgetNow (Context context, RemoteViews remoteViews){
ComponentName widgetComponent = new ComponentName(context, WidgetProvider1.class);
AppWidgetManager.getInstance(context).updateAppWidget(widgetComponent, remoteViews);
}
public PendingIntent onClickPendingIntent (Context context, String stringAction){
Intent onClickIntent = new Intent(context, WidgetProvider1.class);
onClickIntent.setAction(stringAction);
return PendingIntent.getBroadcast(context,0,onClickIntent,PendingIntent.FLAG_UPDATE_CURRENT);
}
}
MainActivity:
package com.example.myapplication;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
public static int number = 15;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.myapplication">
<uses-permission android:name="android.permission.VIBRATE"/>
<application
android:allowBackup="true"
android:dataExtractionRules="#xml/data_extraction_rules"
android:fullBackupContent="#xml/backup_rules"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.MyApplication"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true"
android:label="#string/app_name"
android:theme="#style/Theme.MyApplication">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="com.example.myapplication.WidgetProvider1"
android:label="Tutorial Widget"
android:exported="true"
>
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE"/>
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="#xml/widget_info"
/>
</receiver>
</application>
</manifest>
WidgetInfo:
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider
xmlns:android="http://schemas.android.com/apk/res/android"
android:minHeight="180dp"
android:minWidth="180dp"
android:initialLayout="#layout/widget_layout"
android:previewImage="#drawable/widget_preview"
android:widgetCategory="home_screen"
android:resizeMode="horizontal|vertical"
>
</appwidget-provider>
WidgeLayout:
<?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"
android:theme="#style/Theme.AppCompat.Light"
android:id="#+id/widget_layout"
>
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="220dp"
android:layout_centerInParent="true"
android:text="1"
android:textAlignment="center"
android:textSize="150dp"
android:textColor="#color/white"
/>
<Button
android:id="#+id/button3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/textView"
android:layout_marginBottom="1dp"
android:text="increase"
android:bottomRightRadius="20dp"
android:bottomLeftRadius="20dp"
android:topLeftRadius="20dp"
android:topRightRadius="20dp"
android:textSize="30dp"
/>
<Button
android:id="#+id/button2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/textView"
android:layout_marginTop="1dp"
android:text="decrease"
android:bottomRightRadius="20dp"
android:bottomLeftRadius="20dp"
android:topLeftRadius="20dp"
android:topRightRadius="20dp"
android:textSize="30dp"
/>
</RelativeLayout>

how can i play sound in android

I wrote simplw android program to play sound and it's not working . Have no idea why .
maybe it's related to the fact that i have question mark near mymp3 file ( under raw directory ).
I tried few options without any suseess .
Attached below is my code , thanks in advance .
xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
android:background="#CFEC89"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:layout_width="200dp"
android:layout_height="80dp"
android:id="#+id/sound"
android:layout_marginTop="1dp"
android:layout_marginBottom="1dp"
android:layout_marginLeft="1dp"
android:layout_marginRight="1dp"
android:layout_gravity="center"
android:text="Sound"
android:textSize="30sp"
android:background="#EAE3E3"
/>
</LinearLayout>
main acitivy java
package com.example.playsound;
import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener
{
// define my variables
Button sound;
final MediaPlayer mp = MediaPlayer.create(this,R.raw.cat);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onClick(View v)
{
mp.start();
}
}
and my manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.playsound">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.PlaySound">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
First of all, delete your TextView it could lay over your Button. That's why you probably can't click it.
Paste that in your class:
package com.example.playsound;
import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.cat);
final Button sound = (Button) this.findViewById(R.id.sound);
sound.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.start();
}
});
}
}
For the future, you need to define your variables in the OnCreate and not above.

Broadcast receiver not working in Android Studio 4.0.0

I am new to Android Studio and the broadcast receiver is not working.
"Broadcast Received!!!" doesn't appear on the screen.
Android Studio version: 4.0
Android Version in the emulator: Android 10 (Q)
SendBroadcast Project:
MainActivity.java:
package com.example.sendbroadcast;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void sendBroadcast(View view) {
Intent intent = new Intent();
intent.setAction("com.example.sendbroadcast");
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
sendBroadcast(intent);
System.out.println("Sent!!!");
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="#+id/send_broadcast_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="sendBroadcast"
android:text="Send Broadcast"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
ReceiveBroadcast project:
MyReceiver.java:
package com.example.recievebroadcast;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("Received!!!");
Toast.makeText(context, "Broadcast Received!!!", Toast.LENGTH_LONG).show();
}
}
AndroidManifest.xml :
<?xml version="1.0" encoding="utf-8"?>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="true"
>
<intent-filter>
<action android:name="com.example.sendbroadcast"></action>
</intent-filter>
</receiver>
</application>
Implicit broadcasts like this one have been blocked on Android since Android 8.0, nearly three years ago.
Implicit broadcasts are blocked to prevent unwanted apps from matching your intent and starting (that's why they will only work with receivers registered at runtime).
Since you're sending broadcast to specific receiver you can modify your intent to be explicit by declaring target package:
public void sendBroadcast(View view) {
Intent intent = new Intent();
intent.setAction("com.example.sendbroadcast");
// add this line to have intent delivered explicitly to your app
// use package name of your ReceiveBroadcast project
intent.setPackage("com.example.recievebroadcast");
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
sendBroadcast(intent);
System.out.println("Sent!!!");
}

Android Studio emulator white screen upon opening of app

Whenever I install and run my app in the Android Studio emulator all I get is a white screen and the tool bar above it even though in the preview it works completely fine. Heres the xml code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:background="#drawable/rectanglestemlogo"
android:orientation="horizontal">
<Button
android:id="#+id/Home_Button"
android:layout_width="0dp"
android:layout_weight="0.33"
android:layout_height="wrap_content"
android:onClick="goToStemAcademy"
android:text="#string/Home_Button"
android:textAllCaps="false"
android:textColor="#000000" />
<Button
android:id="#+id/StemAcademy_Button"
android:layout_width="0dp"
android:layout_weight="0.33"
android:layout_height="wrap_content"
android:layout_marginEnd="0dp"
android:text="#string/Stem_Academy"
android:textAllCaps="false"
android:textColor="#000000"
android:visibility="visible" />
<Button
android:id="#+id/Competitions_Button"
android:layout_width="0dp"
android:layout_weight="0.33"
android:layout_height="wrap_content"
android:layout_marginEnd="2dp"
android:text="#string/Competitions"
android:textAllCaps="false"
android:textColor="#000000" />
</LinearLayout>
then the java:
package com.example.dmssteamapp6;
import android.content.Intent;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
public void goToStemAcademy(View v) {
startActivity(new Intent(MainActivity.this, StemAcademy.class));
}
}
then the new xml activity:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/button"
android:layout_width="match_parent"
android:layout_height="138dp"
android:onClick="goToHome"
android:text="Button" />
</LinearLayout>
and the java that goes with it:
package com.example.dmssteamapp6;
import android.content.Intent;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
public class StemAcademy extends AppCompatActivity {
public void goToHome(View v) {
startActivity(new Intent(StemAcademy.this, MainActivity.class));
}
}
also here is the androidmanifest.xml code if applicable:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.dmssteamapp6">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<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>
<activity
android:name=".StemAcademy"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
</activity>
</application>
</manifest>
Just Create onCreate method in every java class
public class StemAcademy extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stemacademy);
}
public void goToHome(View v) {
startActivity(new Intent(StemAcademy.this, MainActivity.class));
}
}
Activity main class
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void goToStemAcademy(View v) {
startActivity(new Intent(MainActivity.this, StemAcademy.class));
}
}

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.myfirstapp/com.example.myfirstapp.DisplayMessageActivity}

I’m following the android tutorial First App in the link below:
https://developer.android.com/training/basics/firstapp/starting-activity.html
The app can be launched in the emulator but the problem is when I click on the button “send, the application crashed with the message “unfortunately, my fist app has stopped”.
I think I did follow the instructions in the tutorial and can’t figure out where is the problem from.
Logcat send this message:
02-12 16:19:36.031: E/AndroidRuntime(786): java.lang.RuntimeException:
Unable to instantiate activity
ComponentInfo{com.example.myfirstapp/com.example.myfirstapp.DisplayMessageActivity}:
java.lang.NullPointerException
activity_main.xml
<LinearLayout 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="horizontal">
<EditText android:id="#+id/edit_message"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="#string/edit_message" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_send"
android:onClick="sendMessage" />
</LinearLayout>
MAinActivity.java
package com.example.myfirstapp;
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";
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
// Do something in response to button
}
#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;
}
}
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:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
</RelativeLayout>
DisplayMessageActivity.java
package com.example.myfirstapp;
import android.annotation.SuppressLint;
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.MenuItem;
import android.widget.TextView;
public class DisplayMessageActivity extends Activity {
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
#SuppressLint("NewApi")
#Override
public 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);
// Make sure we're running on Honeycomb or higher to use ActionBar APIs
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// Show the Up button in the action bar.
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
MyFirstApp Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myfirstapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.myfirstapp.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.myfirstapp.DisplayMessageActivity"
android:label="#string/title_activity_display_message"
android:parentActivityName="com.example.myfirstapp.MainActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.myfirstapp.MainActivity" />
</activity>
</application>
</manifest>
Thank you for your help
I believe the problem is
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
before onCreate(). Intent needs a Context which isn't available until the Activity has been created. Remove those lines since you already have it in onCreate().
Also, when it crashes, post your full logcat because it will tell us, usually, exactly where and what the problem is.

Categories

Resources