简体   繁体   中英

Error after changing .java file (Caused by: java.lang.NullPointerException)

I'm starting at java/android and I'm trying to do an App following a tutorial, but after editing the "CalcSimples.java" with some codes I got some erros:

LogCat:

06-17 12:16:30.730: E/test(1254): Exception 
06-17 12:16:30.732: E/AndroidRuntime(1254): FATAL EXCEPTION: main 
06-17 12:16:30.732: E/AndroidRuntime(1254): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.calculadorasimples/com.example.calculadorasimples.CalcSimples}: java.lang.NullPointerException 
06-17 12:16:30.732: E/AndroidRuntime(1254):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2306)
06-17 12:16:30.732: E/AndroidRuntime(1254):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2358)
06-17 12:16:30.732: E/AndroidRuntime(1254):  at android.app.ActivityThread.access$600(ActivityThread.java:156)
06-17 12:16:30.732: E/AndroidRuntime(1254):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1340)
06-17 12:16:30.732: E/AndroidRuntime(1254):  at android.os.Handler.dispatchMessage(Handler.java:99)
06-17 12:16:30.732: E/AndroidRuntime(1254):  at android.os.Looper.loop(Looper.java:153)
06-17 12:16:30.732: E/AndroidRuntime(1254):  at android.app.ActivityThread.main(ActivityThread.java:5299)
06-17 12:16:30.732: E/AndroidRuntime(1254):  at java.lang.reflect.Method.invokeNative(Native Method)
06-17 12:16:30.732: E/AndroidRuntime(1254):  at java.lang.reflect.Method.invoke(Method.java:511)
06-17 12:16:30.732: E/AndroidRuntime(1254):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
06-17 12:16:30.732: E/AndroidRuntime(1254):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
06-17 12:16:30.732: E/AndroidRuntime(1254):  at dalvik.system.NativeStart.main(Native Method)
06-17 12:16:30.732: E/AndroidRuntime(1254): Caused by: java.lang.NullPointerException 
06-17 12:16:30.732: E/AndroidRuntime(1254):  at com.example.calculadorasimples.CalcSimples.onCreate(CalcSimples.java:32)
06-17 12:16:30.732: E/AndroidRuntime(1254):  at android.app.Activity.performCreate(Activity.java:5182)
06-17 12:16:30.732: E/AndroidRuntime(1254):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
06-17 12:16:30.732: E/AndroidRuntime(1254):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270)
06-17 12:16:30.732: E/AndroidRuntime(1254):  ... 11 more

fragment_calc_simples.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.example.calculadorasimples.CalcSimples$PlaceholderFragment" >

    <TextView
        android:id="@+id/tvNumero1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Digite o primeiro numero: " />

    <EditText
        android:id="@+id/etNumero1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tvNumero1"
        android:layout_marginTop="5pt"
        android:inputType="number" />

    <TextView
        android:id="@+id/tvNumero2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/etNumero1"
        android:layout_marginTop="5pt"
        android:text="Digite o segundo numero: " />

    <EditText
        android:id="@+id/etNumero2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tvNumero2"
        android:layout_marginTop="5pt"
        android:inputType="number" />

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/etNumero2"
        android:layout_marginTop="5pt"
        android:text="Somar"
        android:id="@+id/btSoma" />

    <EditText
        android:id="@+id/etResultado"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/btSoma"
        android:layout_marginTop="5pt"
        android:inputType="number" />

</RelativeLayout>

CalcSimples.java:

package com.example.calculadorasimples;

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.*;
import android.view.*;

public class CalcSimples extends ActionBarActivity {

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

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

        etNum1 = (EditText) findViewById(R.id.etNumero1);
        etNum2 = (EditText) findViewById(R.id.etNumero2);
        etResultado = (EditText) findViewById(R.id.etResultado);
        btSomar = (Button) findViewById(R.id.btSoma);

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

        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.calc_simples, 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_calc_simples, container, false);
            return rootView;
        }
    }

}

I think it's simple to solve, but i can't figure out where is the error.

Thanks for the help.

Edit:

After making some tests, I've figured out where is the error:

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

But still I don't know what's the problem with the code, I've uncommented the line

setContentView(R.layout.activity_calc_simples);

But the result is the same.

You cannot run

etNum1 = (EditText) findViewById(R.id.etNumero1);
etNum2 = (EditText) findViewById(R.id.etNumero2);
etResultado = (EditText) findViewById(R.id.etResultado);
btSomar = (Button) findViewById(R.id.btSoma);

before you set your view, which you commented out just above. Uncomment out that view, and assuming these EditTexts/Buttons are placed properly, it should work.

Is R.id.btSoma defined in activity_calc_simples? You need to make

setContentView(R.layout.activity_calc_simples); 

But make sure you are inflating the correct layout. btSome must be defined in activity_calc_simples or, you must setContentView(R.layout.some_other_layout); in which btSome is defined.

HIH

In the onCreate() method chnage all this.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_calc_simples);
    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment())
                .commit();
    }
}

An your static PlaceHolder class update like this.

   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_calc_simples, container, false);

    etNum1 = (EditText) rootView.findViewById(R.id.etNumero1);
    etNum2 = (EditText) rootView.findViewById(R.id.etNumero2);
    etResultado = (EditText) rootView.findViewById(R.id.etResultado);
    btSomar = (Button) rootView.findViewById(R.id.btSoma);

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

}

Lo que sucede es lo siguiente, en tu actividad estas haciendo referencia a los componentes como el EditText, Botones y demas, pero estos ya no se encuentran en el layout de la actividad, al parecer moviste esos componentes al layout del fragment. Entonces tienes que mover el codigo donde inicializabas los elementos del activity al fragment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM