this is my last desperate attempt to fix this problem.
i am using dialogfragment to make my dialog window MyDialog. the window is supposed to show a score I have sent with and the user can then write in their name and confirm. i am then supposed to be able to retrieve their name.
My first problem is that the edittext that are supposed to show the score, doesn't want to show the score i set the edittext to be (it will only show new text if it was in the xml file). I can however still retrieve the correct score(text) afterwards from the same edittext.
The second problem is that the text that the user writes in can't be retrieved since the edittext isn't updating. However the text that was in the field from the xml file can be retrieved.
It seems like the edittext doesn't want to refresh after they are made in the xml file.
the dialog class (imports taken out):
public class MyDialog extends DialogFragment
{
private EditText scoreEdit;
private EditText userEdit;
private DialogClickListener callback;
public interface DialogClickListener
{
public void onFinishedClick();
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
try
{
callback = (DialogClickListener) getActivity();
}catch(ClassCastException e)
{
throw new ClassCastException("called class must implement interface");
}
}
public static MyDialog newInstance(int title)
{
MyDialog frag = new MyDialog();
Bundle args = new Bundle();
args.putInt("tittel",title);
frag.setArguments(args);
return frag;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View inflatedView = inflater.inflate(R.layout.dig_lay, null);
scoreEdit = (EditText) inflatedView.findViewById(R.id.dialogScoreEdit);
userEdit = (EditText) inflatedView.findViewById(R.id.dialogUsernameEdit);
scoreEdit.setText("score supposed to change");
// scoreEdit (edittext) is not changing
dialog.setView(inflater.inflate(R.layout.dig_lay, null));
dialog.setTitle("Title");
dialog.setPositiveButton("reg1", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int whichButton)
{
System.out.println("new text supposed to be: " + userEdit.getText().toString());
//old text from xml shows
callback.onFinishedClick();
}
});
setCancelable(false);
return dialog.create();
}
}
the XML file for the dialog window:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/dialogLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="16dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginBottom="4dp">
<TextView
android:text="score"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/dialogScoreEdit"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="score here"
android:inputType="none"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="4dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginBottom="16dp"
android:fontFamily="sans-serif">
<TextView
android:text="Username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<EditText
android:id="#+id/dialogUsernameEdit"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="retrive this"
android:inputType="none"/>
</LinearLayout>
</LinearLayout>
picture of the dialogwindow: http://i.stack.imgur.com/EvwSe.png
I have tried calling onResume() and putting the new score in. but the edittext still doesn't change.
I appreciate any answer and sorry for any bad English :)
It looks like there are a few issues there. The ones I have noticed are that when you set your view you are reinflating the view, versus setting it to the view you have already set up when you do
dialog.setView(inflater.inflate(R.layout.dig_lay, null));
you want to set that instead to
dialog.setView(inflatedView);
Also, since we can't see the actual data you are putting into the EditText, we can't see if that might be null, etc.
Finally, I never see you run a scoreEdit.getText(), so you wouldn't be retrieving any changes the user made to the edittext.
Related
I am trying to create a simple PopupWindow with a text entry field.
I know there are many questions of this type, but none seem to solve my problem. This is the XML of my popup layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:background="#color/white"
android:gravity="center"
android:padding="15dp"
android:layout_gravity="center"
android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Dodaj produkt po identyfikatorze"
android:textSize="15sp"
android:gravity="center"
/>
<EditText
android:layout_width="match_parent"
android:textSize="20sp"
android:hint="Identyfikator"
android:minWidth="250dp"
android:id="#+id/insert_edit"
android:gravity="center"
android:layout_height="match_parent" />
<LinearLayout
android:layout_width="match_parent"
android:gravity="center"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="wrap_content"
android:gravity="center"
android:layout_height="wrap_content"
android:id="#+id/insert_ok"
android:text="OK"/>
<Button
android:layout_width="wrap_content"
android:gravity="center"
android:layout_height="wrap_content"
android:id="#+id/insert_cancel"
android:text="Anuluj"/>
</LinearLayout>
</LinearLayout>
Now, I want to create this layout in my main activity when a FAB is pressed. This is how I do it:
public class ScrollingActivity extends AppCompatActivity {
private ActivityScrollingBinding binding;
private int ACTIVITY_LOAD_DATABASE = 1;
AbstractDatabase database;
RowAdapter rowAdapter;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
database = Room.databaseBuilder(getApplicationContext(), AbstractDatabase.class, "magazyn_db")
.allowMainThreadQueries().build();
binding = ActivityScrollingBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
FloatingActionButton fab = binding.addCode;
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.println(Log.INFO, "VIEWs", "Showing popup");
PopupWindow codePopup;
View popupView = getLayoutInflater().inflate(R.layout.insert_code, binding.getRoot());
codePopup = new PopupWindow(popupView);
codePopup.setFocusable(true);
codePopup.setOutsideTouchable(true);
View cancelButton = codePopup.getContentView().findViewById(R.id.insert_cancel);
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
codePopup.dismiss();
}
});
View acceptButton = codePopup.getContentView().findViewById(R.id.insert_ok);
acceptButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
View editView = codePopup.getContentView().findViewById(R.id.insert_edit);
String id = ((EditText)editView).getText().toString().trim();
insertNewElement(id);
codePopup.dismiss();
}
});
}
});
[...]
For an unknown reason my popup doesn't go dismissed, both when I click outside of it, or press the cancel button (when I tried to print some logs from the handler, they worked). I have tried many solutions, also inflating it with no root, but then 'showAtPosition' doesn't even show it, and no solutions here on stackoverflow seem to help me even though there are many of them.
Is anyone able to point the problem here?
public void dismiss () Disposes of the popup window. This method can be invoked only after showAsDropDown(android.view.View) has been executed. Failing that, calling this method will have no effect.
This question already has answers here:
findViewByID returns null
(33 answers)
Closed 3 years ago.
I'm trying to change the text of a NavigationView's child. I am using findViewById to get directly to the TextView. It works in the MainActivity, but in every other Activity findViewById returns a null reference.
By the way this is my first submitted question and I hope I respected the guidelines.
I can't seem to figure this out so I don't know where to start.
This is the NavigationView located in the layout of every activity
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:visibility="visible"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer"/>
nav_header_main is the component that has the said TextView, it is referenced in the code above. This is nav_header_main:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/nav_header"
android:theme="#style/ThemeOverlay.AppCompat.Dark">
<TextView
android:id="#+id/nav_header_textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="Angheluta Filip"
android:textAppearance="#style/TextAppearance.AppCompat.Body1"
android:textColor="#android:color/white" />
</LinearLayout>
This code is from MainActivity, where finding the said text view doesn't return a null reference
NavigationManager navigationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Downloads the database and than proceeds to setup the Activity
//onDataChange gets called when the download is finished and dataSnapshot is the downloaded
//data
final AppCompatActivity context = this;
FirebaseHandler.getFirebaseHandler().getReference().addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
FirebaseHandler.getFirebaseHandler().setData(dataSnapshot);
DataSnapshot userSnapshot = dataSnapshot.child("Users").child(FirebaseHandler.getFirebaseHandler().getAuth().getUid());
User.initializeCurrentUser(userSnapshot);
//Add side bar to this activity
navigationManager = new NavigationManager(context);
navigationManager.createNavBar();
//Recycler view setup
RecyclerManager recyclerManager = new RecyclerManager();
recyclerManager.createRecyclerWithLargeElements(context, Voluntariat.getDataSet());
//Sort spinner setup
SortSpinnerManager sortSpinnerManager = new SortSpinnerManager();
sortSpinnerManager.createSortSpinnerManager(context, recyclerManager);
//Search bar setup
SearchBarManager searchBarManager = new SearchBarManager();
searchBarManager.createSearchBar(context, recyclerManager, Voluntariat.getDataSet());
TextView textViewHeader = findViewById(R.id.nav_header_textView);
Log.d("textHeader", textViewHeader.getText().toString());
textViewHeader.setText(User.currentUser.lastName + " " + User.currentUser.firstName);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
But this is from any other Activity in the onCreate method
RecyclerManager recyclerManager;
NavigationManager navigationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_toate_vol);
//Add side bar to this activity
navigationManager = new NavigationManager(this);
navigationManager.createNavBar();
//RECYCLERVIEW SETUP
recyclerManager = new RecyclerManager();
recyclerManager.createRecyclerWithSmallElements(this, Voluntariat.getDataSet());
//Search bar managing
SearchBarManager searchBarManager = new SearchBarManager();
searchBarManager.createSearchBar(this, recyclerManager, Voluntariat.getDataSet());
TextView textViewHeader = findViewById(R.id.nav_header_textView);
Log.d("textHeader", textViewHeader.getText().toString());
textViewHeader.setText(User.currentUser.lastName + " " + User.currentUser.firstName);
}
When I access any activity other than the MainActivity I get NullPointerException on the textViewHeader.
EDIT: I added more code and i changed it so the findViewById is called straight from the Activity file rather than from the NavigationManager file. The error is the same.
EDIT2: Added some more code from activity_toate_vol.xml:
It seems like this layout doesn't have any view with the problematic id, but the id is located in the nav_header_main.xml file which is set in the activity_toate_vol.xml file with the headerLayout attribute:
app:headerLayout="#layout/nav_header_main"
This NavigationView is a direct child of the root layout and the rest of the code is irrelevant, This same navigation view is found in the MainActivity as well.
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:visibility="visible"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="bottom"
android:gravity="bottom"
android:orientation="vertical"
android:padding="16dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:gravity="bottom"
android:orientation="horizontal">
<ImageView
android:id="#+id/imgdeconctare"
android:layout_width="27dp"
android:layout_height="27dp"
android:alpha=".6"
android:src="#drawable/ic_logout"
app:srcCompat="#drawable/ic_logout"
tools:srcCompat="#drawable/ic_logout" />
<TextView
android:id="#+id/logout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="20dp"
android:gravity="center|start"
android:text="Deconectare"
android:textColor="#android:color/black" />
</LinearLayout>
</LinearLayout>
</android.support.design.widget.NavigationView>
EDIT 3: I came out with a workaround and also identified the problem. Turns out I have to somehow wait for that NavigationView to inflate before I update it's text. Can anyone help me with the proper way to do this? Cause I am not happy with this.
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
try {
wait(150);
}
catch(Exception e){
}
TextView textViewHeader = findViewById(R.id.nav_header_textView);
Log.d("textHeader", textViewHeader.getText().toString());
textViewHeader.setText(User.currentUser.lastName + " " + User.currentUser.firstName);
}
}, 100);
Welcome! When findViewById returns null, that can mean 2 things.
1) The layout that you pass to 'setContentView' does not have a view with that id...
2) The layout does have that view, but the view itself is not fully inflated yet. To wait until a view is fully inflated, you can use a GlobalLayoutListener
in java:
setContentView(R.layout.activity_other);
final NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
TextView text = navigationView.findViewById(R.id.nav_header_textView);
text.setText("Hello StackOverflow");
navigationView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
});
and when you switch to kotlin:
setContentView(R.layout.activity_main)
val view = findViewById<NavigationView>(R.id.nav_view)
view?.viewTreeObserver?.addOnGlobalLayoutListener(object: ViewTreeObserver.OnGlobalLayoutListener{
override fun onGlobalLayout() {
val header = findViewById<TextView>(R.id.nav_header_textView)
header.text= "Hallo Main"
view.viewTreeObserver.removeOnGlobalLayoutListener(this)
}
})
Coming from VB world I learned today that dialogs are not modal in Java. I have the task of converting a program we have written in VB.net for windows based Motorola devices to Java using Android Studio for Android Motorola devices.
I am trying to make it as similar to forms in windows.
I am at a form that has that has several messageboxes that prompt for input.
I tried doing java but noticed that dialogs don't always wait for response.
I have read that using dialogfragments can accomplish what I am trying to do.
Here is the XML that I had for the first dialog.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorBackgroundGray"
>
<TextView
android:id="#+id/theText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="Holding Text"
android:textAlignment="center"
android:textColor="#color/colorBlack"
android:textSize="30dp" />
<Button
android:id="#+id/buttonYes"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_alignParentBottom="true"
android:layout_below="#id/message"
android:layout_margin="8dp"
android:onClick="onClickYes"
android:text="Yes"
android:textSize="26dp" />
<Button
android:id="#+id/buttonNo"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_below="#id/message"
android:layout_margin="8dp"
android:onClick="onClickNo"
android:text="No"
android:textSize="26dp" />
</RelativeLayout>
Here is how I was calling the dialog.
final Dialog dialog = new Dialog(ReturnAreaActivity.this, android.R.style.Theme_Black_NoTitleBar_Fullscreen);
dialog.setContentView(R.layout.dialog_location);
dialog.setTitle("New Location Setup");
TextView message = (TextView) dialog.findViewById(R.id.theText);
message.setText("Is this location a Pick Bin");
Button buttonYes = (Button) dialog.findViewById(R.id.buttonYes);
Button buttonNo = (Button) dialog.findViewById(R.id.buttonNo);
dialog.show();
Having question on what changes would need to be done to turn the dialog into a dialogFragment. I appreciate and clarity anyone can shed. Also the calling of the dialogFragments would be done during a loop
Thanks
First extend DialogFragment and use AlertDialog.Builder to create the dialog inside method onCreateDialog.
public class MyDialogFragment extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
LayoutInflater inflater = getActivity().getLayoutInflater();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(inflater.inflate(R.layout.dialog_location, null))
.setMessage("Is this location a Pick Bin")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Handle "yes" button click here.
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Handle "no" button click here.
}
});
return builder.create();
}
}
Then you can show DialogFragment by using show() method:
DialogFragment newFragment = new MyDialogFragment();
newFragment.show(getSupportFragmentManager(), "MyDialogFragment")
Small advise - don't use dp in your widget textSize, use sp. You can read the explanation here.
Before any of you tell me that this has been answered many times before, let me clarify most of those who've asked this question either gave the wrong view id or set a different ContentView than where the TextView was located. I have already used this function in a different where it worked fine. I've tried using a string literal in the TextView.setText(), but it was futile.
contactstory.xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textyman"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_marginTop="100dp"
android:text="TextView" />
<Button
android:id="#+id/close"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Close" />
</LinearLayout>
Function in java file
public void ShowStory(int pos)
{
final Dialog dialog = new Dialog(this);
dialog.setTitle(srcnames[pos]);
dialog.setContentView(R.layout.contactstory);
String username=getIntent().getStringExtra("username");
LoginDataBaseAdapter loginDataBaseAdapter=new
LoginDataBaseAdapter(this);
loginDataBaseAdapter.open();
String story=loginDataBaseAdapter.GetStory(pos,username);
TextView t1=(TextView)findViewById(R.id.textyman);
Button btnend=(Button)findViewById(R.id.close);
if(TextUtils.isEmpty(story)){
t1.setText(username+" hasn't added any story for this song");
}
else {
t1.setText(story); //Exception is thrown here
}
btnend.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
Logcat
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.sherry.escuchame.ContactInfo.ShowStory(ContactInfo.java:157)
at
com.example.sherry.escuchame.ContactInfo.onContextItemSelected
(ContactInfo.java:140)
at android.app.Activity.onMenuItemSelected(Activity.java:2660)
at android.support.v4.app.FragmentActivity.onMenuItemSelected
(FragmentActivity.java:408)
at
android.support.v7.app.AppCompatActivity.onMenuItemSelected
(AppCompatActivity.java:195)
at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected
(WindowCallbackWrapper.java:113)
Don't set pass layout id directly like R.layout.contactstory instead use layout inflater to inflate layout like below code
View view = LayoutInflater.from(context).inflate(R.layout.contactstory,null);
dialog.setContentView(view);
TextView t1=(TextView)view.findViewById(R.id.textyman);
Hi I'm new to Android Programming and I'm trying to make a simple program that changes the text by clicking a button. Here's my code:
public class HelloAndroidActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button button_scan = (Button) findViewById(R.id.button_scan);
button_scan.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
buttonBeenPressed();
}
});
}
public void buttonBeenPressed(){
final Button button_scan = (Button) findViewById(R.id.button_scan);
TextView tv_barcode = (TextView)findViewById(R.id.textview_barcode);
if (tv_barcode != null){
tv_barcode.setText("been pressed.");
} else {
button_scan.setText("it's null dawg.");
}
}
}
And my XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button android:text="Scan" android:layout_height="wrap_content" android:layout_width="match_parent" android:id="#+id/button_scan"></Button>
<TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="TextView" android:textAppearance="?android:attr/textAppearanceLarge" android:id="#+id/textview_barcode"></TextView>
</LinearLayout>
However the TextView is returning NULL and i don't know why. Any suggestions? Thanks.
Hmmm i got no problems with your code, runs without any error! Are you working with eclipse? Then try to clean your project.
Looks all correct to me....
Your best bet to debug this may be to run your app on the emulator or a phone and run hierarchyviewer, find your TextView and check the id.
You can use textview or a button. Here is an example with a textview I've found from http://www.ahotbrew.com/android-textview-example/
<TextView
android:text="#string/textview_onclick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textview_onclick"
android:layout_below="#+id/textview_center"
android:textSize="25dp"
android:onClick="changeTextColor"
android:clickable="true"/>
In your MainActivity do this
public void changeTextColor (View view)
{
TextView textView = (TextView) view.findViewById(R.id.textview_onclick);
textView.setText("newWord");
}