简体   繁体   English

更改.java文件后发生错误(原因:java.lang.NullPointerException)

[英]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: 我从java / android开始,并尝试按照教程进行操作,但是用一些代码编辑“ CalcSimples.java”后,我得到了一些错误:

LogCat: 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: 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: 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. 取消注释该视图,并假定正确放置了这些EditTexts / Button,它应该可以工作。

Is R.id.btSoma defined in activity_calc_simples? 是否在activity_calc_simples中定义了R.id.btSoma? 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); btSome必须在activity_calc_simples中定义,或者,您必须setContentView(R.layout.some_other_layout); in which btSome is defined. 在其中定义了btSome。

HIH HIH

In the onCreate() method chnage all this. 在onCreate()方法中更改所有内容。

@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. 您的静态PlaceHolder类更新如下。

   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. 可以在活动文本中编辑引用,在活动中进行Botones和demas加密,在活动中可以进行局部布局,也可以在片段中进行适当的修改。 Entonces tienes que mover el codigo donde inicializabas los elementos del activity al fragment. 使片段移动,使片段移动。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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