Java 无法从 Bundle 中获取字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41381102/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 23:20:35  来源:igfitidea点击:

Unable to get string from a Bundle

javaandroidbundle

提问by E Ajanthan

I created a new Activity once a Login is successful. But when I start the app, the app crash within 5 seconds with the message

登录成功后,我创建了一个新活动。但是当我启动应用程序时,应用程序在 5 秒内崩溃并显示消息

Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference

Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference

Error is coming from this

错误来自于此

name.setText(" "+bundle.getString("name"));


public class LoginActivity extends Activity {

    public ImageView bgLogo;

    Button login_button;
    EditText Username, Password;
    String username, password;
    String login_url = "http://192.168.0.19/login.php";
    AlertDialog.Builder builder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE); // Enlever la barre bleue
        setContentView(R.layout.activity_login);

        initExit ();

        builder = new AlertDialog.Builder(LoginActivity.this);
        login_button = (Button) findViewById(R.id.bLogin);
        Username = (EditText) findViewById(R.id.etUsername);
        Password = (EditText) findViewById(R.id.etPassword);

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

                username = Username.getText().toString();
                password = Password.getText().toString();

                if (username.equals("") || password.equals("")) {

                    builder.setTitle("Mince une erreur...");
                    displayAlert("Veuillez entrer un username et un mot de passe correct...");
                }

                else {

                    StringRequest stringRequest = new StringRequest(Request.Method.POST, login_url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {

                                    JSONArray jsonArray = null;
                                    try {
                                        jsonArray = new JSONArray(response);
                                        JSONObject jsonObject = jsonArray.getJSONObject(0);
                                        String code = jsonObject.getString("code");

                                        if (code.equals("login_failed")) {

                                            builder.setTitle("Erreur d'authentification");
                                            displayAlert(jsonObject.getString("message"));
                                        }

                                        else {

                                            Intent intent = new Intent (LoginActivity.this, UserAreaActivity.class);
                                            Bundle bundle = new Bundle();
                                            bundle.putString("name", jsonObject.getString("name"));
                                            intent.putExtras(bundle);
                                            startActivity(intent);
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }

                                }
                            }, new Response.ErrorListener() {

                        @Override
                        public void onErrorResponse(VolleyError error) {

                            Toast.makeText(LoginActivity.this, "Erreur", Toast.LENGTH_LONG).show();
                            error.printStackTrace();

                        }
                    })
                    {
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {

                            Map <String, String> params = new HashMap<String, String>();
                            params.put("user_name", username);
                            params.put("password", password);
                            return params;
                        }
                    };

                    MySingleton.getInstance(LoginActivity.this).addToRequestque(stringRequest);
                }
            }
        });
    }

    private void initExit() {

        bgLogo = (ImageView) findViewById(R.id.bgLogo1);
        bgLogo.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick (View v) {

                Intent intent = new Intent (LoginActivity.this, MainActivity.class);
                startActivity(intent);
            }
        });
    }

    public void displayAlert (String message) {

        builder.setMessage(message);
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Username.setText("");
                Password.setText("");
            }
        });

        AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }

    @Override
    public void onBackPressed() {
        // do nothing.
        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        startActivity(intent);
        return;
    }
}


public class UserAreaActivity extends Activity {

    public ImageView bgNet;
    public ImageView bgChat;
    public ImageView bgStats;
    public ImageView bgGo;
    public Button bLogout;

    TextView name;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE); // Enlever la barre bleue
        setContentView(R.layout.activity_user_area);

        name = (TextView) findViewById(R.id.name);

        Bundle bundle = getIntent().getExtras();
        name.setText(" "+bundle.getString("name"));

        initGoHome ();
        initPlay ();
        initGoStats ();
        initGoChat ();
        buttonLogout ();
    }

    @Override
    public void onBackPressed() {
        return;
    }

    private void initGoHome () {

        bgNet = (ImageView) findViewById(R.id.bgNet);
        bgNet.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick (View v) {

                Intent intent = new Intent (UserAreaActivity.this, HomeActivity.class);
                startActivity(intent);
            }
        });
    }

    private void initPlay () {

        bgGo = (ImageView) findViewById(R.id.bgGo);
        bgGo.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick (View v) {

                Intent intent = new Intent (UserAreaActivity.this, PlayActivity.class);
                startActivity(intent);
            }
        });
    }

    private void initGoStats () {

        bgStats = (ImageView) findViewById(R.id.bgStats);
        bgStats.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick (View v) {

                Intent intent = new Intent (UserAreaActivity.this, StatsActivity.class);
                startActivity(intent);
            }
        });
    }

    private void initGoChat () {

        bgChat = (ImageView) findViewById(R.id.bgChat);
        bgChat.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick (View v) {

                Intent intent = new Intent (UserAreaActivity.this, ChatActivity.class);
                startActivity(intent);
            }
        });
    }

    private void buttonLogout () {

        bLogout = (Button) findViewById(R.id.bLogout);
        bLogout.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick (View v) {

                Intent intent = new Intent (UserAreaActivity.this, MainActivity.class);
                startActivity(intent);
            }
        });
    }
}

采纳答案by Amit Upadhyay

Replace this code snippet:

替换此代码片段:

    Bundle bundle = getIntent().getExtras();
    name.setText(" "+bundle.getString("name"));

with

Bundle bundle = getIntent().getExtras();
if (bundle != null)
{
    name.setText(" "+bundle.getString("name"));
}

Your problem will be solved.

您的问题将得到解决。

回答by Chirag Patel

Replace this code snippet:

替换此代码片段:

        "class".with(getActivity())
            .using(Album.class)
            .bucketId(Application.getBucketId())
            .entityId(getArguments().getString(YourActivity.GALLERY_ID))
            .retrieve(new XXXX()); Change code : Use Bundle method To replace code below type  Bundle bundle = getArguments();
            "example".with(getActivity())
            .using(Album.class)
            .bucketId(Application.getBucketId())
            .entityId(bundle.getString(YourActivity.GALLERY_ID))
            .retrieve(new XXXX());

回答by T? Minh Ti?n

Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference

尝试在空对象引用上调用虚拟方法“java.lang.String android.os.Bundle.getString(java.lang.String)”

Well, you need to avoid calling a method on a null object. In your case:

好吧,您需要避免在空对象上调用方法。在你的情况下:

name.setText(" "+bundle.getString("name"));

The bundle is a null object in this case. So it throws an error. The solution to avoid this crash is to add a if/else statement

在这种情况下,包是一个空对象。所以它会抛出一个错误。避免这种崩溃的解决方案是添加一个 if/else 语句

if (bundle != null) 
   // set text for name like what you have done
else
   // set a default text for name

But, I suggest it's better to check your code and understand why your bundle is getting null.

但是,我建议最好检查您的代码并了解为什么您的包为空。

回答by Suraj Gurav

The code is resolved for me by typing in Activity where you get the value by bundle

通过键入 Activity 来为我解析代码,您可以在其中按捆绑包获取值

    Bundle bundle = getIntent().getExtras();
    hName = bundle.getString("sharedName");

    b1 =new Bundle(); //this b1 should be declared Globally where you are getting value 
    b1.putString("sharedName",hName);