Fatal exception:main Android Eclipse - java

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;
}

Related

android.text.Editable android.widget.EditText.getText() on application click button

I have a problem with this code
public class AgendaActivity extends AppCompatActivity {
private DbManager db=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.agendalayout);
db=new DbManager(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.addxml, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
// User chose the "Settings" item, show the app settings UI...
return true;
case R.id.action_add:
final Dialog d = new Dialog(this);
d.setTitle("Prova");
d.setCancelable(false);
d.setContentView(R.layout.popupdialog);
Window window = d.getWindow();
window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
d.show();
//eventi Button
Button b = (Button) d.findViewById(R.id.ok_action);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
EditText p1 = (EditText) findViewById(R.id.Ora_inizio);
EditText p2 = (EditText) findViewById(R.id.Ora_fine);
EditText p3 = (EditText) findViewById(R.id.pause);
String p1Value = p1.getText().toString();
String p2Value = p2.getText().toString();
String p3Value = p3.getText().toString();
try {
int p1Final = Integer.parseInt(p1Value);
} catch (Exception e) {
Toast exceptionAgenda = Toast.makeText(AgendaActivity.this,
"Uno dei due campi o entrambi sono vuoti!",
Toast.LENGTH_LONG);
exceptionAgenda.show();
}
//db.save(primoValore,secondoValore,terzoValore);
}
});
default:
}
return true;
};
}
}
});
Button b2=(Button) d.findViewById(R.id.canceldialog);
b2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(d.getContext(), "cliccatocancel", Toast.LENGTH_LONG).show();
d.cancel();
}
});
The problem is when I click the button Ok_action this error: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference. I think the problem is on the line String p1Value = p1.getText().toString(); and I don’t know how to resolve. Can someone help me?
add an output error:
11-06 13:03:24.747 16356-16356/com.apps.giak.lavorotime E/AndroidRuntime: FATAL EXCEPTION: main
11-06 13:03:24.747 16356-16356/com.apps.giak.lavorotime E/AndroidRuntime: Process: com.apps.giak.lavorotime, PID: 16356
11-06 13:03:24.747 16356-16356/com.apps.giak.lavorotime E/AndroidRuntime: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
11-06 13:03:24.747 16356-16356/com.apps.giak.lavorotime E/AndroidRuntime: at com.apps.giak.lavorotime.AgendaActivity$1.onClick(AgendaActivity.java:62)
11-06 13:03:24.747 16356-16356/com.apps.giak.lavorotime E/AndroidRuntime: at android.view.View.performClick(View.java:5155)
11-06 13:03:24.747 16356-16356/com.apps.giak.lavorotime E/AndroidRuntime: at android.view.View$PerformClick.run(View.java:20747)
11-06 13:03:24.747 16356-16356/com.apps.giak.lavorotime E/AndroidRuntime: at android.os.Handler.handleCallback(Handler.java:739)
11-06 13:03:24.747 16356-16356/com.apps.giak.lavorotime E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:95)
11-06 13:03:24.747 16356-16356/com.apps.giak.lavorotime E/AndroidRuntime: at android.os.Looper.loop(Looper.java:145)
11-06 13:03:24.747 16356-16356/com.apps.giak.lavorotime E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5832)
11-06 13:03:24.747 16356-16356/com.apps.giak.lavorotime E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
11-06 13:03:24.747 16356-16356/com.apps.giak.lavorotime E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:372)
11-06 13:03:24.747 16356-16356/com.apps.giak.lavorotime E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteIn
XML
`<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"></LinearLayout>
<EditText
android:id="#+id/Ora_inizio"
android:inputType="numberDecimal"
android:digits="0123456789./"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginBottom="4dp"
android:hint="Ore" />
<EditText
android:id="#+id/Ora_fine"
android:inputType="date"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginBottom="16dp"
android:fontFamily="sans-serif"
android:hint="data"/>
<EditText
android:id="#+id/pause"
android:inputType="numberDecimal"
android:digits="0123456789./"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginBottom="16dp"
android:fontFamily="sans-serif"
android:hint=""/>
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:id="#+id/ok_action"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:text="Ok"/>
<Button
android:id="#+id/canceldialog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Cancel"/>
</TableRow>
`
Please use
EditText p1 = (EditText) d.findViewById(R.id.Ora_inizio);
instead of
EditText p1 = (EditText) findViewById(R.id.Ora_inizio);
Because the view with id R.id.Ora_inizio is in the layout which inflated to the dialog, i.e, R.layout.popupdialog.
So you have to use Dialog.findViewById() method.
But now you are trying to access this Edittext from your activity layout (R.layout.agendalayout) instead of the dialog layout.
You can tell--without even looking at your source code--what the problem is, just by the error message, and the line you stated. p1 is null; and you tried running getText() on it. Null doesn't have a method getText(), so you get a null pointer exception.
findViewById(R.id.Ora_inizio) likely is returning null, meaning Android had trouble finding the view by that ID in the current layout. Double check that this ID is used for a view in the current layout.

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>

How do I make the back button I created in the activity change the text in the textView to the previous text created by the random generator?

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);

Categories