简体   繁体   中英

Changing the textview of an activity from another class (nullpointerexception)

I'm trying to make an app that generates a password and then saves it to a separate page in the app for the user to see. To do this, I have a button to generate the password and another that that is supposed to save that password to another page. I'm having trouble using setText in one class to update the TextView of the other class/activity.

Class with buttons.

public class Generate extends AppCompatActivity {

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

    final TextView passText = (TextView) findViewById(R.id.passText);
    //final TextView savedText = (TextView) findViewById(R.id.savedText);
    Button generatePassword = (Button) findViewById(R.id.generatePassword);
    Button savePassword = (Button) findViewById(R.id.savePassword);

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

            int passwordLength = 16;
            String allowedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%&";
            char[] allowedCharsArray = allowedChars.toCharArray();
            char[] chars = new char[passwordLength];
            Random random = new Random();

            for (int i = 0; i < passwordLength; i++) {
                chars[i] = allowedCharsArray[random.nextInt(allowedChars.length())];
            }
            passText.setText(chars, 0, passwordLength);
        }
    });

        savePassword.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v) {
            Save obj= new Save();
            obj.newText.setText("Hello"); //testing to see if this works
            /*Save obj = new Save();
            TextView savedText = obj.getTextView();
            savedText.setText("hello");*/
        }
    });
}
}

Activity with TextView that is supposed to change.

public class Save extends AppCompatActivity {
public static TextView newText;

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

    newText = (TextView) findViewById(R.id.savedText);
}
}

Catlog.

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
                                                                      at cs.rice.password_csp.Generate$2.onClick(Generate.java:52)
                                                                      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:6121)
                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)

What I'm getting here is that its saying that this line is referencing a null object.

obj.newText.setText("Hello"); 

I don't understand why that is because I'm pretty sure everything here looks right but I guess not.

I'm pretty new to this so any help would be great. I tried the solutions here , here , and here but all of them give me the same issue.

Instead of creating new instance of your Save activity, try using intent to pass password to Save activity and then show on TextView .

Send password to Save Activity from your Generate Activity:

savePassword.setOnClickListener(new View.OnClickListener(){
    public void onClick(View v) {

        Intent intent = new Intent(Generate.this, Save.class);
        intent.putExtra("PASSWORD", passText.getText());
        startActivity(intent);
    }
});

Receive data in Save Activity and show on TextView :

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

    newText = (TextView) findViewById(R.id.savedText);

    String password = getIntent().getStringExtra("PASSWORD");
    newText.setText(password);
}

Use a global class which extends Application to store the data. Define it so -

public class Global extends Application {

    private String customerName;
    private String customerPassword;



    public void setCustomerPassword(String password){customerPassword = password;}



    public String getCustomerPassword(){return customerPassword;}


}

Next change your manifest to include the following lines after

<application
        android:name=".Global"

After that in your first activity -

Global globalObject = (Global) getApplication

Next inside your onclick listener -

globalObject.setCustomerPassword(passwordField);

Next in your Save activity -

Global globalObject = (Global) getApplication();
String password = globalObject.getCustomerPassword();

Then set password to the textview. That simple :)

I don't recommend using sharedpreferences since that is not a good practice due to lots of reasons.

You could also try storing it into a sqllite db and then fetching it from there, but the method mentioned above is much simpler and prettier.

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