错误:空指针异常

时间:2017-04-22 11:22:18

标签: android nullpointerexception

我正在运行gradle时遇到错误,但我不知道是什么问题 请帮帮我。

这是活动代码

package com.example.hnnhm.myapplication_new;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class SignupActivity extends Activity {
    private static final String TAG = SignupActivity.class.getSimpleName();
    private Button btnRegister;
    private Button btnLinkToLogin;
    private EditText inputFullName;
    private EditText inputEmail;
    private EditText inputAge;
    private EditText inputWeight;
    private EditText inputExtra;
    private EditText inputPassword;
    private ProgressDialog pDialog;
    private SessionManager session;
    private SQLiteHandler db;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_signup);

        inputFullName = (EditText) findViewById(R.id.editText);
        inputEmail = (EditText) findViewById(R.id.email);
        inputAge = (EditText) findViewById(R.id.editText2);
        inputEmail = (EditText) findViewById(R.id.editText3);
        inputExtra = (EditText) findViewById(R.id.editText6);
        inputPassword = (EditText) findViewById(R.id.password);
        btnRegister = (Button) findViewById(R.id.button);
        btnLinkToLogin = (Button) findViewById(R.id.button2);

        // Progress dialog
        pDialog = new ProgressDialog(this);
        pDialog.setCancelable(false);

        // Session manager
        session = new SessionManager(getApplicationContext());

        // SQLite database handler
        db = new SQLiteHandler(getApplicationContext());

        // Check if user is already logged in or not
        if (session.isLoggedIn()) {
            // User is already logged in. Take him to main activity
            Intent intent = new Intent(SignupActivity.this,
                    LoginActivity.class);
            startActivity(intent);
            finish();
        }

        // Register Button Click event
        btnRegister.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                String name = inputFullName.getText().toString().trim();
                String email = inputEmail.getText().toString().trim();
                String password = inputPassword.getText().toString().trim();
                String Age = inputAge.getText().toString().trim();
                String weight = inputWeight.getText().toString().trim();
                String Extra = inputExtra.getText().toString().trim();

                if (!name.isEmpty() && !email.isEmpty() && !password.isEmpty() && !Age.isEmpty()&& !weight.isEmpty()&& !Extra.isEmpty()) {
                    registerUser(name, email, password, Age , weight , Extra);
                } else {
                    Toast.makeText(getApplicationContext(),
                            "Please enter your details!", Toast.LENGTH_LONG)
                            .show();
                }
            }
        });

        // Link to Login Screen
        btnLinkToLogin.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                Intent i = new Intent(getApplicationContext(),
                        LoginActivity.class);
                startActivity(i);
                finish();
            }
        });

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    /**
     * Function to store user in MySQL database will post params(tag, name,
     * email, password) to register url
     */
    private void registerUser(final String name, final String email,
                              final String password, final String Age, final String weight, final String Extra) {
        // Tag used to cancel the request
        String tag_string_req = "req_register";

        pDialog.setMessage("Registering ...");
        showDialog();

        StringRequest strReq = new StringRequest(Request.Method.POST,
                AppConfig.URL_REGISTER, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Register Response: " + response.toString());
                hideDialog();

                try {
                    JSONObject jObj = new JSONObject(response);
                    boolean error = jObj.getBoolean("error");
                    if (!error) {
                        // User successfully stored in MySQL
                        // Now store the user in sqlite
                        String uid = jObj.getString("uid");

                        JSONObject user = jObj.getJSONObject("user");
                        String name = user.getString("name");
                        String email = user.getString("email");
                        String created_at = user
                                .getString("created_at");

                        // Inserting row in users table
                        db.addUser(name, email, uid, Age, weight,Extra);

                        Toast.makeText(getApplicationContext(), "User successfully registered. Try login now!", Toast.LENGTH_LONG).show();

                        // Launch login activity
                        Intent intent = new Intent(
                                SignupActivity.this,
                                LoginActivity.class);
                        startActivity(intent);
                        finish();
                    } else {

                        // Error occurred in registration. Get the error
                        // message
                        String errorMsg = jObj.getString("error_msg");
                        Toast.makeText(getApplicationContext(),
                                errorMsg, Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Registration Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_LONG).show();
                hideDialog();
            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                // Posting params to register url
                Map<String, String> params = new HashMap<String, String>();
                params.put("name", name);
                params.put("email", email);
                params.put("password", password);

                return params;
            }

        };

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
    }

    private void showDialog() {
        if (!pDialog.isShowing())
            pDialog.show();
    }

    private void hideDialog() {
        if (pDialog.isShowing())
            pDialog.dismiss();
    }

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    public Action getIndexApiAction() {
        Thing object = new Thing.Builder()
                .setName("Register Page") // TODO: Define a title for the content shown.
                // TODO: Make sure this auto-generated URL is correct.
                .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
                .build();
        return new Action.Builder(Action.TYPE_VIEW)
                .setObject(object)
                .setActionStatus(Action.STATUS_TYPE_COMPLETED)
                .build();
    }

    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        AppIndex.AppIndexApi.start(client, getIndexApiAction());
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        AppIndex.AppIndexApi.end(client, getIndexApiAction());
        client.disconnect();
    }
}

这是活动的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:id="@+id/activity_signup"
    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.hnnhm.myapplication_new.SignupActivity">

    <TextView
        android:text="Name:"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:id="@+id/textView3"
        android:textSize="18sp"
        android:textStyle="normal|bold"
        android:textColor="@color/common_google_signin_btn_text_dark_focused"
        android:layout_alignParentStart="true" />

    <TextView
        android:text="Age:"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView4"
        android:layout_below="@+id/editText"
        android:layout_alignParentStart="true"
        android:textStyle="normal|bold"
        android:textSize="18sp"
        android:textColor="@color/common_google_signin_btn_text_dark_focused" />

    <TextView
        android:text="Email:"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText2"
        android:layout_alignParentStart="true"
        android:id="@+id/textView5"
        android:textStyle="normal|bold"
        android:textColor="@color/common_google_signin_btn_text_dark_focused"
        android:textSize="18sp" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress"
        android:ems="10"
        android:layout_below="@+id/textView5"
        android:layout_alignEnd="@+id/editText2"
        android:id="@+id/editText4"
        android:text="Your Email"
        android:textColor="@color/common_plus_signin_btn_text_dark_disabled" />

    <TextView
        android:text="Password:"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView6"
        android:textStyle="normal|bold"
        android:textColor="@color/common_google_signin_btn_text_dark_focused"
        android:textSize="18sp"
        android:layout_below="@+id/editText4"
        android:layout_alignParentStart="true" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPassword"
        android:ems="10"
        android:layout_below="@+id/textView6"
        android:layout_alignParentStart="true"
        android:id="@+id/editText5"
        android:text="Password"
        android:textColor="@color/common_plus_signin_btn_text_dark_disabled" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:ems="10"
        android:id="@+id/editText2"
        android:textSize="18sp"
        android:text="Your age"
        android:textColor="@color/common_plus_signin_btn_text_dark_disabled"
        android:layout_below="@+id/textView4"
        android:layout_alignParentStart="true" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:text="Your name"
        android:ems="10"
        android:id="@+id/editText"
        android:textSize="18sp"
        android:textColor="@color/common_plus_signin_btn_text_dark_disabled"
        android:layout_below="@+id/textView3"
        android:layout_alignParentStart="true" />

    <TextView
        android:text="Weight:"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView9"
        android:textSize="18sp"
        android:textColor="@color/common_google_signin_btn_text_dark_focused"
        android:textStyle="normal|bold"
        android:layout_below="@+id/editText5"
        android:layout_alignParentStart="true" />

    <Button
        android:text="Login"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button2"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:layout_marginEnd="20dp" />

    <TextView
        android:text="already a member?"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView8"
        android:textAlignment="textStart"
        android:textStyle="normal|bold"
        android:layout_alignParentBottom="true"
        android:layout_toStartOf="@+id/button2" />

    <Button
        android:text="Signup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button"
        android:layout_marginStart="11dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentStart="true" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:text="Your weight"
        android:ems="10"
        android:layout_below="@+id/textView9"
        android:layout_alignParentStart="true"
        android:id="@+id/editText3"
        android:textColor="@color/common_plus_signin_btn_text_dark_disabled" />

    <TextView
        android:text="allergies and diseases:"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView7"
        android:textStyle="normal|bold"
        android:textSize="18sp"
        android:textColor="@color/common_google_signin_btn_text_dark_focused"
        android:layout_below="@+id/editText3"
        android:layout_alignParentStart="true" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:text="and allergies or chronic disease  you have"
        android:ems="10"
        android:id="@+id/editText6"
        android:textSize="18sp"
        android:textColor="@color/common_plus_signin_btn_text_dark_disabled"
        android:layout_below="@+id/textView7"
        android:layout_alignParentStart="true" />

</RelativeLayout>

这是我在运行gradle时遇到的错误

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.hnnhm.myapplication_new, PID: 4329
                  java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
                      at com.example.hnnhm.myapplication_new.SignupActivity$1.onClick(SignupActivity.java:86)
                      at android.view.View.performClick(View.java:5637)
                      at android.view.View$PerformClick.run(View.java:22429)
                      at android.os.Handler.handleCallback(Handler.java:751)
                      at android.os.Handler.dispatchMessage(Handler.java:95)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6119)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Disconnected from the target VM, address: 'localhost:8605', transport: 'socket'

3 个答案:

答案 0 :(得分:0)

可能的解决方案可能是:

  • 使用之前成功的Android项目查看gradle版本,或者如果这是第一个项目,请尝试从头开始重新安装gradle。

  • 如果gradle没有问题,请清理项目并重新构建项目。

  • 尝试在您声明和定义变量的代码上创建断点,并在调试模式下运行应用程序并检查变量的位置为NULL。

因为这些是我在我的项目上所做的尝试。

可能会有所帮助。

:)和平

答案 1 :(得分:0)

全部改变:

            String name = inputFullName.getText().toString().trim();
            String email = inputEmail.getText().toString().trim();
            String password = inputPassword.getText().toString().trim();
            String Age = inputAge.getText().toString().trim();
            String weight = inputWeight.getText().toString().trim();
            String Extra = inputExtra.getText().toString().trim();

            String name = inputFullName.getText().toString();
            String email = inputEmail.getText().toString();
            String password = inputPassword.getText().toString();
            String Age = inputAge.getText().toString();
            String weight = inputWeight.getText().toString();
            String Extra = inputExtra.getText().toString();

答案 2 :(得分:0)

Change your mappings like this and it will solve your error.
inputFullName = (EditText) findViewById(R.id.editText);
        inputEmail = (EditText) findViewById(R.id.editText4);
        inputAge = (EditText) findViewById(R.id.editText2);
        inputWeight = (EditText) findViewById(R.id.editText3);
        inputExtra = (EditText) findViewById(R.id.editText6);
        inputPassword = (EditText) findViewById(R.id.editText5);