0

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.

Community
  • 1
  • 1
jared___
  • 3
  • 4
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Joe C Apr 27 '17 at 21:48
  • 1
    Making any View static is a bad idea. Look up how to pass data between activities. – Distraction Apr 27 '17 at 21:59
  • Remember that `static` means that the variable is associated with the class and not with each individual member. `static` should only be used when every instance of the class has the same value. In this case, by making the `View` a static variable, you are saying that every activity shares the same view. This will lead to some undesirable results. – Code-Apprentice Apr 27 '17 at 23:11

2 Answers2

1

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);
}
Ferdous Ahamed
  • 21,438
  • 5
  • 52
  • 61
  • Thanks. The only problem with this is that the screen with the saved password clears if you go back to the home screen and access the activity from there. Do you know of a way I can make it save (or not clear) after I leave the activity? – jared___ Apr 27 '17 at 22:40
  • You can use sharedPreferences to store data permanently and retrieve from any where in your app. See this http://stackoverflow.com/questions/23024831/android-shared-preferences-example – Ferdous Ahamed Apr 27 '17 at 22:42
  • @jared___ SharedPreferences is good for storing data permanently. If you want to save the data temporarily in memory when an activity is destroyed, then you should override `onSaveInstanceState()` and `onRestoreInstanceState()`. – Code-Apprentice Apr 27 '17 at 23:09
  • @Code-Apprentice How would I go about doing that? I've been messing around with SharedPreferences for over 2 hours now so I think I'm just gonna try this instead. – jared___ Apr 28 '17 at 01:16
  • @jared___ There are good tutorials online which already explain it. Particularly, you should look on developer.android.com. – Code-Apprentice Apr 28 '17 at 01:31
-1

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.