why the app crash after calling a method? - android

I hope you can help me I was trying to look into the other questions but I didnt found what I was trying to do or didn't get it.
this is a very simple example of what I'm trying to do. I have this main activity:
public class MainActivity extends Activity {
static EditText num1, num2; //Change EditText from TextView
static TextView num3; //Textview variable
int x, y, r;
Addition addition=new Addition();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
num1=(EditText)findViewById(R.id.editText);
num2=(EditText)findViewById(R.id.editText2);
num3=(TextView)findViewById(R.id.textView);
x = 0;
y = 0;
}
public void add (View view){
setXY();
r=addition.addResult(x,y);
num3.setText(String.valueOf(r));
}
public void setXY(){
x=Integer.parseInt(num1.getText().toString());
y=Integer.parseInt(num2.getText().toString());
}
}
and I am trying to call that method from this class
public class Addition {
public int addResult(int x, int y){
return x+y;
}
}
so at the beginning the app crashed because of the null values that was receiving from the layout, but after set the try catch the app was running. The problem comes when I click the "add" button the app crash again. do you guys can tell me why? what am I doing wrong? how should I do it? and if I have an app with more "operations" ,methods, is it worth creating a class with all this operations and call them from the main one? or maybe I shouldn't try to do this?
Greetings!!!
Chiok
Logcat
07-14 14:35:24.625 5407-5407/com.chiok.x2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.chiok.x2, PID: 5407
java.lang.IllegalStateException: Could not find method addition(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.widget.Button with id 'button'
at android.view.View$DeclaredOnClickListener.resolveMethod(View.java:4479)
at android.view.View$DeclaredOnClickListener.onClick(View.java:4443)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
07-14 14:35:25.893 5407-5407/com.chiok.x2 I/Process: Sending signal. PID: 5407 SIG: 9
and this is the 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="com.chiok.x2.MainActivity">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/editText"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="48dp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/editText2"
android:layout_below="#+id/editText"
android:layout_centerHorizontal="true"
android:layout_marginTop="52dp"
android:onClick="add" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button"
android:layout_below="#+id/editText2"
android:layout_centerHorizontal="true"
android:layout_marginTop="71dp"
android:onClick="addition" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/textView"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="56dp" />
I guess it have something to do with the editable objets that are null.. but nothing that I try works.

change these code
num1=(TextView)findViewById(id.editText);
num2=(TextView)findViewById(id.editText2);
num3=(TextView)findViewById(id.editText3);
to
num1=(TextView)findViewById(R.id.editText);
num2=(TextView)findViewById(R.id.editText2);
num3=(TextView)findViewById(R.id.editText3);
and remember to import R.java in your project.

onClick command which stored in layout need parameter View v in receiver method, so change addResult() to addResult(View v)

if I have an app with more "operations" ,methods, is it worth creating
a class with all this operations and call them from the main one?
Yes it worths that, it will make your code more object oriented. In this case it will make more sense if you change the name of class from Addition to Operations. Also Addition class does not need to be an activity. So don't extend it from MainActivity.
Just send two parameter to that method and make addResult return an int result which is addition of those two parameters.
And in your MainActivity get the return value of your addResult method and setText the edittext3.
public class MainActivity extends Activity {
TextView num1, num2,num3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
num1=(TextView)findViewById(R.id.editText);
num2=(TextView)findViewById(R.id.editText2);
num3=(TextView)findViewById(R.id.editText3);
// here I am trying to call the method
Addition x = new Addition();
int param1 = Integer.parseInt(num1.getText().toString());
int param2 = Integer.parseInt(num2.getText().toString());
int result = x.addResult(param1, param2);
num3.setText(String.valueOf(result));
}
}
And your Addition Class can be like this;
public class Addition {
public int addResult(int param1, int param2){
return param1 + param2;
}
}
Summary I changed setContentView(R.layout.activity_main);
Delete extends MainActivity in your Addition class.
Also if the error still persists, I need to see your xml layout where you define your textviews and button.

Make your Textview static. Try
static TextView num1, num2,num3;
Reason
Addition x = new Addition();
In the above code, it is creating a new instance of Addition class which is extending the MainActivity and hence the TextView will be NULL for the new instance. In order to make the TextView initialization available for all instances, make the TextView static.

Use following code.
public class MainActivity extends Activity {
EditText num1, num2; //Change EditText from TextView
TextView num3; //Textview variable
Button add; //Button variable
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //Add R.layout.activity_main
num1=(EditText)findViewById(R.id.editText); //R.id.editText
num2=(EditText)findViewById(R.id.editText2); //R.id.editText2
num3=(TextView)findViewById(R.id.textview); // initialize textview
add=(Button) findViewById(R.id.add); //initialize add button
final Addition x = new Addition();
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
x.addResult();
}
});
}
}
public class Addition {
public void addResult(){
try {
num3.setText(String.valueOf((Integer.parseInt(num1.getText().toString())+(Integer.parseInt(num2.getText().toString())))));
}
catch (Exception e) {}
}
}
}

Related

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.design.widget.AppBarLayout.addOnOffsetChangedListener [duplicate]

I have code:
public class HelloWorld extends Activity {
private Button buttonOk;
private Button buttonCancel;
private OnClickListener buttonOkListener = new OnClickListener() {
public void onClick(View v){
EditText editText = (EditText)findViewById(R.id.input);
CharSequence textFromInput = (CharSequence) editText.getText();
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context,textFromInput,duration);
toast.show();
}
};
private OnClickListener buttonCancelListener = new OnClickListener() {
public void onClick(View v){
EditText editText = (EditText)findViewById(R.id.input);
CharSequence textFromInput = (CharSequence) editText.getText();
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context,textFromInput,duration);
toast.show();
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
// ToDo add your GUI initialization code here
setContentView(R.layout.main);
buttonOk = (Button)findViewById(R.id.buttonOk);
buttonCancel = (Button)findViewById(R.id.buttonCancel);
buttonOk.setOnClickListener(buttonOkListener);
buttonCancel.setOnClickListener(buttonCancelListener);
}
}
and the layout file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Wpisz swoje imię:"/>
<EditText
android:id="#+id/input"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#android:drawable/editbox_background"
android:layout_below="#id/label"/>
<Button
android:id="#+id/buttonOk"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/input"
android:layout_alignParentRight="true"
android:layout_marginLeft="10dip"
android:text="OK" />
<Button
android:id="#+id/buttonCancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="#id/buttonOk"
android:layout_alignTop="#id/buttonOk"
android:text="Anuluj" />
</RelativeLayout>
Line with buttonCancel.setOnClickListener(buttonCancelListener); throws an Exception because buttonCancel is null. What i am doing wrong?
there is no problem with your codes, by right everything should work as per normal.
The most common mistake of encountering null via findViewById() method is when you forgot to call setContentView() or called it for the wrong layout.
I suggest cleaning your project and try again!!!!
I was having the same trouble, but after cleaning my project and running it again it works perfectly.
I'm not 100% sure but you are calling the findviewbyid's in the class initialisation. I think this code is called before the onCreate method so the view's cannot be found. Initializing the listeners in the oncreate method should work.
At times there are few points to be considered!
This can always happen even for experienced developers as well. I would suggest few points below,
Check that the findViewById is added in the appropriate life cycle of the activity or fragment which ever under consideration.
Also verify if the layout is inflated correctly and that the valid layout is set in the setContentView - which was incorrect in my case.
Also as mentioned above there are some cases where cleaning the project could help resolve this issue.

accessing intent views from activity class to java class

I have one java class and one Activity class.
In my java class, it consists of business logic. I want to access the Textviews from activity class to my java class.
If I create an object to activity class. I got all views in activity class as NULL and getting null pointer Exception.
This is my java class here I have created object for activity class and here I am getting NULLpointerException for tdoor.setText() method.
public class Subscribe {
viewtiles vtiles=new viewtiles();
public void sendMessageforstatus(String status)
{
if(status.contains("Door is open"))
{
vtiles.tdoor.setText("OPEN");
}
else if(status.equalsIgnoreCase("Door is close"))
{
vtiles.tdoor.setText("CLOSE");
}
This is my activity layout class
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tilesview);
tdoor = (TextView) findViewById(R.id.door2);
}
XML
<RelativeLayout xmlns:android="schemas.android.com/apk/res/android";
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/background_light" >
<TextView android:layout_width="79dp"
android:layout_height="wrap_content"
android:text="Door"
android:layout_marginTop="10dp"
android:layout_marginLeft="52dp"
android:id="#+id/door1"
android:textColor="#android:color/black"
android:textSize="20dp" />
</RelativeLayout>
Can u plzzz help me for this problem...
You can pass TextView object into your Java class,
public void sendMessageforstatus(String status, TextView txt)
{
// example
txt.setText("OPEN");
}

Not able to set text of textview from other activity

i have main activity:
public class MainActivity extends AppCompatActivity {
Button btnadd;
int a1 = 10;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnadd = (Button) findViewById(R.id.btnadd);
btnadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final SecondAct sa = new SecondAct();
sa.ttl(a1);
}
});
}
}
and i have other activity:
public class SecondAct extends Activity {
public TextView txt2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
txt2 = (TextView) findViewById(R.id.txt2);
}
public void numsum(int no)
{
txt2.setText(String.valueOf(no));
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<Button
android:id="#+id/btnadd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="addd"></Button>
<LinearLayout
android:layout_below="#+id/btnadd"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include layout="#layout/second"></include>
</LinearLayout>
</RelativeLayout>
When i click on button from main activity to set textview text of second activity then it gives me error.
Error:
FATAL EXCEPTION: main
Process: com.example.sumdemo, PID: 13809
java.lang.NullPointerException
at com.example.sumdemo.MainActivity$1.onClick(MainActivity.java:28)
at android.view.View.performClick(View.java:4463)
at android.view.View$PerformClick.run(View.java:18770)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5333)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
How can i set second activity value from main activity without passing data through intent ?
final SecondAct sa = new SecondAct();
sa.ttl(a1);
never use the new operator on a class that extends Activity. You have to use startActivity to start SecondAct, and provide additional info through the Intent object
Use Application class with a static parameter.
That is
class MyApp extends Application{
public static TextView tv;
}
in the first activity:
usemyapp.tv = (TextView) findViewById(...);
in oreder to have an access from somewhere use this:
if (MyApp.tv != null)
MyApp.tv.setText("a new text");
do not forget to wrap it in mainUiThread by using a handler.
in AndroidMainfest.xml file use this:
<application
android:name=".MyApp" <<<<<<<<<<<<<<<<<<<<<<<this the name of the class
>
Futhermore, do not create an activity class by a constructor. this is a very very bad idea:) You have this error because you have created the class but onCreate() method has not called and has not attached to Android UI process.
Use this question as guide.
How to manage `startActivityForResult` on Android?
And don't try to change one activity content from another activity.
When you create an Activity object through its constructor, you can't call its life cycle methods (e.g onCreate) so your activity doesn't have a View and you can't access your views. you must use startActivity and let android handle creating Activity object and call its life cycle method. you should change its view after inflating view. for your case, you can pass extra data via Intents and use that data in your second Activity

Edit text not receiving text

I have tried to solve it for hours but been unable to. What is going on is that I setted this editText, called the layout on the activity, and connect it to my variable on the activity, when you click on the field it opens the visual keyboard, but when you press a key, it takes you to a browser-like search screen, instead of just updating the edittext´s text.
on my xml the editText is:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background = "#drawable/splash"
android:orientation = "vertical">
<EditText
android:id="#+id/searchEdit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:singleLine="true"
android:textColor="#color/black"
android:textColorHint="#color/hintGray"
android:textSize="20dp"
android:paddingLeft="50dp"
android:paddingRight="10dp"
android:layout_marginTop="300dp"
android:background="#drawable/a01_text_box"
android:hint="Hint"
android:layout_gravity="center_horizontal" />
<ImageButton
android:id="#+id/searchButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/a01_boton_buscar"
android:layout_gravity="center_horizontal" />
</LinearLayout>
on the activity I do this
public class SubscribeActivity {
private EditText searchEdit;
private ImageButton searchButton;
private Context context;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.subscribe_main);
this.context = this;
findAndInitViews();
}
protected void findAndInitViews() {
searchEdit = (EditText) findViewById(R.id.searchEdit);
searchButton = (ImageButton) findViewById(R.id.searchButton);
searchButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String codeText = searchEdit.getText().toString();
Toast.makeText(context, codeText, Toast.LENGTH_LONG).show();
}
});
}
}
I still can't find a way for it not to happen. Can you help me?
Seems like you are not actually playing with activities
This is wrong:
public class SubscribeActivity
It should be something like:
public class SubscribeActivity extends Activity
first I would suggesting to use the getApplicationContext() Method of Activity - instead of casting the Activity down to your Context-Object. Beside you must extend Activity. Im wondering that your code is running... But I assume it's an copy and paste mistake.
Your onCreate(Bundle b) should be public instead of protected.
If the fault is still there I would comment the code not needed for displaying the EditText. And then step by step including the code back again.
Try it different way.
public class SubscribeActivity extends Activity{
private EditText searchEdit;
private ImageButton searchButton;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.subscribe_main);
searchEdit = (EditText) findViewById(R.id.searchEdit);
searchButton = (ImageButton) findViewById(R.id.searchButton);
}
searchButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String codeText = searchEdit.getText().toString();
Toast.makeText(SubscribeActivity.this, codeText, Toast.LENGTH_LONG).show();
}
});
}
}
Please try to do in this way and let me know the result.

Update EditText after Button is clicked

This EditText is inside an Activity that is part of a TabHost within the main Activity. It's just supposed to be 4 tabs with an EditText and two Buttons on each, one to increment and one to decrement the EditText field. However, if I ever try to setText() on one of the EditText boxes, the app crashes. So when I call setText() in onCreate() it crashes. Any help would be greatly appreciated!
<EditText
android:label="#+id/LifeForP1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autoText="true"
android:cursorVisible="false"
android:background="#null"
android:textColor="#999999"
android:color="#null"
android:layout_x="90px"
android:layout_y="0px"
android:textSize="250px"
android:maxLength="3"
android:capitalize="sentences"
android:layout_weight="1"
android:freezesText="true"
android:text="20"
/>
public class ActivityTab1 extends Activity {
private EditText lifeView;
int p1Life = 20;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content1layout);
lifeView = (EditText) findViewById(R.id.LifeForP1);
lifeView.setText(getString(R.string.lifeStart)); //Error here
}
#Override
protected void onResume() {
super.onResume();
}
public void p1GainLifeListener(View view) {
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("test gain 1");
alertDialog.show();
//String show = String.format("", Integer.toString(++p1Life));
//lifeView.setText(show);
}
In your xml, change
android:label="#+id/LifeForP1" to
android:id="#+id/LifeForP1"
When you bind your EditBox in code you reference to
findViewById(R.id.LifeForP1);
This means the EditBox needs an ID.
If you change the android:label to an android:id your code will run fine

Categories

Resources