将数据从一个活动传递到另一个活动时收到错误

时间:2017-03-07 07:22:23

标签: android android-intent

我将数据从一个活动发送到另一个活动。 但是获取错误空指针异常和应用程序崩溃。

错误 -

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.a98fit.neeraj.a98fit, PID: 31167
                  java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.BaseBundle.getString(java.lang.String)' on a null object reference
                      at com.a98fit.neeraj.a98fit.Signup$1.onClick(Signup.java:118)
                      at android.view.View.performClick(View.java:5612)
                      at android.view.View$PerformClick.run(View.java:22285)
                      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:6123)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
Application terminated.

一项活动 - 我正在存储数据令牌& userId在数据库中并通过意图发送到另一个活动。

 Intent intent1 = new Intent(Name.this, Signup.class);
                            intent1.putExtra("userId", userId);
                            intent1.putExtra("token",token);
                            startActivity(intent1); 

另一项活动 - 我在哪里

Bundle bundle = getIntent().getExtras();
String token = bundle.getString("token").toString();
String userId= bundle.getString("userId");

一项活动---

public class Name extends AppCompatActivity {
        private static final String TAG = Name.class.getSimpleName();

        private Button btn_name_next;
        EditText emailid,editTextUserName;
        private ProgressDialog pDialog;
        private SessionManager session;
        private SQLiteHandler db;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_name);
            btn_name_next = (Button) findViewById(R.id.btn_name_next);

            editTextUserName=(EditText) findViewById(R.id.editTextUserName);
            final TelephonyManager tm = (TelephonyManager) getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);

            final String tmDevice, tmSerial, androidId;
            tmDevice = "" + tm.getDeviceId();
            tmSerial = "" + tm.getSimSerialNumber();
            androidId = "" + Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);

            UUID deviceUuid = new UUID(androidId.hashCode(), ((long) tmDevice.hashCode() << 32) | tmSerial.hashCode());
            final String deviceId = deviceUuid.toString();
            Log.e(TAG, "Device Id: " + deviceId);
            // 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(Name.this,
                        MakemeHealthy.class);
                startActivity(intent);
                finish();
            }



            btn_name_next.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {




                    String name=editTextUserName.getText().toString();

                    if (name.length()==0) {

                        editTextUserName.setError("Tell us your name atleast");

                    }


                    else
                    {
                        //launchAgeScreen();
                        registerUser(name, deviceId);

                    }
                }
            });
        }

        private void registerUser(final String name, final String deviceId) {


                // Tag used to cancel the request
                String tag_string_req = "req_register";

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

                StringRequest strReq = new StringRequest(Request.Method.POST,
                        AppConfig.NAME_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 success = jObj.getBoolean("success");
                            //boolean error = jObj.getBoolean("error");
                            if (success) {
                                // User successfully stored in MySQL
                                // Now store the user in sqlite
                                //String uid = jObj.getString("uid");

                                String userId =jObj.getString("userId");
                                String token = jObj.getString("token");

                                db.addUser( token,userId);
                                //db.addUser(userId);
                                Intent intent1 = new Intent(Name.this, Signup.class);
                                intent1.putExtra("userId", userId);
                                intent1.putExtra("token",token);
                                startActivity(intent1);
                                Log.e(TAG, "token: " + token);
                                Log.e(TAG, "userId: " + userId);

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

                                // Launch login activity
                                Intent intent = new Intent(
                                        Name.this,
                                        Signup.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);
                        params.put("deviceId", deviceId);


                        return params;
                    }

                };

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

另一项活动 - 我发送数据。

protected void onCreate(Bundle savedInstanceState) {
        //ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.READ_PHONE_STATE}, 1);



       /* if(b!=null)
        {
            String token =(String) b.get("token");
            String userId = (String) b.get("userId");
           // Textv.setText(j);
        }*/
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_signup);
        TextView textViewlaer = (TextView) findViewById(R.id.textViewlater);
        btn_name_make = (Button) findViewById(R.id.btn_name_make);
        editTextEmailid = (EditText) findViewById(R.id.editTextEmailid);
        passwordentry = (EditText) findViewById(R.id.passwordentry);
        final TelephonyManager tm = (TelephonyManager) getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);

        final String tmDevice, tmSerial, androidId;
        tmDevice = "" + tm.getDeviceId();
        tmSerial = "" + tm.getSimSerialNumber();
        androidId = "" + Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);

        UUID deviceUuid = new UUID(androidId.hashCode(), ((long) tmDevice.hashCode() << 32) | tmSerial.hashCode());
        final String deviceId = deviceUuid.toString();
        Log.e(TAG, "Device Id: " + deviceId);
        // 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(Signup.this,
                    MakemeHealthy.class);
            startActivity(intent);
            finish();
        }

        // Make Me Awesome Button Click event
        btn_name_make.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String email = editTextEmailid.getText().toString();
                String password = passwordentry.getText().toString();

                Bundle bundle = getIntent().getExtras();
                String token = bundle.getString("token").toString();
                String userId= bundle.getString("userId");
                Log.e(TAG, "token: " + token);
                Log.e(TAG, "userId: " + userId);

                if (email.length() == 0) {

                    editTextEmailid.setError("Please Enter Email id");

                } else if (!Patterns.EMAIL_ADDRESS.matcher(email).matches())

                {
                    editTextEmailid.setError("Please enter Valid Email id");

                } else if (password.length() == 0) {

                    passwordentry.setError("Please Enter password");

                } else if (password.length() < 6) {

                    passwordentry.setError("Please Enter minimum 6 character");
                } else {

                    registerUser(token,userId,email,password);
                }


            }
        });


        // I'll do it later Button Click event
        textViewlaer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent doitlater = new Intent(Signup.this, Name.class);
                startActivity(doitlater);

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

4 个答案:

答案 0 :(得分:3)

你在这里弄错了

startActivity(intent);

您将意图值置于意图中,并且启动活动为intent1。所以请通过intent1而不是intent

startActivity(intent1);// pass this intent1

使用此代码

                            Intent intent1 = new Intent(Name.this, Signup.class);
                            intent1.putExtra("userId", userId);
                            intent1.putExtra("token",token);
                            startActivity(intent1);
                            Log.e(TAG, "token: " + token);
                            Log.e(TAG, "userId: " + userId);

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

答案 1 :(得分:1)

您的Bundle为空:

试试这个:在第二个活动中获取数据

 Intent i = getIntent();
String id = i.getStringExtra("userId");
String token = i.getStringExtra("token");

答案 2 :(得分:1)

您已在代码中两次调用Signup Actvity,请参阅代码中的以下代码。

Intent intent1 = new Intent(Name.this, Signup.class);
intent1.putExtra("userId", userId);
intent1.putExtra("token",token);
startActivity(intent1);
Log.e(TAG, "token: " + token);
Log.e(TAG, "userId: " + userId);

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

// Launch login activity
Intent intent = new Intent(Name.this,Signup.class);
startActivity(intent);
finish();

删除代码中Toast消息下方的代码。如下代码:

// Launch Signup activity
Intent intent1 = new Intent(Name.this, Signup.class);
intent1.putExtra("userId", userId);
intent1.putExtra("token",token);
startActivity(intent1);
Log.e(TAG, "token: " + token);
Log.e(TAG, "userId: " + userId);

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

答案 3 :(得分:0)

如果没有显示NullPointerException错误,请尝试这样:

Bundle bundle = getIntent().getExtras();
if(bundle !=null){
String token = bundle.getString("token").toString();
String userId= bundle.getString("userId");
}