I'm new to android. I just tried creating a simple app that performs basic mathematical operations (addition,subtraction,multiplication and division). When i try to run the code i get FATAL EXCEPTION: mainerror. I've gone through the other threads that had the same problem. I still couldn't figure out why i'm having this error.
The mainactivity.java file is
package com.example.mathematicalopr;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
Button add,sub,mul,div;
TextView display2;
EditText display,display1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//int c=0;
add = (Button) findViewById(R.id.bAdd);
sub = (Button) findViewById(R.id.bSub);
mul = (Button) findViewById(R.id.times);
div = (Button) findViewById(R.id.divide);
display = (EditText) findViewById(R.id.tvDisplay);
String myFirstNum = display.getText().toString();
final int a = Integer.parseInt(myFirstNum);
display1 = (EditText) findViewById(R.id.tvDisplay1);
String mySecondNum = display1.getText().toString();
final int b = Integer.parseInt(mySecondNum);
display2 = (TextView) findViewById(R.id.tvDisplay2);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int c = a+b;
display2.setText("Answer is"+c);
}
});
sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int c = a-b;
display2.setText("Answer is"+c);
}
});
mul.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int c = a*b;
display2.setText("Answer is"+c);
}
});
div.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int c = a/b;
display2.setText("Answer is"+c);
}
});
}
#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;
}
}
My activity_main.xml file is
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<EditText
android:id="#+id/tvDisplay"
android:layout_width="342dp"
android:layout_height="wrap_content"
android:inputType="number"
android:text="#string/ref" />
<EditText
android:id="#+id/tvDisplay1"
android:layout_width="342dp"
android:layout_height="wrap_content"
android:inputType="number"
android:text="#string/ref1" />
<Button
android:id="#+id/bAdd"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="#string/add" />
<Button
android:id="#+id/bSub"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="#string/sub" />
<Button
android:id="#+id/times"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="#string/times" />
<Button
android:id="#+id/divide"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="#string/divide" />
<TextView
android:id="#+id/tvDisplay2"
android:layout_width="342dp"
android:layout_height="wrap_content"
android:text="#string/ref2" />
</LinearLayout>
My strings.xml file
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Mathematicalopr</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="ref">Enter first number</string>
<string name="add">Add</string>
<string name="sub">Subtract </string>
<string name="times">Multiply</string>
<string name="divide">divide</string>
<string name="ref1">Enter second number</string>
<string name="ref2">Answer is</string>
</resources>
Logcat:
02-08 10:50:43.962: W/Trace(2302): Unexpected value from nativeGetEnabledTags: 0
02-08 10:50:43.972: W/Trace(2302): Unexpected value from nativeGetEnabledTags: 0
02-08 10:50:43.972: W/Trace(2302): Unexpected value from nativeGetEnabledTags: 0
02-08 10:50:44.022: W/Trace(2302): Unexpected value from nativeGetEnabledTags: 0
02-08 10:50:44.022: W/Trace(2302): Unexpected value from nativeGetEnabledTags: 0
02-08 10:50:44.422: D/AndroidRuntime(2302): Shutting down VM
02-08 10:50:44.432: W/dalvikvm(2302): threadid=1: thread exiting with uncaught exception (group=0xb2ca6908)
02-08 10:50:44.462: E/AndroidRuntime(2302): FATAL EXCEPTION: main
02-08 10:50:44.462: E/AndroidRuntime(2302): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mathematicalopr/com.example.mathematicalopr.MainActivity}: java.lang.NumberFormatException: Invalid int: "Enter first number"
02-08 10:50:44.462: E/AndroidRuntime(2302): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
02-08 10:50:44.462: E/AndroidRuntime(2302): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
02-08 10:50:44.462: E/AndroidRuntime(2302): at android.app.ActivityThread.access$600(ActivityThread.java:141)
02-08 10:50:44.462: E/AndroidRuntime(2302): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
02-08 10:50:44.462: E/AndroidRuntime(2302): at android.os.Handler.dispatchMessage(Handler.java:99)
02-08 10:50:44.462: E/AndroidRuntime(2302): at android.os.Looper.loop(Looper.java:137)
02-08 10:50:44.462: E/AndroidRuntime(2302): at android.app.ActivityThread.main(ActivityThread.java:5039)
02-08 10:50:44.462: E/AndroidRuntime(2302): at java.lang.reflect.Method.invokeNative(Native Method)
02-08 10:50:44.462: E/AndroidRuntime(2302): at java.lang.reflect.Method.invoke(Method.java:511)
02-08 10:50:44.462: E/AndroidRuntime(2302): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
02-08 10:50:44.462: E/AndroidRuntime(2302): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
02-08 10:50:44.462: E/AndroidRuntime(2302): at dalvik.system.NativeStart.main(Native Method)
02-08 10:50:44.462: E/AndroidRuntime(2302): Caused by: java.lang.NumberFormatException: Invalid int: "Enter first number"
02-08 10:50:44.462: E/AndroidRuntime(2302): at java.lang.Integer.invalidInt(Integer.java:138)
02-08 10:50:44.462: E/AndroidRuntime(2302): at java.lang.Integer.parse(Integer.java:375)
02-08 10:50:44.462: E/AndroidRuntime(2302): at java.lang.Integer.parseInt(Integer.java:366)
02-08 10:50:44.462: E/AndroidRuntime(2302): at java.lang.Integer.parseInt(Integer.java:332)
02-08 10:50:44.462: E/AndroidRuntime(2302): at com.example.mathematicalopr.MainActivity.onCreate(MainActivity.java:30)
02-08 10:50:44.462: E/AndroidRuntime(2302): at android.app.Activity.performCreate(Activity.java:5104)
02-08 10:50:44.462: E/AndroidRuntime(2302): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
02-08 10:50:44.462: E/AndroidRuntime(2302): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
02-08 10:50:44.462: E/AndroidRuntime(2302): ... 11 more
Can i know why am i getting such an error? When i try to run this code on a virtual device the application closes unexpectedly. Thank you :)
Thank you everyone. Sorry apparently i don't have enough reputation to thank each one of you personally.
String myFirstNum = display.getText().toString();
final int a = Integer.parseInt(myFirstNum);
String mySecondNum = display1.getText().toString();
final int b = Integer.parseInt(mySecondNum);
insert this code in your add button click event listener then you will get correct data
Your Logcat say it all,
Read this
Invalid int: "Enter first number"
Your are casting a string value to int, which results java.lang.NumberFormatException.
you must change
<EditText
android:id="#+id/tvDisplay"
android:layout_width="342dp"
android:layout_height="wrap_content"
android:inputType="number"
android:hint="#string/ref" />
<EditText
android:id="#+id/tvDisplay1"
android:layout_width="342dp"
android:layout_height="wrap_content"
android:inputType="number"
android:hint="#string/ref1" />
you must change from
android:text="#string/ref1"
to
android:hint="#string/ref1"
because on oncreate() method you are retrieving value of EditText. And in xml you have set string for it and after that you have parsed it in Integer. So you have got invalid int error. So just change it for every EditText.
Your are casting a string value to int, which results java.lang.NumberFormatException.
Modified your code:
package com.example.sampleactivity;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
Button add,sub,mul,div;
TextView display2;
EditText display,display1;
int a,b,c;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//int c=0;
add = (Button) findViewById(R.id.bAdd);
sub = (Button) findViewById(R.id.bSub);
mul = (Button) findViewById(R.id.times);
div = (Button) findViewById(R.id.divide);
display = (EditText) findViewById(R.id.tvDisplay);
display1 = (EditText) findViewById(R.id.tvDisplay1);
display2 = (TextView) findViewById(R.id.tvDisplay2);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
getValues();
c = a+b;
display2.setText("Answer is"+c);
}
});
sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
getValues();
c = a-b;
display2.setText("Answer is"+c);
}
});
mul.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
getValues();
c = a*b;
display2.setText("Answer is"+c);
}
});
div.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
getValues();
c = a/b;
display2.setText("Answer is"+c);
}
});
}
protected void getValues() {
String myFirstNum = display.getText().toString();
a= Integer.parseInt(myFirstNum);
String mySecondNum = display1.getText().toString();
b = Integer.parseInt(mySecondNum);
}
#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;
}
}
xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<EditText
android:id="#+id/tvDisplay"
android:layout_width="342dp"
android:layout_height="wrap_content"
android:hint="#string/ref"
android:inputType="number" />
<EditText
android:id="#+id/tvDisplay1"
android:layout_width="342dp"
android:layout_height="wrap_content"
android:hint="#string/ref1"
android:inputType="number" />
<Button
android:id="#+id/bAdd"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="#string/add" />
<Button
android:id="#+id/bSub"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="#string/sub" />
<Button
android:id="#+id/times"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="#string/times" />
<Button
android:id="#+id/divide"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="#string/divide" />
<TextView
android:id="#+id/tvDisplay2"
android:layout_width="342dp"
android:layout_height="wrap_content"
android:text="#string/ref2" />
</LinearLayout>
Related
I'm trying to get the input value from EditText in SearchUser to query in SearchResult
Here is my Code for SearchUser :
package com.example.yearbookmuict9sec2;
import android.app.Activity;
import android.content.Intent;
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.EditText;
public class SearchUser extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_user);
addButtonListenerHomeButton();
addButtonListenerViewAll();
addButtonListenerSearchButton();
}
private void addButtonListenerSearchButton() {
// TODO Auto-generated method stub
Button button = (Button) findViewById(R.id.SearchButton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText edtSearch;
String Answer;
edtSearch = (EditText)findViewById(R.id.answer);
Answer = edtSearch.getText().toString();
Intent goAnswer = new Intent(getApplicationContext(),SearchResult.class);
goAnswer.putExtra("Answer", Answer);
startActivity(goAnswer);
}
});
}
private void addButtonListenerViewAll() {
// TODO Auto-generated method stub
Button button = (Button) findViewById(R.id.viewALLBUTTON);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(SearchUser.this,ViewAll.class);
startActivity(i);
}
});
}
private void addButtonListenerHomeButton() {
// TODO Auto-generated method stub
ImageButton button = (ImageButton) findViewById(R.id.HomeButton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(SearchUser.this,Home.class);
startActivity(i);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.search_user, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Here is my activity_search_user :
<ScrollView
android:id="#+id/scrollView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageButton
android:id="#+id/HomeButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/home1"
android:layout_alignTop="#+id/scrollView4"
android:background="#fffbf8f0"
android:src="#drawable/ic_home_black_24dp" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/home1"
android:layout_below="#+id/HomeButton"
android:text="Back Home" />
<Button
android:id="#+id/viewALLBUTTON"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/SearchButton"
android:layout_alignBottom="#+id/SearchButton"
android:layout_marginRight="20dp"
android:layout_toLeftOf="#+id/HomeButton"
android:background="#ffff6c41"
android:text="View All"
android:textColor="#ffffffff" />
<ImageView
android:id="#+id/home1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="27dp"
android:src="#drawable/logo_180" />
<Button
android:id="#+id/SearchButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/home1"
android:layout_below="#+id/home1"
android:layout_marginLeft="56dp"
android:layout_marginTop="47dp"
android:background="#ff606efd"
android:nestedScrollingEnabled="false"
android:text="Search"
android:textColor="#ffffffff" />
<EditText
android:id="#+id/answer"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/viewALLBUTTON"
android:layout_alignParentRight="true"
android:ems="10"
android:inputType="text" >
<requestFocus />
</EditText>
Here is my code for SearchResult :
package com.example.yearbookmuict9sec2;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class SearchResult extends Activity {
SQLiteDatabase mDb;
Database mHelper;
Cursor mCursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_result);
EditText txtAnswer;
Button btnBack;
String showAnswer;
txtAnswer = (EditText)findViewById(R.id.answer);
btnBack = (Button)findViewById(R.id.SearchButton);
showAnswer = getIntent().getStringExtra("Answer");
txtAnswer.setText(showAnswer);
ListView listView1 = (ListView)findViewById(R.id.listView1);
mHelper = new Database(this);
mDb = mHelper.getWritableDatabase();
mHelper.onUpgrade(mDb, 1, 1);
mCursor = mDb.rawQuery("SELECT " + Database.COL_StudentID + ", "
+ Database.COL_FNAME + ", " + Database.COL_LNAME+ ", "
+ Database.COL_NNAME + " FROM " + Database.TABLE_NAME +" WHERE "
+ Database.COL_StudentID + " = ?", new String[] {showAnswer});
ArrayList<String> dirArray = new ArrayList<String>();
mCursor.moveToFirst();
while ( !mCursor.isAfterLast() ){
dirArray.add("ID : " + mCursor.getString(mCursor.getColumnIndex(Database.COL_StudentID)) + "\n"
+ "Firstname : " + mCursor.getString(mCursor.getColumnIndex(Database.COL_FNAME)) + "\n"
+ "Lastname : " + mCursor.getString(mCursor.getColumnIndex(Database.COL_LNAME)) + "\n"
+ "Nickname : " + mCursor.getString(mCursor.getColumnIndex(Database.COL_NNAME)));
mCursor.moveToNext();
}
ArrayAdapter<String> adapterDir = new ArrayAdapter<String>(getApplicationContext()
, android.R.layout.simple_list_item_1, dirArray);
listView1.setAdapter(adapterDir);
List<Map<String, String>> data = new ArrayList<Map<String, String>>();
Map<String, String> datum = new HashMap<String, String>(2);
datum.put("First Line", "First line of text");
datum.put("Second Line","Second line of text");
data.add(datum);
SimpleAdapter adapter = new SimpleAdapter(this, data,
android.R.layout.simple_list_item_2,
new String[] {"First Line", "Second Line" },
new int[] {android.R.id.text1, android.R.id.text2 });
}
public void onPause() {
super.onPause();
mHelper.close();
mDb.close();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.search_result, 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);
}
}
Here is my activity_search_result :
<Button
android:id="#+id/backToHome"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignRight="#+id/listView1"
android:layout_toEndOf="#+id/imageView"
android:background="#ffafff9b"
android:text="Back to Home" />
<TextView
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:gravity="center"
android:text="Student"
android:textColor="#FFFFFF"
android:textSize="40dp" />
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true"
android:layout_margin="30dp"
android:cacheColorHint="#00000000" >
</ListView>
</RelativeLayout>
Here is my LogCat :
12-09 03:57:09.421: E/AndroidRuntime(4961): FATAL EXCEPTION: main
12-09 03:57:09.421: E/AndroidRuntime(4961): Process: com.example.yearbookmuict9sec2, PID: 4961
12-09 03:57:09.421: E/AndroidRuntime(4961): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.yearbookmuict9sec2/com.example.yearbookmuict9sec2.SearchResult}: java.lang.NullPointerException
12-09 03:57:09.421: E/AndroidRuntime(4961): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
12-09 03:57:09.421: E/AndroidRuntime(4961): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
12-09 03:57:09.421: E/AndroidRuntime(4961): at android.app.ActivityThread.access$800(ActivityThread.java:135)
12-09 03:57:09.421: E/AndroidRuntime(4961): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
12-09 03:57:09.421: E/AndroidRuntime(4961): at android.os.Handler.dispatchMessage(Handler.java:102)
12-09 03:57:09.421: E/AndroidRuntime(4961): at android.os.Looper.loop(Looper.java:136)
12-09 03:57:09.421: E/AndroidRuntime(4961): at android.app.ActivityThread.main(ActivityThread.java:5001)
12-09 03:57:09.421: E/AndroidRuntime(4961): at java.lang.reflect.Method.invokeNative(Native Method)
12-09 03:57:09.421: E/AndroidRuntime(4961): at java.lang.reflect.Method.invoke(Method.java:515)
12-09 03:57:09.421: E/AndroidRuntime(4961): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
12-09 03:57:09.421: E/AndroidRuntime(4961): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
12-09 03:57:09.421: E/AndroidRuntime(4961): at dalvik.system.NativeStart.main(Native Method)
12-09 03:57:09.421: E/AndroidRuntime(4961): Caused by: java.lang.NullPointerException
12-09 03:57:09.421: E/AndroidRuntime(4961): at com.example.yearbookmuict9sec2.SearchResult.onCreate(SearchResult.java:39)
12-09 03:57:09.421: E/AndroidRuntime(4961): at android.app.Activity.performCreate(Activity.java:5231)
12-09 03:57:09.421: E/AndroidRuntime(4961): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
12-09 03:57:09.421: E/AndroidRuntime(4961): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
12-09 03:57:09.421: E/AndroidRuntime(4961): ... 11 more
Help me please.
What i have to do to fix this problem? I'm new here.
The problem is sourced on line 39 in SearchResult.java. You can see this in the LogCat on the line after the one that starts with Caused by: java.lang.NullPointerException.
txtAnswer is not a valid id for an EditText object in your activity_search_result.xml, so it returned null on line 35 when you searched for it. You cannot call .setText() on a null object.
txtAnswer is null. This is because it is not in the activity's view. Your activity loads its view as follows:
setContentView(R.layout.activity_search_result);
Yet the element with ID answer id not defined in activity_search_result.xml. It is defined in activity_search_user.xml.
So your problem is either:
a) You are loading the wrong view for your activity OR
b) You forgot to add the EditText with ID answer to your view (activity_search_result.xml)
Edit - looking at your code, I think it is likely that option is is the problem. So to fix this, change
setContentView(R.layout.activity_search_result);
to
setContentView(R.layout.activity_search_user);
You activity_search_result.xml does not contain any view that you have specified in your activity. You may have to pass right layout xml file in setContentView or change id of EditText and Button.
I am new on android and trying to develop simple calculator but this Fatal exception : main occurs please help.
I did comment my onClickListner to check but it did'nt helped at all.
package com.example.calculatorsinglescreen;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
EditText value1,value2,myoperator,result;
Button ok;
String strvalue1,strvalue2,stroperator,strresult;
int ivalue1,ivalue2,ioperator,iresult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
value1 = (EditText) findViewById(R.id.txtvalue1);
value2 = (EditText) findViewById(R.id.txtvalue2);
myoperator = (EditText) findViewById(R.id.txtoperator);
result = (EditText) findViewById(R.id.txtresult);
ok = (Button) findViewById(R.id.btnok);
strvalue1 = value1.getText().toString();
strvalue2 = value2.getText().toString();
stroperator = myoperator.getText().toString();
ivalue1 = Integer.parseInt(strvalue1);
ivalue2 = Integer.parseInt(strvalue2);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (stroperator.equals("+")) {
Toast msg = Toast.makeText(MainActivity.this, "If is running", Toast.LENGTH_LONG);
msg.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;
}
#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);
}
}
This is my 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: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.calculatorsinglescreen.MainActivity" >
<TextView
android:id="#+id/value1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_margin="20dp"
android:text="Value 1" />
<TextView
android:id="#+id/value2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/value1"
android:layout_margin="20dp"
android:text="Value 2" />
<TextView
android:id="#+id/operator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/value2"
android:layout_margin="20dp"
android:text="Operator" />
<EditText
android:id="#+id/txtvalue1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/value1"
android:layout_alignBaseline="#+id/value1"
android:layout_alignParentRight="true"
android:ems="10" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/txtoperator"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/operator"
android:layout_below="#+id/txtvalue2"
android:layout_toRightOf="#+id/operator"
android:layout_alignParentRight="true"
android:ems="10" />
<EditText
android:id="#+id/txtvalue2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/value2"
android:layout_toRightOf="#+id/value2"
android:layout_below="#+id/txtvalue1"
android:layout_alignParentRight="true"
android:ems="10" />
<Button
android:id="#+id/btnok"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Ok" />
<TextView
android:id="#+id/result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/btnok"
android:layout_margin="40dp"
android:text="Result" />
<EditText
android:id="#+id/txtresult"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/result"
android:layout_toRightOf="#+id/result"
android:ems="10" />
Here is my LogCat to get a clearer view :
10-18 17:51:25.468: D/AndroidRuntime(742): Shutting down VM
10-18 17:51:25.468: W/dalvikvm(742): threadid=1: thread exiting with uncaught exception (group=0x40015560)
10-18 17:51:25.488: E/AndroidRuntime(742): FATAL EXCEPTION: main
10-18 17:51:25.488: E/AndroidRuntime(742): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.calculatorsinglescreen/com.example.calculatorsinglescreen.MainActivity}: java.lang.NumberFormatException: unable to parse '' as integer
10-18 17:51:25.488: E/AndroidRuntime(742): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
10-18 17:51:25.488: E/AndroidRuntime(742): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
10-18 17:51:25.488: E/AndroidRuntime(742): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
10-18 17:51:25.488: E/AndroidRuntime(742): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
10-18 17:51:25.488: E/AndroidRuntime(742): at android.os.Handler.dispatchMessage(Handler.java:99)
10-18 17:51:25.488: E/AndroidRuntime(742): at android.os.Looper.loop(Looper.java:123)
10-18 17:51:25.488: E/AndroidRuntime(742): at android.app.ActivityThread.main(ActivityThread.java:3683)
10-18 17:51:25.488: E/AndroidRuntime(742): at java.lang.reflect.Method.invokeNative(Native Method)
10-18 17:51:25.488: E/AndroidRuntime(742): at java.lang.reflect.Method.invoke(Method.java:507)
10-18 17:51:25.488: E/AndroidRuntime(742): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
10-18 17:51:25.488: E/AndroidRuntime(742): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
10-18 17:51:25.488: E/AndroidRuntime(742): at dalvik.system.NativeStart.main(Native Method)
10-18 17:51:25.488: E/AndroidRuntime(742): Caused by: java.lang.NumberFormatException: unable to parse '' as integer
10-18 17:51:25.488: E/AndroidRuntime(742): at java.lang.Integer.parseInt(Integer.java:362)
10-18 17:51:25.488: E/AndroidRuntime(742): at java.lang.Integer.parseInt(Integer.java:332)
10-18 17:51:25.488: E/AndroidRuntime(742): at com.example.calculatorsinglescreen.MainActivity.onCreate(MainActivity.java:34)
10-18 17:51:25.488: E/AndroidRuntime(742): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
10-18 17:51:25.488: E/AndroidRuntime(742): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
10-18 17:51:25.488: E/AndroidRuntime(742): ... 11 more
this is the error
java.lang.ClassCastException: android.widget.TextView
check your line 24 and see if you cast the right widget in java -(xml), this error means incompatible cast widget lol...
if everything seems correct-(mean widgets are cast in java to with their respective class) then clean rebuild and restart..
EDIT: It worked.. you've solved it but there is a new error which is
java.lang.NumberFormatException:
its because of this on these lines
ivalue1 = Integer.parseInt(strvalue1);
ivalue2 = Integer.parseInt(strvalue2);
ioperator = Integer.parseInt(stroperator);
so change these to this
Integer.valueOf(strvalue1); do that as follows
and also looking at your codes.. your string values are pullled from the edittext during oncreate which means when the app starts in oncreate before the Onresume(which is called when the app shows on the), and during oncreate the user cant flirt with your app, and going further to input values, so at the end your strings are empty when you pull from the edittext, so basically what im saying is remove these lines
strvalue1 = value1.getText().toString();
and put them in the click events ... i am lucid enough to you??..
EDIT2: OVERALL CODE
for button click
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
strvalue1 = value1.getText().toString();
strvalue2 = value2.getText().toString();
stroperator = myoperator.getText().toString();
ivalue1 = Integer.valueOf(strvalue1);
ivalue2 = Integer.valueOf(strvalue2);
if (stroperator.equals("+")) {
Toast.makeText(MainActivity.this, "If is running", Toast.LENGTH_LONG).show();
}
}
});
remove ioperator = Integer.parseInt(stroperator); from the code.I think Your trying to convert the operator to Integer.
ioperator = Integer.parseInt(stroperator);
if you mean operator like this +,-,/,* , you only can convert to thr char or stay in string and do something like this:
private int plus(int ivalue1 , int ivalue2 , String operator ){
if(operator.equal("+")){
return ivalue1 + ivalue2;
}
return 0;
}
I'm a total newbie with Android, and I'm trying to switch between two activities ("MainActivity" and "LoginDisplayActivity") and adding the "OnClickListener" seem to make my app crash on startup.
Here is my code :
package info.dremor.kronos;
import android.app.Activity;
import android.app.ActionBar;
import android.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.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.os.Build;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState == null) {
getFragmentManager().beginTransaction().add(R.id.container, new MainFragment()).commit();
}
final Button loginButton = (Button) findViewById(R.id.connect);
loginButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, LoginDisplayActivity.class);
startActivity(intent);
}
});
}
#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 MainFragment extends Fragment {
public MainFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
trace :
05-26 15:48:11.286: D/AndroidRuntime(947): Shutting down VM
05-26 15:48:11.286: W/dalvikvm(947): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
05-26 15:48:11.296: E/AndroidRuntime(947): FATAL EXCEPTION: main
05-26 15:48:11.296: E/AndroidRuntime(947): java.lang.RuntimeException: Unable to start activity ComponentInfo{info.dremor.kronos/info.dremor.kronos.MainActivity}: java.lang.NullPointerException
05-26 15:48:11.296: E/AndroidRuntime(947): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
05-26 15:48:11.296: E/AndroidRuntime(947): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
05-26 15:48:11.296: E/AndroidRuntime(947): at android.app.ActivityThread.access$600(ActivityThread.java:130)
05-26 15:48:11.296: E/AndroidRuntime(947): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
05-26 15:48:11.296: E/AndroidRuntime(947): at android.os.Handler.dispatchMessage(Handler.java:99)
05-26 15:48:11.296: E/AndroidRuntime(947): at android.os.Looper.loop(Looper.java:137)
05-26 15:48:11.296: E/AndroidRuntime(947): at android.app.ActivityThread.main(ActivityThread.java:4745)
05-26 15:48:11.296: E/AndroidRuntime(947): at java.lang.reflect.Method.invokeNative(Native Method)
05-26 15:48:11.296: E/AndroidRuntime(947): at java.lang.reflect.Method.invoke(Method.java:511)
05-26 15:48:11.296: E/AndroidRuntime(947): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
05-26 15:48:11.296: E/AndroidRuntime(947): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
05-26 15:48:11.296: E/AndroidRuntime(947): at dalvik.system.NativeStart.main(Native Method)
05-26 15:48:11.296: E/AndroidRuntime(947): Caused by: java.lang.NullPointerException
05-26 15:48:11.296: E/AndroidRuntime(947): at info.dremor.kronos.MainActivity.onCreate(MainActivity.java:31)
05-26 15:48:11.296: E/AndroidRuntime(947): at android.app.Activity.performCreate(Activity.java:5008)
05-26 15:48:11.296: E/AndroidRuntime(947): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
05-26 15:48:11.296: E/AndroidRuntime(947): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
05-26 15:48:11.296: E/AndroidRuntime(947): ... 11 more
activity_main.xml :
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="info.dremor.kronos.MainActivity"
tools:ignore="MergeRootFrame" />
fragment_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="info.dremor.kronos.MainActivity$PlaceholderFragment" >
<Button
android:id="#+id/connect"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="35dp"
android:text="#string/connect" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="35dp"
android:text="#string/login_greeting" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="35dp"
android:text="#string/login" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView3"
android:layout_centerHorizontal="true"
android:layout_marginTop="35dp"
android:ems="10" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText1"
android:layout_centerHorizontal="true"
android:layout_marginTop="35dp"
android:text="#string/password" />
<EditText
android:id="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editText1"
android:layout_below="#+id/textView2"
android:layout_marginTop="35dp"
android:ems="10"
android:inputType="textPassword" />
</RelativeLayout>
Can someone help me?
In your activity, you set the layout file like this:
setContentView(R.layout.activity_main);
This means, when you write findViewById, it will look within the activity_main.xml file.
Your button on the other hand is within another layout file.
Just move the click event into your fragment, and access the context using getActivity like so:
final Button loginButton = (Button) rootView.findViewById(R.id.connect);
loginButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), LoginDisplayActivity.class);
startActivity(intent);
}
});
your button is in the fragment layout, you're "finding" it from the activity layout. Setup button onclick in the fragment onCreateView
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
final Button loginButton = (Button) rootView.findViewById(R.id.connect);
loginButton.setOnClickListener(new OnClickListener(){...})
return rootView;
}
Remove the button and code from onCreate and shift the button and clicklistener code to onCreateView like this:
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
final Button loginButton = (Button) rootView.findViewById(R.id.connect);
loginButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, LoginDisplayActivity.class);
startActivity(intent);
}
});
return rootView;
As your button is in fragment_main, not activity_main. The button is not found.
I'm new to Android development and trying to build my first application. I'm currently trying to build a simple counter that allows the user to increment the total by +1, -1, +5, -5 with the starting value being 20. When I try to run my app it always crashes immediately and I'm completely stuck on how to fix it.
Here is my code:
package com.example.mtglifecounter;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
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.widget.EditText;
import android.widget.TextView;
import android.os.Build;
public class MainActivity extends ActionBarActivity {
int Total=20;
Button Plus1, Min1, Plus5, Min5;
EditText Display;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Total = 20;
Plus1 = (Button) findViewById(R.id.btnPlus1);
Min1 = (Button) findViewById(R.id.btnMin1);
Plus5 = (Button) findViewById(R.id.btnPlus5);
Min5 = (Button) findViewById(R.id.btnmin5);
Display = (EditText) findViewById(R.id.tvTotal);
Display.setText(Total);
Plus1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Adds 1 to the counter
Total = Total + 1;
Display.setText(Total);
}
});
Min1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Subtract 1 from counter
Total = Total - 1;
Display.setText(Total);
}
});
Plus5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Adds 1 to the counter
Total = Total + 5;
Display.setText(Total);
}
});
Min5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Subtract 1 from counter
Total = Total - 5;
Display.setText(Total);
}
});
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
#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;
}
}
}
I also have a logcat that I saved:
04-11 11:56:27.433: D/AndroidRuntime(1459): Shutting down VM
04-11 11:56:27.433: W/dalvikvm(1459): threadid=1: thread exiting with uncaught exception (group=0xb1aabba8)
04-11 11:56:27.453: E/AndroidRuntime(1459): FATAL EXCEPTION: main
04-11 11:56:27.453: E/AndroidRuntime(1459): Process: com.example.mtglifecounter, PID: 1459
04-11 11:56:27.453: E/AndroidRuntime(1459): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mtglifecounter/com.example.mtglifecounter.MainActivity}: java.lang.NullPointerException
04-11 11:56:27.453: E/AndroidRuntime(1459): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
04-11 11:56:27.453: E/AndroidRuntime(1459): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
04-11 11:56:27.453: E/AndroidRuntime(1459): at android.app.ActivityThread.access$800(ActivityThread.java:135)
04-11 11:56:27.453: E/AndroidRuntime(1459): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
04-11 11:56:27.453: E/AndroidRuntime(1459): at android.os.Handler.dispatchMessage(Handler.java:102)
04-11 11:56:27.453: E/AndroidRuntime(1459): at android.os.Looper.loop(Looper.java:136)
04-11 11:56:27.453: E/AndroidRuntime(1459): at android.app.ActivityThread.main(ActivityThread.java:5017)
04-11 11:56:27.453: E/AndroidRuntime(1459): at java.lang.reflect.Method.invokeNative(Native Method)
04-11 11:56:27.453: E/AndroidRuntime(1459): at java.lang.reflect.Method.invoke(Method.java:515)
04-11 11:56:27.453: E/AndroidRuntime(1459): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-11 11:56:27.453: E/AndroidRuntime(1459): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-11 11:56:27.453: E/AndroidRuntime(1459): at dalvik.system.NativeStart.main(Native Method)
04-11 11:56:27.453: E/AndroidRuntime(1459): Caused by: java.lang.NullPointerException
04-11 11:56:27.453: E/AndroidRuntime(1459): at com.example.mtglifecounter.MainActivity.onCreate(MainActivity.java:34)
04-11 11:56:27.453: E/AndroidRuntime(1459): at android.app.Activity.performCreate(Activity.java:5231)
04-11 11:56:27.453: E/AndroidRuntime(1459): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-11 11:56:27.453: E/AndroidRuntime(1459): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
04-11 11:56:27.453: E/AndroidRuntime(1459): ... 11 more
04-11 11:56:33.373: I/Process(1459): Sending signal. PID: 1459 SIG: 9
I would really appreciate any help you can give me since this is my first try at Android.
Thanks
Here is the activity_Main.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.mtglifecounter.MainActivity"
tools:ignore="MergeRootFrame" >
<RelativeLayout
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.mtglifecounter.MainActivity$PlaceholderFragment" >
<EditText
android:id="#+id/etTotal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/LifeTotal"
android:ems="10"
android:inputType="number"
android:text="20" />
<Button
android:id="#+id/btnmin5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/btnPlus5"
android:layout_alignBottom="#+id/btnPlus5"
android:layout_alignLeft="#+id/btnMin1"
android:onClick="On_Clicked"
android:text="-5" />
<Button
android:id="#+id/btnMin1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/btnPlus1"
android:layout_alignBottom="#+id/btnPlus1"
android:layout_alignLeft="#+id/LifeTotal"
android:layout_marginLeft="37dp"
android:onClick="On_Clicked"
android:text="-1" />
<Button
android:id="#+id/btnPlus5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/tvTotal"
android:layout_below="#+id/btnPlus1"
android:layout_marginRight="60dp"
android:layout_marginTop="25dp"
android:onClick="On_Clicked"
android:text="+5" />
<Button
android:id="#+id/btnPlus1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/btnPlus5"
android:layout_below="#+id/LifeTotal"
android:layout_marginTop="44dp"
android:onClick="On_Clicked"
android:text="+1" />
<TextView
android:id="#+id/LifeTotal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/tvTotal"
android:layout_alignParentLeft="true"
android:layout_marginLeft="21dp"
android:text="Life Total:"
android:textSize="#dimen/abc_action_bar_title_text_size" />
As per your code and layout , issue is with the EditText Id.
You are trying to find the EditText view using the Button Id
As per your layout change this line
Display = (EditText) findViewById(R.id.tvTotal);
to
Display = (EditText) findViewById(R.id.etTotal);
Also , the other issue is in setText to EditText
Display.setText(Total);
Total is an int. It should be a String or should be a valid String Resource ID
If you are setting an integer , it will be considered as Resource Id
This what the setText method does...
public final void setText(int resid) {
setText(getContext().getResources().getText(resid));
}
Either, change the int to pass the correct string Resource Id or convert the int to string like this
Display.setText(Integer.toString(Total));
You should use a debugger. Step each line in your onCreate method until you see a value that is wrong - probably a null pointer. You don't say how you built your application but using both Eclipse or Android Studio allow line by line debug stepping. Use this feature and it will allow you to find your bugs quickly and easily.
https://developer.android.com/tools/debugging/debugging-projects.html
make sure all of these exists in your layout activity_mail.xml
Plus1 = (Button) findViewById(R.id.btnPlus1);
Min1 = (Button) findViewById(R.id.btnMin1);
Plus5 = (Button) findViewById(R.id.btnPlus5);
Min5 = (Button) findViewById(R.id.btnmin5);
Display = (EditText) findViewById(R.id.tvTotal);
And by that I mean, check if there is a Button with ID btnPlus1 , then check if there is a Button with ID btnMin1, and so on.
Since the exception is a NullPointerException the problem is probably that you mistyped an ID and one (or more) of them is returning null.
When I start the activity on my phone, it says that the app is not responding. The problem is the back button which I can't seem to program to make it gather the previous text from the textView.
Xml code for activity
<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:background="#drawable/background"
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=".Author" >
<TextView
android:id="#+id/textView1"
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:background="#drawable/button_shape"
android:text="#string/Getstarted"
android:textColor="#FFFFFF"
android:textSize="23sp" />
<ImageButton
android:id="#+id/next"
android:layout_width="90dp"
android:layout_height="50dp"
android:layout_alignRight="#+id/textView1"
android:layout_below="#+id/textView1"
android:layout_marginTop="14dp"
android:background="#drawable/button_shape"
android:contentDescription="#string/Next"
android:onClick="NextQuote"
android:src="#drawable/navigationnextitem" />
<ImageButton
android:id="#+id/share"
android:layout_width="90dp"
android:layout_height="50dp"
android:layout_alignTop="#+id/next"
android:layout_centerHorizontal="true"
android:background="#drawable/button_shape"
android:contentDescription="#string/share"
android:onClick="Sharing"
android:src="#drawable/socialshare" />
<ImageButton
android:id="#+id/back"
android:layout_width="90dp"
android:layout_height="50dp"
android:layout_alignLeft="#+id/textView1"
android:layout_alignTop="#+id/next"
android:background="#drawable/button_shape"
android:contentDescription="#string/Back"
android:onClick="PreviousQuote"
android:src="#drawable/navigationpreviousitem" />
</RelativeLayout>
Java code for activity
package com.android.motivateme3;
import java.util.Random;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.support.v4.app.NavUtils;
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
public class Author extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_author);
// 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);
Button NextQuote = (Button)findViewById(R.id.next);
final TextView display = (TextView) findViewById(R.id.textView1);
NextQuote.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Random numGen = new Random();
int rNumber = numGen.nextInt(10);
if (rNumber == 0)
{
display.setText(R.string.Author1);
}
else if (rNumber == 1)
{
display.setText(R.string.Author2);
}
else if (rNumber == 2)
{
display.setText(R.string.Author3);
}
else if (rNumber == 3)
{
display.setText(R.string.Author4);
}
else if (rNumber == 4)
{
display.setText(R.string.Author5);
}
else if (rNumber == 5)
{
display.setText(R.string.Author6);
}
else if (rNumber == 6)
{
display.setText(R.string.Author7);
}
else if (rNumber == 7)
{
display.setText(R.string.Author8);
}
else if (rNumber == 8)
{
display.setText(R.string.Author9);
}
else if (rNumber == 9)
{
display.setText(R.string.Author10);
} }
});
}
ImageButton Sharing = (ImageButton)findViewById(R.id.share);
Sharing.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
TextView text = (TextView)findViewById(R.id.textView1);
String quote = text.getText().toString();{
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("plain/text");
shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "This is a great quote (from the Motivate Me! app)");
shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, quote);
startActivity(Intent.createChooser(shareIntent, "Share via:"));}}});
Button BackQuote = (Button)findViewById(R.id.back);
final TextView display = (TextView) findViewById(R.id.textView1);
BackQuote.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String prev = (String) display.getText();
display.setText(prev);
}
});}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.author, menu);
return true;
}
#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);
}
}
This is the stack trace
04-03 14:29:34.174: E/AndroidRuntime(17383): at android.app.ActivityThread.main(ActivityThread.java:4441)
04-03 14:29:34.174: E/AndroidRuntime(17383): at java.lang.reflect.Method.invokeNative(Native Method)
04-03 14:29:34.174: E/AndroidRuntime(17383): at java.lang.reflect.Method.invoke(Method.java:511)
04-03 14:29:34.174: E/AndroidRuntime(17383): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:823)
04-03 14:29:34.174: E/AndroidRuntime(17383): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:590)
04-03 14:29:34.174: E/AndroidRuntime(17383): at dalvik.system.NativeStart.main(Native Method)
04-03 14:29:34.174: E/AndroidRuntime(17383): Caused by: java.lang.ClassCastException: android.widget.ImageButton cannot be cast to android.widget.Button
04-03 14:29:34.174: E/AndroidRuntime(17383): at com.android.motivateme3.Author.setupActionBar(Author.java:36)
04-03 14:29:34.174: E/AndroidRuntime(17383): at com.android.motivateme3.Author.onCreate(Author.java:25)
04-03 14:29:34.174: E/AndroidRuntime(17383): at android.app.Activity.performCreate(Activity.java:4465)
04-03 14:29:34.174: E/AndroidRuntime(17383): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
04-03 14:29:34.174: E/AndroidRuntime(17383): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1931)
04-03 14:29:34.174: E/AndroidRuntime(17383): ... 11 more
04-03 14:29:41.664: I/Process(17383): Sending signal. PID: 17383 SIG: 9
It seems to me that R.id.next refers to an ImageButton, which cannot be cast into a Button, since it is not a subclass of a Button
Do you happen to see a ClassCastException?
To fix that particular issue, replace:
Button NextQuote = (Button)findViewById(R.id.next);
with
ImageButton NextQuote = (ImageButton)findViewById(R.id.next);