Android Runtime Crash - java

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.

Related

Unable to start activity: NullPointerException [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
Hi I am encountering a null pointer error when I click on the activity Links. The purpose of my feature is to call a list of links in the form of list view. Below is the logcat and as far as I understand it is coming from my onItemClickListener, but I can't seem to point out the null error.:
sitesList.setOnItemClickListener(new OnItemClickListener()
Links.java
package com.example.sgrecipe;
import java.io.FileNotFoundException;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
public class Links extends Activity {
private SitesAdapter mAdapter;
private ListView sitesList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("StackSites", "OnCreate()");
setContentView(R.layout.activity_main);
//Get reference to our ListView
sitesList = (ListView)findViewById(R.id.sitesList);
//Set the click listener to launch the browser when a row is clicked.
sitesList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int pos,long id) {
String url = mAdapter.getItem(pos).getLink();
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
/*
* If network is available download the xml from the Internet.
* If not then try to use the local file from last time.
*/
if(isNetworkAvailable()){
Log.i("StackSites", "starting download Task");
SitesDownloadTask download = new SitesDownloadTask();
download.execute();
}else{
mAdapter = new SitesAdapter(getApplicationContext(), -1, SitesXmlPullParser.getStackSitesFromFile(Links.this));
sitesList.setAdapter(mAdapter);
}
}
//Helper method to determine if Internet connection is available.
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
/*
* AsyncTask that will download the xml file for us and store it locally.
* After the download is done we'll parse the local file.
*/
private class SitesDownloadTask extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... arg0) {
//Download the file
try {
Downloader.DownloadFromUrl("https://dl.dropboxusercontent.com/u/5724095/XmlParseExample/stacksites.xml", openFileOutput("StackSites.xml", Context.MODE_PRIVATE));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result){
//setup our Adapter and set it to the ListView.
mAdapter = new SitesAdapter(Links.this, -1, SitesXmlPullParser.getStackSitesFromFile(Links.this));
sitesList.setAdapter(mAdapter);
Log.i("StackSites", "adapter size = "+ mAdapter.getCount());
}
}
}
activity_links.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"
tools:context=".Links" >
<ListView
android:id="#+id/sitesList"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
row_site.xml (for the listview)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp" >
<ProgressBar
android:id="#+id/progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageView
android:id="#+id/iconImg"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_marginRight="8dp" />
<TextView
android:id="#+id/nameTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/iconImg"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="#+id/aboutTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/iconImg"
android:textSize="12sp"
android:layout_below="#id/nameTxt"
/>
</RelativeLayout>
Here is the logcat:
02-23 15:13:10.856: E/AndroidRuntime(8201): FATAL EXCEPTION: main
02-23 15:13:10.856: E/AndroidRuntime(8201): Process: com.example.sgrecipe, PID: 8201
02-23 15:13:10.856: E/AndroidRuntime(8201): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sgrecipe/com.example.sgrecipe.Links}: java.lang.NullPointerException
02-23 15:13:10.856: E/AndroidRuntime(8201): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2292)
02-23 15:13:10.856: E/AndroidRuntime(8201): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2350)
02-23 15:13:10.856: E/AndroidRuntime(8201): at android.app.ActivityThread.access$800(ActivityThread.java:163)
02-23 15:13:10.856: E/AndroidRuntime(8201): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1257)
02-23 15:13:10.856: E/AndroidRuntime(8201): at android.os.Handler.dispatchMessage(Handler.java:102)
02-23 15:13:10.856: E/AndroidRuntime(8201): at android.os.Looper.loop(Looper.java:157)
02-23 15:13:10.856: E/AndroidRuntime(8201): at android.app.ActivityThread.main(ActivityThread.java:5335)
02-23 15:13:10.856: E/AndroidRuntime(8201): at java.lang.reflect.Method.invokeNative(Native Method)
02-23 15:13:10.856: E/AndroidRuntime(8201): at java.lang.reflect.Method.invoke(Method.java:515)
02-23 15:13:10.856: E/AndroidRuntime(8201): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
02-23 15:13:10.856: E/AndroidRuntime(8201): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
02-23 15:13:10.856: E/AndroidRuntime(8201): at dalvik.system.NativeStart.main(Native Method)
02-23 15:13:10.856: E/AndroidRuntime(8201): Caused by: java.lang.NullPointerException
02-23 15:13:10.856: E/AndroidRuntime(8201): at com.example.sgrecipe.Links.onCreate(Links.java:36)
02-23 15:13:10.856: E/AndroidRuntime(8201): at android.app.Activity.performCreate(Activity.java:5389)
02-23 15:13:10.856: E/AndroidRuntime(8201): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
02-23 15:13:10.856: E/AndroidRuntime(8201): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2256)
Any help is really appreciate, thank you!
Change following line
setContentView(R.layout.activity_main);
to
setContentView(R.layout.activity_links);
Seems like your using different layouts:
setContentView(R.layout.activity_main);
vs
activity_links.xml

App Crashing (Unable to start ComponentInfo Error) [duplicate]

This question already has answers here:
NullPointerException accessing views in onCreate()
(13 answers)
Closed 8 years ago.
I am having trouble finding the source of the crash in my application. I've done a clean/build. I'm very new to Android dev so I'm still learning. From looking at the logcat, I think there maybe some null error exception that might have something to do with the calculate function. Any help or guidance is appreciated.
The java code:
package com.example.rectangle;
import java.text.DecimalFormat;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.os.Build;
public class MainActivity extends ActionBarActivity implements OnEditorActionListener {
//graphical variables
private EditText widthInput;
private EditText heightInput;
private TextView areaOutput;
private TextView perimeterOutput;
private Button calculateButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//assign ids to graphical variables
widthInput = (EditText) findViewById(R.id.widthEditText);
heightInput = (EditText) findViewById(R.id.heightEditText);
areaOutput = (TextView) findViewById(R.id.areaOutput);
perimeterOutput = (TextView) findViewById(R.id.perimterOutput);
calculateButton = (Button) findViewById(R.id.calculateButton);
widthInput.setOnEditorActionListener(this);
heightInput.setOnEditorActionListener(this);
//calculate and display
calculateAreaAndPerimeter();
}
//hide keyboard
//source: http://stackoverflow.com/questions/8697499/hide-keyboard-when-user-taps-anywhere-else-on-the-screen-in-android
#Override
public boolean onTouchEvent(MotionEvent event) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.
INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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;
}
}
//display
public void display(String area, String perimeter)
{
areaOutput.setText(area);
perimeterOutput.setText(perimeter);
}
//algorithms
private void calculateAreaAndPerimeter()
{
//get width and height
String widthInputString = widthInput.getText().toString();
String heightInputString = heightInput.getText().toString();
float width = Float.parseFloat(widthInputString);
float height = Float.parseFloat(heightInputString);
//calculate and display
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
float area;
area = width * height;
String areaString = (df.format(area)) + "";
float perimeter;
perimeter = (width * 2) + (height * 2);
String perimeterString = (df.format(perimeter)) + "";
display(areaString, perimeterString);
}
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
// TODO Auto-generated method stub
calculateAreaAndPerimeter();
return false;
}
}
The logcat:
11-12 13:05:14.049: E/AndroidRuntime(10535): FATAL EXCEPTION: main
11-12 13:05:14.049: E/AndroidRuntime(10535): Process: com.example.rectangle, PID: 10535
11-12 13:05:14.049: E/AndroidRuntime(10535): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.rectangle/com.example.rectangle.MainActivity}: java.lang.NullPointerException
11-12 13:05:14.049: E/AndroidRuntime(10535): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2198)
11-12 13:05:14.049: E/AndroidRuntime(10535): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2257)
11-12 13:05:14.049: E/AndroidRuntime(10535): at android.app.ActivityThread.access$800(ActivityThread.java:139)
11-12 13:05:14.049: E/AndroidRuntime(10535): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
11-12 13:05:14.049: E/AndroidRuntime(10535): at android.os.Handler.dispatchMessage(Handler.java:102)
11-12 13:05:14.049: E/AndroidRuntime(10535): at android.os.Looper.loop(Looper.java:136)
11-12 13:05:14.049: E/AndroidRuntime(10535): at android.app.ActivityThread.main(ActivityThread.java:5086)
11-12 13:05:14.049: E/AndroidRuntime(10535): at java.lang.reflect.Method.invokeNative(Native Method)
11-12 13:05:14.049: E/AndroidRuntime(10535): at java.lang.reflect.Method.invoke(Method.java:515)
11-12 13:05:14.049: E/AndroidRuntime(10535): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
11-12 13:05:14.049: E/AndroidRuntime(10535): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
11-12 13:05:14.049: E/AndroidRuntime(10535): at dalvik.system.NativeStart.main(Native Method)
11-12 13:05:14.049: E/AndroidRuntime(10535): Caused by: java.lang.NullPointerException
11-12 13:05:14.049: E/AndroidRuntime(10535): at com.example.rectangle.MainActivity.onCreate(MainActivity.java:46)
11-12 13:05:14.049: E/AndroidRuntime(10535): at android.app.Activity.performCreate(Activity.java:5248)
11-12 13:05:14.049: E/AndroidRuntime(10535): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)
11-12 13:05:14.049: E/AndroidRuntime(10535): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2162)
11-12 13:05:14.049: E/AndroidRuntime(10535): ... 11 more
Fragment_main
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/heightTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/widthTextView"
android:layout_below="#+id/widthTextView"
android:layout_marginTop="29dp"
android:text="Height"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/areaTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/heightTextView"
android:layout_below="#+id/heightTextView"
android:layout_marginTop="30dp"
android:text="Area"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/perimeterTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/areaTextView"
android:layout_below="#+id/areaTextView"
android:layout_marginTop="40dp"
android:text="Perimeter"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/heightEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/heightTextView"
android:layout_alignLeft="#+id/widthEditText"
android:layout_alignRight="#+id/widthEditText"
android:ems="10"
android:inputType="numberSigned"
android:text="0.0" />
<TextView
android:id="#+id/widthTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="35dp"
android:text="Width"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/widthEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/heightTextView"
android:layout_alignParentRight="true"
android:ems="10"
android:inputType="numberDecimal"
android:text="0.0" />
<TextView
android:id="#+id/areaOutput"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/areaTextView"
android:layout_marginLeft="38dp"
android:layout_toRightOf="#+id/perimeterTextView"
android:text="0.0"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/perimterOutput"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/perimeterTextView"
android:layout_alignBottom="#+id/perimeterTextView"
android:layout_alignLeft="#+id/areaOutput"
android:text="0.0"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
Try this:
TextView.OnEditorActionListener listener = new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
// TODO Auto-generated method stub
calculateAreaAndPerimeter();
return false;
}
};
The compile may still want to the one you have, and if, so create one like the above.
I think you have to tell the compiler its a listener, even though it may have created the method you have. Android Studio doesn't create listener syntax very well and I typically have to go back and surround a new public method with the listener stuff. Hope that works!

Crash when adding a OnClickListener to a Button

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.

FATAL EXCEPTION: main. (Runtime exception) . Android

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>

android getViewById() NullPointerException

I'm trying to make my app changes its layout when user rotate the screen.
When i launch the app while the screen of virtual machines is in portrait position.
The app is ok when launch but when I rotate the screen to landscape, the app will stops and the logCat shows a nullPointerException at line 40
line 39 btn=(Button)findViewById(R.id.btn);
line 40 btn.setOnClickListener(btnListener);
I think the findViewById() method is returning null, but i dont know why.
Also, if i launch the app while screen in landscape position, the same error occured.
SOLVED: the problem might be the arrangement of nested if, add braces for every if and else-if do solve this problem
Here are the codes:
MainActivity.java
package com.example.test;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
SharedPreferences preference;
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
preference = getSharedPreferences("preferences", MODE_PRIVATE);
if(getResources().getConfiguration().orientation == 1)
if(preference.getInt("THE_CHECKED", 0) == 0)
setContentView(R.layout.portrait_black);
else if(preference.getInt("THE_CHECKED", 0) == 1)
setContentView(R.layout.portrait_white);
else if(getResources().getConfiguration().orientation == 2)
if(preference.getInt("THE_CHECKED", 0) == 0)
setContentView(R.layout.landscape_black);
else if(preference.getInt("THE_CHECKED", 0) == 1)
setContentView(R.layout.landscape_white);
btn=(Button)findViewById(R.id.btn);
btn.setOnClickListener(btnListener);
}
private Button.OnClickListener btnListener = new Button.OnClickListener()
{
public void onClick(View v)
{
Toast toast1 = Toast.makeText(MainActivity.this, "HI", Toast.LENGTH_LONG);
toast1.show();
}
};
private DialogInterface.OnClickListener theDialogListener = new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
SharedPreferences.Editor editor = preference.edit();
switch(which)
{
case 0: //Black
editor.putInt("THE_CHECKED", 0);
break;
case 1: //White
editor.putInt("THE_CHECKED", 1);
break;
}
editor.commit();
((Dialog)dialog).dismiss();
onCreate(new Bundle());
}
};
#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)
{
SharedPreferences.Editor editor = preference.edit();
switch (item.getItemId())
{
case R.id.theme:
Builder theDialog = new AlertDialog.Builder(this);
theDialog.setTitle("Theme");
theDialog.setSingleChoiceItems(R.array.theme_menu, preference.getInt("THE_CHECKED", 0), theDialogListener);
theDialog.show();
break;
}
editor.commit();
return super.onOptionsItemSelected(item);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
onCreate(new Bundle());
}
}
Layouts
portrait_white.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/LinearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
android:orientation="vertical" >
<Button
android:id="#+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="portrait"
android:textSize="30sp"
android:textColor="#000000" />
</LinearLayout>
portrait_black.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/LinearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000"
android:orientation="vertical" >
<Button
android:id="#+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="portrait"
android:textSize="30sp"
android:textColor="#000000" />
</LinearLayout>
landscape_white.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/LinearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
android:orientation="vertical" >
<Button
android:id="#+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="landscape"
android:textSize="30sp"
android:textColor="#000000" />
</LinearLayout>
landscape_black.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/LinearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000"
android:orientation="vertical" >
<Button
android:id="#+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="landscape"
android:textSize="30sp"
android:textColor="#000000" />
</LinearLayout>
LogCat(when i launch the app while screen is in landscape position)
02-21 01:26:53.895: D/AndroidRuntime(1836): Shutting down VM
02-21 01:26:53.925: W/dalvikvm(1836): threadid=1: thread exiting with uncaught exception (group=0x41465700)
02-21 01:26:53.935: E/AndroidRuntime(1836): FATAL EXCEPTION: main
02-21 01:26:53.935: E/AndroidRuntime(1836): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.test/com.example.test.MainActivity}: java.lang.NullPointerException
02-21 01:26:53.935: E/AndroidRuntime(1836): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
02-21 01:26:53.935: E/AndroidRuntime(1836): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
02-21 01:26:53.935: E/AndroidRuntime(1836): at android.app.ActivityThread.access$600(ActivityThread.java:141)
02-21 01:26:53.935: E/AndroidRuntime(1836): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
02-21 01:26:53.935: E/AndroidRuntime(1836): at android.os.Handler.dispatchMessage(Handler.java:99)
02-21 01:26:53.935: E/AndroidRuntime(1836): at android.os.Looper.loop(Looper.java:137)
02-21 01:26:53.935: E/AndroidRuntime(1836): at android.app.ActivityThread.main(ActivityThread.java:5103)
02-21 01:26:53.935: E/AndroidRuntime(1836): at java.lang.reflect.Method.invokeNative(Native Method)
02-21 01:26:53.935: E/AndroidRuntime(1836): at java.lang.reflect.Method.invoke(Method.java:525)
02-21 01:26:53.935: E/AndroidRuntime(1836): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
02-21 01:26:53.935: E/AndroidRuntime(1836): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
02-21 01:26:53.935: E/AndroidRuntime(1836): at dalvik.system.NativeStart.main(Native Method)
02-21 01:26:53.935: E/AndroidRuntime(1836): Caused by: java.lang.NullPointerException
02-21 01:26:53.935: E/AndroidRuntime(1836): at com.example.test.MainActivity.onCreate(MainActivity.java:40)
02-21 01:26:53.935: E/AndroidRuntime(1836): at android.app.Activity.performCreate(Activity.java:5133)
02-21 01:26:53.935: E/AndroidRuntime(1836): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
02-21 01:26:53.935: E/AndroidRuntime(1836): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
02-21 01:26:53.935: E/AndroidRuntime(1836): ... 11 more
Thanks.
You don't have setContentView() in your Activity, hence, there's actually no View referenced to your activity and no views to find using findViewById() method, make sure the setContentView() was actually called...
Regards!
Use it this way. You have written nested if else and the second condition will never be executed in landscape mode i.e. orientation==2
package com.example.test;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
SharedPreferences preference;
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
preference = getSharedPreferences("preferences", MODE_PRIVATE);
if(getResources().getConfiguration().orientation == 1)
{
if(preference.getInt("THE_CHECKED", 0) == 0)
setContentView(R.layout.portrait_black);
else if(preference.getInt("THE_CHECKED", 0) == 1)
setContentView(R.layout.portrait_white);
}
else if(getResources().getConfiguration().orientation == 2)
if(preference.getInt("THE_CHECKED", 0) == 0)
setContentView(R.layout.landscape_black);
else if(preference.getInt("THE_CHECKED", 0) == 1)
setContentView(R.layout.landscape_white);
btn=(Button)findViewById(R.id.btn);
btn.setOnClickListener(btnListener);
}
private Button.OnClickListener btnListener = new Button.OnClickListener()
{
public void onClick(View v)
{
Toast toast1 = Toast.makeText(MainActivity.this, "HI", Toast.LENGTH_LONG);
toast1.show();
}
};
private DialogInterface.OnClickListener theDialogListener = new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
SharedPreferences.Editor editor = preference.edit();
switch(which)
{
case 0: //Black
editor.putInt("THE_CHECKED", 0);
break;
case 1: //White
editor.putInt("THE_CHECKED", 1);
break;
}
editor.commit();
((Dialog)dialog).dismiss();
onCreate(new Bundle());
}
};
#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)
{
SharedPreferences.Editor editor = preference.edit();
switch (item.getItemId())
{
case R.id.theme:
Builder theDialog = new AlertDialog.Builder(this);
theDialog.setTitle("Theme");
theDialog.setSingleChoiceItems(R.array.theme_menu, preference.getInt("THE_CHECKED", 0), theDialogListener);
theDialog.show();
break;
}
editor.commit();
return super.onOptionsItemSelected(item);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
onCreate(new Bundle());
}
}
Could you print the getResources().getConfiguration().orientation, I think it may be others values than 1 and 2
Infact, we have 4 value of getResources().getConfiguration().orientation: Configuration.ORIENTATION_PORTRAIT = 1, Configuration.ORIENTATION_LANDSCAPE =2, Configuration.ORIENTATION_SQUARE =3, Configuration.ORIENTATION_UNDEFINED =0

Categories