Closing application (Unfortunately Myapplication has stopped)

Asked

Viewed 7,213 times

1

I am doing the application below, of course Neri, but when I implement the code referring to the button the application closes alone with error

Unfortunately Myapplication has stopped

If you comment on the button code, the application runs. Follow the code:

MainActivity

package br.com.calculadora;

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.os.Build;
import android.widget.*;

public class MainActivity extends ActionBarActivity {

EditText etNum1, etNum2, etResultado;
double num1, num2, resultado;
Button btSomar;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment())
                .commit();
    }

    etNum1 = (EditText) findViewById(R.id.calculo_numero1);
    etNum2 = (EditText) findViewById(R.id.calculo_numero2);
    etResultado = (EditText) findViewById(R.id.calculo_resultado);

    btSomar = (Button) findViewById(R.id.botao_soma);

    btSomar.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            num1 = Double.parseDouble(etNum1.getText().toString());
            num2 = Double.parseDouble(etNum2.getText().toString());     
            resultado = num1 + num2;
            etResultado.setText(String.valueOf(resultado));


        }

    });

}


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

}

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="br.com.calculadora.MainActivity$PlaceholderFragment" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/titulo" />

<TextView
    android:id="@+id/textView3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/textView1"
    android:layout_below="@+id/textView1"
    android:layout_marginTop="18dp"
    android:text="@string/text1" />

<EditText
    android:id="@+id/calculo_numero1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/textView3"
    android:layout_below="@+id/textView3"
    android:ems="10"
    android:inputType="number" />

<TextView
    android:id="@+id/textView2"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignRight="@+id/textView1"
    android:layout_below="@+id/calculo_numero1"
    android:text="@string/text2" />

<EditText
    android:id="@+id/calculo_numero2"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/calculo_numero1"
    android:layout_below="@+id/textView2"
    android:ems="10"
    android:inputType="number" />

<TextView
    android:id="@+id/textView4"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/botao_soma"
    android:layout_centerVertical="true"
    android:text="@string/resultado" />

<EditText
    android:id="@+id/calculo_resultado"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/calculo_numero2"
    android:layout_below="@+id/textView4"
    android:ems="10"
    android:inputType="number" />

<Button
    android:id="@+id/botao_soma"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/calculo_numero2"
    android:layout_below="@+id/calculo_numero2"
    android:text="@string/button1" />

</RelativeLayout>

log of the error in LogCat:

03-18 16:18:54.339: D/AndroidRuntime(1879): Shutting down VM
03-18 16:18:54.339: W/dalvikvm(1879): threadid=1: thread exiting with uncaught exception    (group=0xb3a75ba8)
03-18 16:18:54.389: E/AndroidRuntime(1879): FATAL EXCEPTION: main
03-18 16:18:54.389: E/AndroidRuntime(1879): Process: br.com.calculadora, PID: 1879
03-18 16:18:54.389: E/AndroidRuntime(1879): java.lang.RuntimeException: Unable to start   activity ComponentInfo{br.com.calculadora/br.com.calculadora.MainActivity}: java.lang.NullPointerException
03-18 16:18:54.389: E/AndroidRuntime(1879):     at    android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
03-18 16:18:54.389: E/AndroidRuntime(1879):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
03-18 16:18:54.389: E/AndroidRuntime(1879):     at android.app.ActivityThread.access$800(ActivityThread.java:135)
03-18 16:18:54.389: E/AndroidRuntime(1879):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
03-18 16:18:54.389: E/AndroidRuntime(1879):     at android.os.Handler.dispatchMessage(Handler.java:102)
03-18 16:18:54.389: E/AndroidRuntime(1879):     at android.os.Looper.loop(Looper.java:136)
03-18 16:18:54.389: E/AndroidRuntime(1879):     at android.app.ActivityThread.main(ActivityThread.java:5017)
03-18 16:18:54.389: E/AndroidRuntime(1879):     at java.lang.reflect.Method.invokeNative(Native Method)
03-18 16:18:54.389: E/AndroidRuntime(1879):     at java.lang.reflect.Method.invoke(Method.java:515)
03-18 16:18:54.389: E/AndroidRuntime(1879):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-18 16:18:54.389: E/AndroidRuntime(1879):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
03-18 16:18:54.389: E/AndroidRuntime(1879):     at dalvik.system.NativeStart.main(Native Method)
03-18 16:18:54.389: E/AndroidRuntime(1879): Caused by: java.lang.NullPointerException
03-18 16:18:54.389: E/AndroidRuntime(1879):     at br.com.calculadora.MainActivity.onCreate(MainActivity.java:39)
03-18 16:18:54.389: E/AndroidRuntime(1879):     at android.app.Activity.performCreate(Activity.java:5231)
03-18 16:18:54.389: E/AndroidRuntime(1879):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
03-18 16:18:54.389: E/AndroidRuntime(1879):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
03-18 16:18:54.389: E/AndroidRuntime(1879):     ... 11 more
03-18 16:23:54.839: I/Process(1879): Sending signal. PID: 1879 SIG: 9

After the changes suggested by @Exceptionai, the code was:

MainActivity:

package br.com.calculadora;

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.os.Build;
import android.widget.*;

public class MainActivity extends ActionBarActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    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 {

    EditText etNum1, etNum2, etResultado;
    double num1, num2, resultado;
    Button btSomar;

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);

        etNum1 = (EditText) rootView.findViewById(R.id.calculo_numero1);
        etNum2 = (EditText) rootView.findViewById(R.id.calculo_numero2);
        etResultado = (EditText) rootView.findViewById(R.id.calculo_resultado);


        btSomar = (Button) rootView.findViewById(R.id.botao_soma);

        btSomar.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                num1 = Double.parseDouble(etNum1.getText().toString());
                num2 = Double.parseDouble(etNum2.getText().toString());     
                resultado = num1 + num2;
                etResultado.setText(String.valueOf(resultado));

            }

        });


        return rootView;
    }
}

}

Follows also 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="br.com.calculadora.MainActivity"
    tools:ignore="MergeRootFrame" />

3 answers

2


I had this problem and I solved it like this:

/*
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment implements View.OnClickListener {
  • Solved my problem, thank you very much @Euder

1

You are trying to locatilize the button in the layout activity_main but your button is on the fragment fragment_main, so it is null.

Just move your code from onCreate from Activity to the onCreateView fragment and use rootView.

btSomar = (Button) rootView.findViewById(R.id.botao_soma);

  • I’m not sure if the method onCreateView() is the most suitable place to move the code. This method should not exclusively return the view that makes up Fragment, according to the life cycle of Fragments?

  • @Piovezan Depende. The problem described is very basic, the OP is obviously beginner in Android and so I described the simplest way to solve the problem, without going into details of the best practice of using fragments. Let’s go one step at a time.

  • @Exceptional, I did as you said, but the error persists, I moved all the code.

  • @Jamesortiz Update the question with the new code and also put the xml of your activity_main. Remembering that was only to move the code of the button.

  • @Exceptional, I put in the new code, thank you for your help!

0

It can also occur when a character foreign to the example code is written: Incorrect implementation

.....
private String getClassName() {
        String s = getClass().getName();
        return s.substring(s.lastIndexOf(",")); 
    }
.....

Correct implementation

.....
private String getClassName() {
        String s = getClass().getName();
        return s.substring(s.lastIndexOf(".)); /*Observe que nesta linha    
                                        deve ter um ponto em vez da vírgula*/
    }
.....

Browser other questions tagged

You are not signed in. Login or sign up in order to post.