-1

I have a mainActivity.java class with a layout called activity_main.xml and a .xml file named drawer_menu.xml which has a textView that's displayed in the app's drawer menu.I want to set the drawer menu's textView text to a String value that i have in my mainActivity.java class. How can i access that textView inside the mainActivity class?

activity_main.java (the part accessing the textView):

    /**
 * Prompts the user for his/her username
 * when the tutorial is done
 */
private void promptForUsername() {
    UsernameDialog dialog = new UsernameDialog();
    dialog.setCancelable(false);
    dialog.show(getFragmentManager(),"USERNAME_DIALOG");
    username.setText(getUsername());
}

public void setUsername(String name) {
    tempName = name;
}

public String getUsername() {
    return tempName;
}

UsernameDialog.java class:

public class UsernameDialog extends DialogFragment {

@BindView(R.id.editText) EditText mEditText;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    // inflate the layout using the dialog themed context
    final Context context = getActivity();
    final LayoutInflater inflater = LayoutInflater.from(context);
    final View view = inflater.inflate(R.layout.username_dialog,null,false);

    final MainActivity activity = new MainActivity();

    ButterKnife.bind(this,view);

    DialogInterface.OnClickListener posListener = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            activity.setUsername(mEditText.getText().toString());
            Log.d("USERNAME",mEditText.getText().toString());
        }
    };

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity())
            .setTitle("Choose your username")
            .setView(view)
            .setPositiveButton("OK",posListener);
    return builder.create();
}
}

drawer_menu.xml (contains the TextView to be accessed):

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="@color/NavigationDrawerHeader">

<ImageView
    android:id="@+id/menu_logo"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:layout_marginStart="18dp"
    android:layout_marginTop="10dp"
    android:adjustViewBounds="true"
    android:contentDescription="@string/logo"
    app:srcCompat="@drawable/user_icon" />

<TextView
    android:id="@+id/username"
    android:layout_width="wrap_content"
    android:layout_height="66dp"
    android:layout_alignParentStart="true"
    android:layout_alignTop="@+id/menu_logo"
    android:layout_marginStart="93dp"
    android:layout_marginTop="5dp"
    android:fontFamily="@font/alegreya_sans_extrabold"
    android:paddingTop="25dp"
    android:text="username"
    android:textColor="#ffffff"
    android:textSize="18sp" />

</RelativeLayout>
Stelios Papamichail
  • 955
  • 2
  • 19
  • 57

4 Answers4

1

Try this code at the end of onCreate() method in MainActivity.java

NavigationView navigationView = findViewById(R.id.nav_view);
//R.id.nav_view the id of the navigation drawer

View drawerHead = navigationView.getHeaderView(0);
//0 index of the header

TextView userName = drawerHead.findViewById(R.id.username);
Ahmed Emad
  • 674
  • 6
  • 19
  • @SteliosPapamichail see my edit to the answer I hope it helps tell me if it didn't we could figure out why – Ahmed Emad Aug 01 '18 at 21:16
  • Sadly it still doesn't change anything :( . I changed some of my code so that the username is stored in the internal storage with SharedPrefs but the same thing keeps on happening – Stelios Papamichail Aug 02 '18 at 09:51
  • beside that my answer solves an error in your code I recommend see the below link to compare what is wrong with your code as I think that another thing is wrong but I can't see or not in this segment of code http://android-coding.blogspot.com/2012/07/dialogfragment-with-interface-to-pass.html – Ahmed Emad Aug 02 '18 at 15:53
  • From what i can tell this link is about passing data back and forth to an activity which is not a problem i have. My problem is accessing a textView that's on a different layout than that of the activity's – Stelios Papamichail Aug 02 '18 at 17:26
  • You don't need to pass the textview between pages but you can pass the data to the activity that have that textview and can change the text value – Ahmed Emad Aug 02 '18 at 17:33
  • That "activity" is the drawerMenu and it doesn't have an activity.java file associated with it – Stelios Papamichail Aug 02 '18 at 17:56
  • I saw something right now `username.setText(getUsername());` this line need to be added to setUserName() function so after set text it will update the `textView` – Ahmed Emad Aug 02 '18 at 18:02
  • Should be the same since if it's not set to the new text, the string already has a value of "error" but the issue is that it can't access it,hence the NPR – Stelios Papamichail Aug 02 '18 at 21:37
  • can u log the `username.getText()` value before and after `tempName = name;` line you will notice it doesn't change anything because show function on the dialog doesn't wait till the dialog dismiss to return and run the next line of code which change the value of the `username` `TextView` so you need to call `username.setText(getUsername());` inside `setUserName()` – Ahmed Emad Aug 03 '18 at 21:51
  • I get that but since that doesn't happen the default value of "error" is set and logged but not displayed. I think you've mixed some things up, the issue is that i am getting a NPE because I'm trying to access the .setText method of a supposedly non existent textView. I don't have any issues changing the String's value in code dynamically. The problem is accessing that textView without the NPE. What am i missing here? How should i approach accessing this view? – Stelios Papamichail Aug 03 '18 at 22:09
  • where do you inflate this drawerMenu.xml file ? – Ahmed Emad Aug 03 '18 at 22:36
  • I have edited my answer again with I think the solution of your problem – Ahmed Emad Aug 03 '18 at 22:49
  • that was it, i should have thought of that earlier. Good job and thanks for sticking with me on this one! – Stelios Papamichail Aug 04 '18 at 16:53
0

you can define

    static TextView tv; 

and can access to from other class

0

Nobody recommends the use of static views. Look here for more.

Now, for your situation you can create a String resource to be able use same text in both activities. How to do that? here:

  • In your strings.xml add a string like this
<string name="my_string">what ever u want to put here </string>
  • Add TextView
 TextView textView = (TextView) findViewById(R.id.Id_of_TextView);
 textView.setText(getString(R.id.my_string));

OR

You can add that string directly in both textview's xml.

And to get the string value in a variable you can use

String temp = getResources().getString(R.string.my_string);
Sahdeep Singh
  • 1,342
  • 1
  • 13
  • 34
0

If you give the textview an id on the xml layout file, you could then use TextView myTextView = (TextView) findViewById(R.id.myTextView);

user3064141
  • 407
  • 4
  • 17
  • I've tried this but it's causing the nullPointerException – Stelios Papamichail Jul 30 '18 at 12:07
  • are you using fragments? if so, you might need to call this.getActivity() or if it's a textview in another layout you may need to inflate the layout first by using the layout inflator. (i'm guessing the names, but I think you see what I mean.) – user3064141 Aug 01 '18 at 01:52
  • i do actually, i just posted my code so take a look if you have some free time :D – Stelios Papamichail Aug 01 '18 at 13:19
  • I think Ahmed is right (see his Edit). It seems like you should be calling this.getActivity(...) or something. But my larger question is it seems this is a field that will remain for that user so it almost seems like you should be handling this as a User Preference for which there is a specific dialog fragment you can use. if you did it that way once they close the dialog the user preference store would know the value for the username entered and you would have access to it to populate the textview. google "android shared user store" and "anddroid user preferences fragment" examples. – user3064141 Aug 01 '18 at 21:56
  • that's what i wanted to do actually, is there an actual dialog for that? – Stelios Papamichail Aug 02 '18 at 09:09
  • I just saved it to the internal storage using SharedPrefs but still the problem keeps on happening. It throws the same NullPointerException.Isn't that because of the mainActivity trying to access an xml element from a different layout? – Stelios Papamichail Aug 02 '18 at 09:53