Can't get simple android calculator app to run - java

I have been spending a little time going over some of Google's android tutorials, and decided to throw together my own simple calculator application. I know a good bit of JAVA, and have messed around a little bit of Android back a few SDKs ago. I think the code is fine, but I just can't get the bastard to run. I have been trying to find an answer based on my LogCat stuff, but have had no luck. First, here is my MainActivity.java:
package com.AppliedArgonautics.calculator;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
EditText editText1 = (EditText)findViewById(R.id.editText1);
EditText editText2 = (EditText)findViewById(R.id.editText2);
TextView textView1 = (TextView)findViewById(R.id.textView1);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void Add(){
float num1 = Float.parseFloat(editText1.getText().toString());
float num2 = Float.parseFloat(editText2.getText().toString());
float result = num1 + num2;
textView1.setText(Float.toString(result));
}
public void Subtract(){
float num1 = Float.parseFloat(editText1.getText().toString());
float num2 = Float.parseFloat(editText2.getText().toString());
float result = num1 - num2;
textView1.setText(Float.toString(result));
}
public void Multiply(){
float num1 = Float.parseFloat(editText1.getText().toString());
float num2 = Float.parseFloat(editText2.getText().toString());
float result = num1 * num2;
textView1.setText(Float.toString(result));
}
public void Divide(){
float num1 = Float.parseFloat(editText1.getText().toString());
float num2 = Float.parseFloat(editText2.getText().toString());
float result = num1 / num2;
textView1.setText(Float.toString(result));
}
public void Clear(){
editText1.setText("");
editText2.setText("");
textView1.setText("");
}
}
My manifest file:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.AppliedArgonautics.calculator"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
then, 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" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="32dp"
android:onClick="Add"
android:text="Add" />
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/button1"
android:layout_below="#+id/button1"
android:layout_marginTop="45dp"
android:onClick="Multiply"
android:text="Multiply" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/button3"
android:layout_alignParentRight="true"
android:layout_marginRight="28dp"
android:onClick="Subtract"
android:text="Subtract" />
<Button
android:id="#+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/button3"
android:layout_alignBottom="#+id/button3"
android:layout_alignLeft="#+id/button2"
android:onClick="Divide"
android:text="Divide" />
<Button
android:id="#+id/button5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/button1"
android:layout_centerHorizontal="true"
android:onClick="Clear"
android:text="Clear" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignRight="#+id/button1"
android:layout_marginTop="37dp"
android:ems="10"
android:inputType="phone" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/editText1"
android:layout_alignLeft="#+id/button2"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/editText1"
android:ems="10"
android:inputType="phone" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/button5"
android:layout_below="#+id/editText1"
android:layout_marginTop="56dp"
android:text="TextView" />
</RelativeLayout>
This is what LogCat shows when I try to run it:
/Trace ( 3186): error opening trace file: No such file or directory (2)
D/AndroidRuntime( 3186): Shutting down VM
W/dalvikvm( 3186): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
E/AndroidRuntime( 3186): FATAL EXCEPTION: main
E/AndroidRuntime( 3186): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.AppliedArgonautics.calculator/com.AppliedArgonautics.calculator.MainActivi ty}: java.lang.NullPointerException
E/AndroidRuntime( 3186): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1983)
E/AndroidRuntime( 3186): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
E/AndroidRuntime( 3186): at android.app.ActivityThread.access$600(ActivityThread.java:130)
E/AndroidRuntime( 3186): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
E/AndroidRuntime( 3186): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime( 3186): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime( 3186): at android.app.ActivityThread.main(ActivityThread.java:4745)
E/AndroidRuntime( 3186): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime( 3186): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime( 3186): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
E/AndroidRuntime( 3186): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
E/AndroidRuntime( 3186): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime( 3186): Caused by: java.lang.NullPointerException
E/AndroidRuntime( 3186): at android.app.Activity.findViewById(Activity.java:1825)
E/AndroidRuntime( 3186): at com.AppliedArgonautics.calculator.MainActivity.<init>(MainActivity.java:10)
E/AndroidRuntime( 3186): at java.lang.Class.newInstanceImpl(Native Method)
E/AndroidRuntime( 3186): at java.lang.Class.newInstance(Class.java:1319)
E/AndroidRuntime( 3186): at android.app.Instrumentation.newActivity(Instrumentation.java:1053)
E/AndroidRuntime( 3186): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1974)
E/AndroidRuntime( 3186): ... 11 more
W/ActivityManager( 160): Force finishing activity com.AppliedArgonautics.calculator/.MainActivity
I would really appreciate it if someone could have a look at this. I thought it would be cool to learn android, but am getting very frustrated with my inability to get even a simple program like this to launch. Thank you.

There may be lot of issues in your code, but first to get you started:
Create EditText and TextView as instance variables. Assign views to those variables in onCreate.
public class MainActivity extends Activity {
EditText editText1;
EditText editText2;
TextView textView1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText1 = (EditText)findViewById(R.id.editText1);
editText2 = (EditText)findViewById(R.id.editText2);
textView1 = (TextView)findViewById(R.id.textView1);
}
.........
}

I did here for adding the values.. Your created the button in xml but, not using in java code..
we need to do our stuff under button click listener...
public class MainActivity extends Activity {
EditText editText1 ;
EditText editText2 ;
TextView textView1 ;
float num1, num2,result;
Button add;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText1 = (EditText)findViewById(R.id.editText1);
editText2 = (EditText)findViewById(R.id.editText2);
textView1 = (TextView)findViewById(R.id.textView1);
add = (Button)findViewById(R.id.button1);
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
num1 = Float.parseFloat(editText1.getText().toString());
num2 = Float.parseFloat(editText2.getText().toString());
result = num1 + num2;
textView1.setText(Float.toString(result));
}
});
}
}
Apply the same thing for all methods...
Hope, this will helps you..

I loaded up your application, and ran the application in debug mode. It broke on the line
EditText editText1 = (EditText)findViewById(R.id.editText1);
It was throwing a null pointer exception because you have not yet loaded your layout. This happens in your OnCreate function.
The solution is to shift the findViewById command into your onCreate function after the SetContentView command. Ie:
public class MainActivity extends Activity {
EditText editText1;
EditText editText2;
TextView textView1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText1 = (EditText)findViewById(R.id.editText1);
editText2 = (EditText)findViewById(R.id.editText2);
textView1 = (TextView)findViewById(R.id.textView1);
}
Your next issues are that the functions that your Add, Subtract, etc functions all need to take a parameter of type View. This is the reference back to the button that was clicked. (Otherwise you get an IllegalStateException when it can't find the function to call)
Then it's going to fail on Float.parseFloat(editText1.getText().toString()) because the the editText contains blank, not a number. You'll want to either force the edit texts to always have a valid number, or modify your functions to cater for empty strings.
Good luck from here! :)

write these
EditText editText1;
EditText editText2;
TextView textView1 ;
instead of these
EditText editText1 = (EditText)findViewById(R.id.editText1);
EditText editText2 = (EditText)findViewById(R.id.editText2);
TextView textView1 = (TextView)findViewById(R.id.textView1);
and change this
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
to
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText1 = (EditText)findViewById(R.id.editText1);
editText2 = (EditText)findViewById(R.id.editText2);
textView1 = (TextView)findViewById(R.id.textView1);
}
You are getting error because you are trying to access the views without specifying which layout you are considering.
setContentView(R.layout.activity_main);
specifies the layout you are considering

Related

App stopped working as soon as i clicked the button

I built a simple project that squares a given number. In that app as soon as i click the button "Calculate" it say's "Unfortunately, SquareCalculator has stopped". What should i do to resolve the problem?
Below is my entire code:-
MainActivity.java
package thenerdimite.squarecalculator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
protected void calculate (View v){
EditText input = (EditText) findViewById(R.id.etInput);
TextView output = (TextView) findViewById(R.id.tvOutput);
int base = Integer.valueOf(input.getText().toString());
int result = base * base;
String formattedResult = String.format("%,d", result);
output.setText("Result: " + formattedResult);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="thenerdimite.squarecalculator.MainActivity">
<EditText
android:id="#+id/etInput"
android:layout_width="245dp"
android:layout_height="41dp"
android:layout_marginTop="15dp"
android:ems="10"
android:inputType="number"
tools:layout_editor_absoluteX="16dp"
tools:layout_editor_absoluteY="62dp"
android:layout_below="#+id/tvInput"
android:layout_alignStart="#+id/tvInput" />
<Button
android:id="#+id/btnCalculate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/etInput"
android:layout_below="#+id/etInput"
android:layout_marginTop="20dp"
android:onClick="Calculate"
android:text="Calculate"
android:textSize="18sp" />
<TextView
android:id="#+id/tvOutput"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Result:"
android:textAppearance="#style/TextAppearance.AppCompat.Display1"
android:layout_below="#+id/btnCalculate"
android:layout_alignStart="#+id/btnCalculate"
android:layout_marginTop="18dp" />
<TextView
android:id="#+id/tvInput"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter an Integer:"
android:textAppearance="#style/TextAppearance.AppCompat.Display1"
android:layout_marginStart="19dp"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
logcat
04-25 09:28:05.060 3596-3596/thenerdimite.squarecalculator D/AndroidRuntime: Shutting down VM
04-25 09:28:05.060 3596-3596/thenerdimite.squarecalculator W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0xa5007678)
04-25 09:28:05.060 3596-3596/thenerdimite.squarecalculator E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.IllegalStateException: Could not find method Calculate(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'btnCalculate'
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:327)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
at android.view.View.performClick(View.java:4240)
at android.view.View$PerformClick.run(View.java:17721)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
04-25 09:28:06.740 3596-3596/? I/Process: Sending signal. PID: 3596 SIG: 9
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="thenerdimite.squarecalculator">
<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>
</manifest>
Using the documentation of Button
You see the method need to be public and accept a View
In order for this to work, the method must be public and accept a View as its only parameter.
So it should be
public void Calculate (View v){
Using the xml notation, of course, you should call it calculate and correct the XML
From what I see, the problem is that your button action is android:onClick="Calculate" but should be android:onClick="calculate"
you need to make the method public, protected and private methods are not accessible by xml.
public void calculate (View v){
EditText input = (EditText) findViewById(R.id.etInput);
TextView output = (TextView) findViewById(R.id.tvOutput);
int base = Integer.valueOf(input.getText().toString());
int result = base * base;
String formattedResult = String.format("%,d", result);
output.setText("Result: " + formattedResult);
}
Change android:onClick="Calculate" to android:onClick="calculate".
Also calculate method should be public.
In XML you have "Calculate" with capital "C" while method is called "calculate". Change XML and it should work.
https://developer.android.com/reference/android/widget/Button.html

java android crash setOnClickListener

i am new in android and i was trying to make my app works in all phones
it works in 23 API and don't work in 19 API kitkat it crashes each time i open the application
Is there a way to fix this problem ?
and could you tell me what was my problem and explain it to me,
public class MainActivity extends AppCompatActivity {
private Button ButtonStart,ButtonReset ;
private TextView Number ;
private CountDownTimer myTimer ;
private MediaPlayer TimePassesSound;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButtonStart = (Button)findViewById (R.id.button); //initialize view
Number = (TextView)findViewById (R.id.textView); //initialize view
ButtonReset = (Button)findViewById (R.id.button2);
MediaPlayer TimePassesSound;
TimePassesSound = new MediaPlayer();
TimePassesSound = MediaPlayer.create(getApplicationContext(), R.raw.time_passing);
addListerOnButton (); //call method of the view
addListerOnButton2 (); //call method of the view
}
public void addListerOnButton () {
ButtonStart.setOnClickListener (
new View.OnClickListener () {
public void onClick(View v) {
if (ButtonStart.getText ().toString () != "Stop") {
int StartTime = Integer.parseInt (Number.getText ().toString ());
myTimer = new CountDownTimer (StartTime*1000, 1000) {
public void onTick(long millisUntilFinished) {
ButtonStart.setText ("Stop");
Number.setText (""+millisUntilFinished / 1000);
}
public void onFinish() {
Number.setText("60");
ButtonStart.setText ("Start");
TimePassesSound.setLooping(false);
TimePassesSound.start();
}
}.start();
} else {
ButtonStart.setText ("Start");
myTimer.cancel ();
}
}
}
);
}
public void addListerOnButton2 () {
ButtonReset.setOnClickListener (
new View.OnClickListener () {
public void onClick(View v) {
if ("Start".equals (ButtonStart.getText ().toString())) {
Number.setText ("60");
myTimer.cancel ();
}else{
Toast.makeText (MainActivity.this,"You must stop the countdown first",Toast.LENGTH_LONG).show();
}
}
}
);
}
}
public void addListerOnButton2 () {
ButtonReset.setOnClickListener (
new View.OnClickListener () {
public void onClick(View v) {
if ("Start".equals (ButtonStart.getText ().toString())) {
Number.setText ("60");
myTimer.cancel ();
}else{
Toast.makeText (MainActivity.this,"You must stop the countdown first",Toast.LENGTH_LONG).show();
}
}
}
);
}
}
-- Error messages
Process: com.aabdelrahman730yahoo.mydesign, PID: 3627
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.aabdelrahman730yahoo.mydesign/com.aabdelrahman730yahoo.mydesign.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.aabdelrahman730yahoo.mydesign.MainActivity.addListerOnButton(MainActivity.java:51)
at com.aabdelrahman730yahoo.mydesign.MainActivity.onCreate(MainActivity.java:43)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245) 
at android.app.ActivityThread.access$800(ActivityThread.java:135) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:136) 
at android.app.ActivityThread.main(ActivityThread.java:5017) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 
at dalvik.system.NativeStart.main(Native Method) 
Main Activity :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_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.aabdelrahman730yahoo.mydesign.MainActivity"
android:touchscreenBlocksFocus="false"
android:background="#34416a">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start"
android:id="#+id/button"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Reset"
android:id="#+id/button2"
android:layout_above="#+id/button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="60"
android:id="#+id/textView"
android:singleLine="true"
android:textSize="80dp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"/>
That's was my full problem i hope someone could help me with
You are calling the method of the view without initializing it.
You need to initialize the view first and then call the method
ButtonStart = (Button)findViewById (R.id.button); //initialize view
Number = (TextView)findViewById (R.id.textView); //initialize view
addListerOnButton (); //call method of the view
addListerOnButton2 (); //call method of the view
Check this,
As #Rod_ mentioned and from error log, it clearly states that view is not initialized.
java.lang.NullPointerException
at
com.aabdelrahman730yahoo.mydesign.MainActivity.addListerOnButton(MainActivity.java:51)
at
com.aabdelrahman730yahoo.mydesign.MainActivity.onCreate(MainActivity.java:43)
Make sure following buttons were initialized in your java code.
ButtonStart and ButtonReset -- Buttonreset is not initialized here it seems.
Change your code like below.
under oncreate
ButtonStart = (Button)findViewById (R.id.button);
ButtonReset = (Button)findViewById (R.id.button_); --> You missed it ..
Number = (TextView)findViewById (R.id.textView);
addListerOnButton ();
addListerOnButton2 ();
Hope it seems clear..!!
UPDATE:
You may not initialized the media player.
The problem may be also due to usage of media player. Kindly check the code below.
MediaPlayer mediaPlayer;
mediaPlayer = new MediaPlayer();
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.time_passing);
in your case
MediaPlayer TimePassesSound;
TimePassesSound = new MediaPlayer();
TimePassesSound = MediaPlayer.create(getApplicationContext(), R.raw.time_passing);
Add the above lines befor calling the functions.

getting null pointer exception

I am getting a NullPointerException when I try to access text view which is defined in view class. I am accessing it from setting class. A small part of my code is:
view class
public class view1 extends menu {
public static TextView text1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
text1=(TextView)findViewById(R.id.textfile1);
text1.setText("product");
}
public void small(String mytext) { // this is my method which I want to access
text1.setText(mytext);
}
}
setting class
public class Setting extends Activity {
private Spinner spinner1;
private Button apply;
TextView small1;
private view1 view11;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.setting);
//setContentView(R.layout.view);
addItemsOnSpinner1();
addListenerOnSpinnerItemSelection();
}
public void addItemsOnSpinner1() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
List<String> list = new ArrayList<String>();
list.add("Small");
list.add("Medium");
list.add("Large");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(dataAdapter);
}
public void addListenerOnSpinnerItemSelection() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
apply = (Button) findViewById(R.id.apply);
spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
apply.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String mytext = "Something else";
view11.small(mytext);
}
Stack trace
01-17 00:11:02.064: E/AndroidRuntime(4191): FATAL EXCEPTION: main
01-17 00:11:02.064: E/AndroidRuntime(4191): java.lang.NullPointerException
01-17 00:11:02.064: E/AndroidRuntime(4191): at com.ramanrayat.notelet.Setting$1.onClick(Setting.java:106)
01-17 00:11:02.064: E/AndroidRuntime(4191): at android.view.View.performClick(View.java:4240)
01-17 00:11:02.064: E/AndroidRuntime(4191): at android.view.View$PerformClick.run(View.java:17721)
01-17 00:11:02.064: E/AndroidRuntime(4191): at android.os.Handler.handleCallback(Handler.java:730)
01-17 00:11:02.064: E/AndroidRuntime(4191): at android.os.Handler.dispatchMessage(Handler.java:92)
01-17 00:11:02.064: E/AndroidRuntime(4191): at android.os.Looper.loop(Looper.java:137)
01-17 00:11:02.064: E/AndroidRuntime(4191): at android.app.ActivityThread.main(ActivityThread.java:5103)
01-17 00:11:02.064: E/AndroidRuntime(4191): at java.lang.reflect.Method.invokeNative(Native Method)
01-17 00:11:02.064: E/AndroidRuntime(4191): at java.lang.reflect.Method.invoke(Method.java:525)
01-17 00:11:02.064: E/AndroidRuntime(4191): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
01-17 00:11:02.064: E/AndroidRuntime(4191): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-17 00:11:02.064: E/AndroidRuntime(4191): at dalvik.system.NativeStart.main(Native Method)
setting.xml code
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="horizontal" >
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="38dp"
android:text="Setting"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="40dp" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView2"
android:layout_centerHorizontal="true"
android:layout_marginTop="57dp"
android:gravity="center"
android:text="Font Size"
android:textSize="30dp" />
<Spinner
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1"
android:layout_marginTop="30dp" />
<Button
android:id="#+id/apply"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_alignRight="#+id/textView2"
android:layout_below="#+id/spinner1"
android:layout_marginTop="58dp"
android:text="Apply" />
</RelativeLayout>
Chnage
if(String.valueOf(spinner1.getSelectedItem())=="Small")
TO
if(String.valueOf(spinner1.getSelectedItem()).equals("Small"))
Use .equals or .equalsIgnoreCase to compare strings
Instead of making textview static you should use intents to pass values between activities.
Intent intent = new Intent(ActivityName.this,Settings.class);
intent.putExtra("key",text1.getText().toString());
startActivity(intent);
Then
String value = getIntent().getStringExtra("key");
Change
public static TextView text1;
to
public TextView text1;
Also follow java naming conventions
Replace
public static TextView text1;
with
TextView text1;
text1 can not be static.
Next time, please click on the file name in the error log and indicate which line number in your code listing is the line that the error actually points to.
Learn to start all your class names with capital letters (athough, this is not what's causing the problem). And while I'm at it, please stop using numbers in class names and in variables, especially the number 1, which can be ambiguously read as an "l" in some fonts.
Look for your LogCat, it will told you where is NPE.
The other question is : don't use equals to compare String instead of ==
== is compare two object's address and equals is compare their value.
if(String.valueOf(spinner1.getSelectedItem()).equals("Small")) {
String mytext = "Something else ";
view11.small(mytext); // view11 is clas view1 reference
}
else if(String.valueOf(spinner1.getSelectedItem()).equals("Medium")) {
finish();
}

java.lang.NullPointerException Cant figure out what is causing the error

I am creating a VERY basic POS system for an assignment for class. I keep getting that dreaded nullpointerexception. I know the error is coming from line 72 in main activity but it is declared in both the main activity and in the xml.
Here is the logcat:
10-07 18:05:36.946: D/AndroidRuntime(1279): Shutting down VM
10-07 18:05:36.946: W/dalvikvm(1279): threadid=1: thread exiting with uncaught exception (group=0x414c4700)
10-07 18:05:36.958: E/AndroidRuntime(1279): FATAL EXCEPTION: main
10-07 18:05:36.958: E/AndroidRuntime(1279): java.lang.RuntimeException: Unable to start activity ComponentInfo{hotchkissmobilesolutions.kudlerpos/hotchkissmobilesolutions.kudlerpos.MainActivity}: java.lang.NullPointerException
10-07 18:05:36.958: E/AndroidRuntime(1279): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
10-07 18:05:36.958: E/AndroidRuntime(1279): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
10-07 18:05:36.958: E/AndroidRuntime(1279): at android.app.ActivityThread.access$600(ActivityThread.java:141)
10-07 18:05:36.958: E/AndroidRuntime(1279): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
10-07 18:05:36.958: E/AndroidRuntime(1279): at android.os.Handler.dispatchMessage(Handler.java:99)
10-07 18:05:36.958: E/AndroidRuntime(1279): at android.os.Looper.loop(Looper.java:137)
10-07 18:05:36.958: E/AndroidRuntime(1279): at android.app.ActivityThread.main(ActivityThread.java:5103)
10-07 18:05:36.958: E/AndroidRuntime(1279): at java.lang.reflect.Method.invokeNative(Native Method)
10-07 18:05:36.958: E/AndroidRuntime(1279): at java.lang.reflect.Method.invoke(Method.java:525)
10-07 18:05:36.958: E/AndroidRuntime(1279): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
10-07 18:05:36.958: E/AndroidRuntime(1279): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-07 18:05:36.958: E/AndroidRuntime(1279): at dalvik.system.NativeStart.main(Native Method)
10-07 18:05:36.958: E/AndroidRuntime(1279): Caused by: java.lang.NullPointerException
10-07 18:05:36.958: E/AndroidRuntime(1279): at hotchkissmobilesolutions.kudlerpos.MainActivity.onCreate(MainActivity.java:72)
10-07 18:05:36.958: E/AndroidRuntime(1279): at android.app.Activity.performCreate(Activity.java:5133)
10-07 18:05:36.958: E/AndroidRuntime(1279): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
10-07 18:05:36.958: E/AndroidRuntime(1279): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
10-07 18:05:36.958: E/AndroidRuntime(1279): ... 11 more
Here is the android manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="hotchkissmobilesolutions.kudlerpos"
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="hotchkissmobilesolutions.kudlerpos.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>
here is the Main Activity:
package hotchkissmobilesolutions.kudlerpos;
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.GridLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
double dairy = 4.99, seafood = 15.99, wine = 20, meat = 5.99,
cheese = 2.99, fruit = 1.99, vegetable = 0.69;
double total, tax = 0.0725;
String total2;
Button btnDairy, btnSeafood, btnWine, btnMeat, btnFruit, btnVegetable,
btnTotal, btnClear;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnDairy = (Button) findViewById(R.id.btnDairy);
btnSeafood = (Button) findViewById(R.id.btnSeafood);
btnWine = (Button) findViewById(R.id.btnWine);
btnMeat = (Button) findViewById(R.id.btnMeat);
btnFruit = (Button) findViewById(R.id.btnFruit);
btnVegetable = (Button) findViewById(R.id.btnVegetable);
btnClear = (Button) findViewById(R.id.btnClear);
btnDairy.setOnClickListener(new OnClickListener() {
public void onClick(View V) {
total = (total + dairy) + (total * tax);
System.out.println(total);
}
});
btnSeafood.setOnClickListener(new OnClickListener() {
public void onClick(View V) {
total = (total + seafood) + (total * tax);
System.out.println(total);
}
});
btnWine.setOnClickListener(new OnClickListener() {
public void onClick(View V) {
total = (total + wine) + (total * tax);
System.out.println(total);
}
});
btnMeat.setOnClickListener(new OnClickListener() {
public void onClick(View V) {
total = (total + meat) + (total * tax);
System.out.println(total);
}
});
btnFruit.setOnClickListener(new OnClickListener() {
public void onClick(View V) {
total = (total + fruit) + (total * tax);
System.out.println(total);
}
});
btnVegetable.setOnClickListener(new OnClickListener() {
public void onClick(View V) {
total = (total + vegetable) + (total * tax);
System.out.println(total);
}
});
btnTotal.setOnClickListener(new OnClickListener() {
public void onClick(View V) {
total2 = new Double(total).toString();
final TextView textView = (TextView) findViewById(R.id.textViewTotal);
textView.setText(total2);
System.out.println(total);
System.out.println(total2);
}
});
btnClear.setOnClickListener(new OnClickListener() {
public void onClick(View V) {
total = 0;
total2 = new Double(total).toString();
final TextView textView = (TextView) findViewById(R.id.textViewTotal);
textView.setText(total2);
System.out.println(total);
}
});
}
and here is the activity_main.xml:
<?xml version="1.0" encoding="UTF-8"?>
<GridLayout
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:columnCount="6"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:rowCount="8"
tools:context=".MainActivity"
tools:targetApi="14" >
<TextView android:id="#+id/txtViewInstructions"
android:layout_column="0"
android:layout_gravity="left|top"
android:layout_row="0"
android:text="#string/InstructionText"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button android:id="#+id/btnDairy"
android:layout_column="0"
android:layout_gravity="left|top"
android:layout_row="3"
android:onClick="onCLickDairy"
android:text="#string/Dairy" />
<Button android:id="#+id/btnWine"
android:layout_column="0"
android:layout_gravity="center_horizontal|top"
android:layout_row="3"
android:onClick="onCLickWine"
android:text="#string/Wine" />
<Button android:id="#+id/btnMeat"
android:layout_column="0"
android:layout_gravity="left|top"
android:layout_row="4"
android:onClick="onCLickMeat"
android:text="#string/Meat" />
<Button android:id="#+id/btnSeafood"
android:layout_column="0"
android:layout_gravity="center_horizontal|top"
android:layout_row="4"
android:onClick="onCLickSeafood"
android:text="#string/Seafood" />
<Button android:id="#+id/btnVegetable"
android:layout_column="0"
android:layout_gravity="left|top"
android:layout_row="5"
android:onClick="onCLickVegetable"
android:text="#string/Vegetable" />
<TextView android:id="#+id/txtViewTotalDue"
android:layout_column="0"
android:layout_gravity="left|top"
android:layout_row="7"
android:text="#string/TotalDue"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView android:id="#+id/textViewTotal"
android:layout_width="260dp"
android:layout_height="93dp"
android:layout_column="0"
android:layout_gravity="left|bottom"
android:layout_row="6"
android:text="#string/total"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button android:id="#+id/btnTotal"
android:layout_column="0"
android:layout_gravity="left|center_vertical"
android:layout_row="7"
android:onClick="onCLickTotal"
android:text="#string/TotalButton" />
<Button android:id="#+id/btnFruit"
android:layout_column="0"
android:layout_gravity="center_horizontal|top"
android:layout_row="5"
android:onClick="onCLickFruit"
android:text="#string/Fruit" />
<Button android:id="#+id/btnClear"
android:layout_column="0"
android:layout_gravity="left|bottom"
android:layout_row="7"
android:text="#string/ClearButton" />
</GridLayout>
Any help in finding the issue with the btnTotal line in the main activity.java would be so helpful. Thanks in advance!
You don't have a btnTotal so when you click on it, the value is null.
See:
btnDairy = (Button) findViewById(R.id.btnDairy);
btnSeafood = (Button) findViewById(R.id.btnSeafood);
btnWine = (Button) findViewById(R.id.btnWine);
btnMeat = (Button) findViewById(R.id.btnMeat);
btnFruit = (Button) findViewById(R.id.btnFruit);
btnVegetable = (Button) findViewById(R.id.btnVegetable);
btnClear = (Button) findViewById(R.id.btnClear);
//add this
btnTotal = (Button) findViewById(R.id.btnTotal);
No button for btnTotal. Add that button and you'll be fine. Simple mistake. Happens all the time. Good luck.
You did not initialise your total field, so it throws NPE

whenever application is executed it is displayed as blank in android emulator

Below i have pasted copy of my java,xml and logcat of the application.
Here goes my java code
package my.example.myproject;
import my.example.myproject.util.SystemUiHider;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
/**
* An example full-screen activity that shows and hides the system UI (i.e.
* status bar and navigation/system bar) with user interaction.
*
* #see SystemUiHider
*/
public class FullscreenActivity extends Activity {
/**
* Whether or not the system UI should be auto-hidden after
* {#link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
*/
private static final boolean AUTO_HIDE = true;
/**
* If {#link #AUTO_HIDE} is set, the number of milliseconds to wait after
* user interaction before hiding the system UI.
*/
private static final int AUTO_HIDE_DELAY_MILLIS = 3000;
/**
* If set, will toggle the system UI visibility upon interaction. Otherwise,
* will show the system UI visibility upon interaction.
*/
private static final boolean TOGGLE_ON_CLICK = true;
/**
* The flags to pass to {#link SystemUiHider#getInstance}.
*/
private static final int HIDER_FLAGS = SystemUiHider.FLAG_HIDE_NAVIGATION;
/**
* The instance of the {#link SystemUiHider} for this activity.
*/
private SystemUiHider mSystemUiHider;
Button iol,help,about;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen);
final View controlsView = findViewById(R.id.fullscreen_content_controls);
iol = (Button)findViewById(R.id.iolCalculation);
help = (Button)findViewById(R.id.sHelp);
about = (Button)findViewById(R.id.sAbout);
Thread iolthread=new Thread(){
public void run(){
try{
iol.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
setContentView(R.layout.selection);
}
});
Intent iolIntent=new Intent(FullscreenActivity.this,Selection.class);
startActivity(iolIntent);
}
finally{
finish();
}
}
};
iolthread.start();
// Set up an instance of SystemUiHider to control the system UI for
// this activity.
mSystemUiHider = SystemUiHider.getInstance(this, controlsView,
HIDER_FLAGS);
mSystemUiHider.setup();
mSystemUiHider
.setOnVisibilityChangeListener(new SystemUiHider.OnVisibilityChangeListener() {
// Cached values.
int mControlsHeight;
int mShortAnimTime;
#Override
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
public void onVisibilityChange(boolean visible) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
// If the ViewPropertyAnimator API is available
// (Honeycomb MR2 and later), use it to animate the
// in-layout UI controls at the bottom of the
// screen.
if (mControlsHeight == 0) {
mControlsHeight = controlsView.getHeight();
}
if (mShortAnimTime == 0) {
mShortAnimTime = getResources().getInteger(
android.R.integer.config_shortAnimTime);
}
controlsView
.animate()
.translationY(visible ? 0 : mControlsHeight)
.setDuration(mShortAnimTime);
} else {
// If the ViewPropertyAnimator APIs aren't
// available, simply show or hide the in-layout UI
// controls.
controlsView.setVisibility(visible ? View.VISIBLE
: View.GONE);
}
if (visible && AUTO_HIDE) {
// Schedule a hide().
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
}
});
// Set up the user interaction to manually show or hide the system UI.
controlsView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (TOGGLE_ON_CLICK) {
mSystemUiHider.toggle();
} else {
mSystemUiHider.show();
}
}
});
// Upon interacting with UI controls, delay any scheduled hide()
// operations to prevent the jarring behavior of controls going away
// while interacting with the UI.
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Trigger the initial hide() shortly after the activity has been
// created, to briefly hint to the user that UI controls
// are available.
delayedHide(100);
}
/**
* Touch listener to use for in-layout UI controls to delay hiding the
* system UI. This is to prevent the jarring behavior of controls going away
* while interacting with activity UI.
*/
View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (AUTO_HIDE) {
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
return false;
}
};
Handler mHideHandler = new Handler();
Runnable mHideRunnable = new Runnable() {
#Override
public void run() {
mSystemUiHider.hide();
}
};
/**
* Schedules a call to hide() in [delay] milliseconds, canceling any
* previously scheduled calls.
*/
private void delayedHide(int delayMillis) {
mHideHandler.removeCallbacks(mHideRunnable);
mHideHandler.postDelayed(mHideRunnable, delayMillis);
}
}
XML
<FrameLayout 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:background="#color/black"
tools:context=".FullscreenActivity"
android:id="#+id/frame_layout">
<LinearLayout
android:id="#+id/fullscreen_content_controls"
style="?buttonBarStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center_horizontal"
android:background="#color/black_overlay"
android:orientation="horizontal"
tools:ignore="UselessParent" >
</LinearLayout>
<Button
style="#style/ButtonBarButton"
android:layout_width="222dp"
android:layout_height="62dp"
android:layout_marginLeft="45dp"
android:layout_marginTop="75dp"
android:background="#color/black"
android:paddingLeft="20dp"
android:id="#+id/iolCalculation"
android:text="#string/Button"
android:textColor="#color/WhiteSmoke"
android:textStyle="bold" />
<Button
style="#style/ButtonBarButton"
android:layout_width="222dp"
android:layout_height="62dp"
android:layout_marginLeft="45dp"
android:id="#+id/sHelp"
android:layout_marginTop="139dp"
android:background="#color/Black"
android:gravity="center"
android:paddingLeft="10dp"
android:text="#string/Button1"
android:textColor="#color/WhiteSmoke"
android:textStyle="bold" />
<Button
style="#style/ButtonBarButton"
android:layout_width="222dp"
android:layout_height="62dp"
android:id="#+id/sAbout"
android:layout_marginLeft="45dp"
android:layout_marginTop="203dp"
android:background="#color/Black"
android:paddingLeft="10dp"
android:text="#string/Button2"
android:textColor="#color/WhiteSmoke"
android:textStyle="bold" >
</Button>
</FrameLayout>
logcat
12-16 10:48:26.975: E/Trace(767): error opening trace file: No such file or directory (2)
12-16 10:51:38.199: E/AndroidRuntime(767): FATAL EXCEPTION: main
12-16 10:51:38.199: E/AndroidRuntime(767): java.lang.NullPointerException
12-16 10:51:38.199: E/AndroidRuntime(767): at com.android.internal.widget.ActionBarView$3.onClick(ActionBarView.java:168)
12-16 10:51:38.199: E/AndroidRuntime(767): at android.view.View.performClick(View.java:4202)
12-16 10:51:38.199: E/AndroidRuntime(767): at android.view.View$PerformClick.run(View.java:17340)
12-16 10:51:38.199: E/AndroidRuntime(767): at android.os.Handler.handleCallback(Handler.java:725)
12-16 10:51:38.199: E/AndroidRuntime(767): at android.os.Handler.dispatchMessage(Handler.java:92)
12-16 10:51:38.199: E/AndroidRuntime(767): at android.os.Looper.loop(Looper.java:137)
12-16 10:51:38.199: E/AndroidRuntime(767): at android.app.ActivityThread.main(ActivityThread.java:5039)
12-16 10:51:38.199: E/AndroidRuntime(767): at java.lang.reflect.Method.invokeNative(Native Method)
12-16 10:51:38.199: E/AndroidRuntime(767): at java.lang.reflect.Method.invoke(Method.java:511)
12-16 10:51:38.199: E/AndroidRuntime(767): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
12-16 10:51:38.199: E/AndroidRuntime(767): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
12-16 10:51:38.199: E/AndroidRuntime(767): at dalvik.system.NativeStart.main(Native Method)
i have tried every possible solution in stackoverflow but in vain.help me. I think mostly there is a problem in xml to java display content.Also do i need to put in id for every layout in xml and how does the java code detect the layout to be displayed
here goes my selection java code and xml
package com.example.iolcalci;
import android.app.Activity;
import android.os.Bundle;
public class Selection extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.selective);
}
}
<?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:background="#color/black"
android:orientation="vertical" >
<Spinner
android:id="#+id/formulae"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:background="#color/LightSkyBlue"
android:prompt="#string/prompt"
android:entries="#array/formulas" />
<TextView
android:id="#+id/k2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/k1"
android:layout_below="#+id/k1"
android:layout_marginTop="38dp"
android:text="#string/K2"
android:textColor="#color/White"
android:textSize="25sp" />
<TextView
android:id="#+id/al_const"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/al"
android:layout_below="#+id/al"
android:layout_marginTop="44dp"
android:text="#string/Rx"
android:textColor="#color/White"
android:textSize="20sp" />
<TextView
android:id="#+id/al"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/k2"
android:layout_below="#+id/k2"
android:layout_marginTop="38dp"
android:text="#string/AL"
android:textColor="#color/White"
android:textSize="25sp" />
<EditText
android:id="#+id/k2_editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/al"
android:layout_alignRight="#+id/al_editText"
android:layout_alignTop="#+id/k2"
android:layout_marginLeft="120dp"
android:background="#color/black"
android:ems="10"
android:inputType="numberDecimal"
android:textColorLink="#color/white" />
<EditText
android:id="#+id/al_editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/formulae"
android:layout_alignTop="#+id/al"
android:layout_marginLeft="120dp"
android:ems="10"
android:inputType="numberDecimal" />
<EditText
android:id="#+id/al_const_editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/al_const"
android:layout_alignRight="#+id/al_editText"
android:layout_marginLeft="120dp"
android:ems="10"
android:inputType="numberDecimal" />
<Button
android:id="#+id/result"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:background="#color/LightSkyBlue"
android:text="#string/Result" />
<EditText
android:id="#+id/k1_editText"
android:layout_width="wrap_content"
android:layout_height="37dp"
android:layout_alignLeft="#+id/k2_editText"
android:layout_alignRight="#+id/formulae"
android:layout_below="#+id/formulae"
android:layout_marginTop="30dp"
android:background="#color/black"
android:ems="10"
android:inputType="numberDecimal"
android:textColorLink="#color/White" />
<TextView
android:id="#+id/k1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/k1_editText"
android:layout_alignParentLeft="true"
android:layout_marginLeft="27dp"
android:text="#string/K1"
android:textColor="#color/white"
android:textSize="25sp" />
</RelativeLayout>
THE NEW LOGCAT
12-21 10:44:50.419: W/Trace(766): Unexpected value from nativeGetEnabledTags: 0
12-21 10:44:50.573: W/Trace(766): Unexpected value from nativeGetEnabledTags: 0
12-21 10:44:50.573: W/Trace(766): Unexpected value from nativeGetEnabledTags: 0
12-21 10:44:50.923: D/AndroidRuntime(766): Shutting down VM
12-21 10:44:50.923: W/dalvikvm(766): threadid=1: thread exiting with uncaught exception (group=0x40a70930)
12-21 10:44:50.933: E/AndroidRuntime(766): FATAL EXCEPTION: main
12-21 10:44:50.933: E/AndroidRuntime(766): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.iolcalci/com.example.iolcalci.MainActivity}: java.lang.NullPointerException
12-21 10:44:50.933: E/AndroidRuntime(766): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
12-21 10:44:50.933: E/AndroidRuntime(766): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
12-21 10:44:50.933: E/AndroidRuntime(766): at android.app.ActivityThread.access$600(ActivityThread.java:141)
12-21 10:44:50.933: E/AndroidRuntime(766): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
12-21 10:44:50.933: E/AndroidRuntime(766): at android.os.Handler.dispatchMessage(Handler.java:99)
12-21 10:44:50.933: E/AndroidRuntime(766): at android.os.Looper.loop(Looper.java:137)
12-21 10:44:50.933: E/AndroidRuntime(766): at android.app.ActivityThread.main(ActivityThread.java:5039)
12-21 10:44:50.933: E/AndroidRuntime(766): at java.lang.reflect.Method.invokeNative(Native Method)
12-21 10:44:50.933: E/AndroidRuntime(766): at java.lang.reflect.Method.invoke(Method.java:511)
12-21 10:44:50.933: E/AndroidRuntime(766): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
12-21 10:44:50.933: E/AndroidRuntime(766): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
12-21 10:44:50.933: E/AndroidRuntime(766): at dalvik.system.NativeStart.main(Native Method)
12-21 10:44:50.933: E/AndroidRuntime(766): Caused by: java.lang.NullPointerException
12-21 10:44:50.933: E/AndroidRuntime(766): at com.example.iolcalci.MainActivity.onCreate(MainActivity.java:23)
12-21 10:44:50.933: E/AndroidRuntime(766): at android.app.Activity.performCreate(Activity.java:5104)
12-21 10:44:50.933: E/AndroidRuntime(766): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
12-21 10:44:50.933: E/AndroidRuntime(766): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
12-21 10:44:50.933: E/AndroidRuntime(766): ... 11 more
Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.iolcalci"
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.iolcalci.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="Selection"
android:exported="false"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="#string/app_name">
<intent-filter>
<action android:name="com.example.iolcalci.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
Judging from your code I'm going to go with the conjecture that this line is causing the error:
setContentView(R.id.selection);
There's no need to change the contentView of the activity from which you're calling the "selection" activity. You should read up on intents. I'm assuming that when the button is clicked, you want the new activity and it's content to pop up. For that, do this :
try{
iol.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent iolIntent=new Intent(FullscreenActivity.this,Selection.class);
startActivity(iolIntent);
}
});
}
Also set your button's layout width and layout height to "wrap_content". Definite measurements won't work well because there are many resolutions possible.
android:layout_height="wrap_content"
android:layout_width="wrap_content"
In case of more errors, post the new logcat, please.
I found this in your selection.java:
setContentView(R.layout.selective);
This means you should have a selective.xml file in your res/layout/ folder.
This selective.xml file should contain a definition of EditText.
Example,
<EditText
android:id="#+id/k1_editText"
android:layout_width="wrap_content"
android:layout_height="37dp"
android:layout_alignLeft="#+id/k2_editText"
android:layout_alignRight="#+id/formulae"
android:layout_below="#+id/formulae"
android:layout_marginTop="30dp"
android:background="#color/black"
android:ems="10"
android:inputType="numberDecimal"
android:textColorLink="#color/White" />
You need to reference this in the activity file with this piece of code:
EditText ed=new EditText findViewById(R.id.k2_editText);
Now the EditText field will be displayed.
If you want to make your EditText object global, declare it in the class and then initialize it after setting content view. Like this,
public class Selection extends Activity {
EditText ed;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.selective);
EditText ed=new EditText findViewById(R.id.k2_editText);
}
Make sure you always initialize a widget object AFTER the creation of the activity and setting content view, because otherwise the compiler is going to have to initialize something which hasn't been referenced yet. The layout file is referenced only after setting content view. Only after setting the layout file can you initialize objects to whatever is present inside the layout file.
If you like the answer, do vote it up.

Categories