How to set the value of TextView in Custom Dialog in Android - java

I want to set the value of TextView in custom dialog box after I clicked in one of the fragments in Activity. Dialog was running fine with custom text view after it is being called. The problem is that it always shows NullPointerException when I tried to call changeMessageText("Hello") function.
ProgressDialogFragment.java
public class ProgressDialogFragment extends DialogFragment {
private TextView txtMessage;
private AlertDialog.Builder mBuilder;
public static ProgressDialogFragment newInstance(AlertDialog.Builder builder){
ProgressDialogFragment progressDialogFragment = new ProgressDialogFragment();
progressDialogFragment.mBuilder = builder;
return progressDialogFragment;
}
#Nullable
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
View view = getLayoutInflater(savedInstanceState).inflate(R.layout.dialog_progress, null);
txtMessage = (TextView) view.findViewById(R.id.txtMessage);
changeMessageText("Hello World by default"); // this one works
mBuilder.setView(view);
return mBuilder.create();
}
public void changeMessageText(String text){
txtMessage.setText(text);
}
}
Sample Code after the button Clicked
AlertDialog.Builder builder = new AlertDialog.Builder(this);
ProgressDialogFragment progressDialogFragment = ProgressDialogFragment.newInstance(builder);
progressDialogFragment.show(getSupportFragmentManager(),"progress_dialog");
// dialog box shows until the following function is called.
progressDialogFragment.changeMessageText("Hello");

When progressDialogFragment.changeMessageText("Hello"); called, txtMessage is not created yet.
1) Add private String message; to ProgressDialogFragment.
2) Change changeMessageText
public void changeMessageText(String text){
message = text;
if(txtMessage != null){
txtMessage.setText(text);
}
}
3) add after mBuilder.setView(view);
if(message!=null && !message.isEmpty()){
txtMessage.setText(message);
}
4) Remove changeMessageText("Hello World by default"); in onCreateDialog
And. It Doesn't Work for Me.
View view = getLayoutInflater(savedInstanceState).inflate(R.layout.dialog_progress, null);
I change it.
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.dialog_progress, null);
Hope it will help you.

Related

How do I connect a button to a Dialog that will edit a TextView, within a FrameLayout, with a users input?

I don't understand DialogFragment at all. How to create one, how to get the user input out of it, and set it into a TextView.
I would like for the TITLE button, when clicked, to bring up a DialogFragment asking the user to enter the title of their Mood Board. The user enters a title. When they click the PostiveButton "Done", the user's title is set into the top left frame of the mood board, which has a TextView with a hint.
Please! Ask questions, because I don't really understand the dialog setup.
Here is a picture of my main_layout, in my MainActivity. Every element has an "#+id/".
The solution you are looking for is a callback:
Create an interface with a method to use as a callback
Implements the interface on the activity
Create the dialog fragment and in onAttach get the interface
Show the dialog fragment on the activity
On dismiss the dialog fragment pass the text using the instance of the interface
interface Callback {
updateText(String text)
}
class CoolActivity... implements Callback
onCreate {
//find your views
showDialogBtn.setOnClickListener(...
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
Fragment prev = getSupportFragmentManager().findFragmentByTag("yourTag");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
DialogFragment dialogFragment = ExampleDialogFragment.newInstance();
dialogFragment.show(ft, "yourTag");
)
}
#Override
updateText(String text) {
youtView.setText(text)
}
class CoolDialogFragment extend DialogFragment {
private Callback callback;
#Override
void onAttach(Context context) {
callback = (Callback) context
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = new Dialog(getActivity());
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
return dialog;
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.dialog_fragment_example, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//find the views in the dialog fragment
closeBtn.clickListener(...
callback.updateText(edittext.getText().toString())
dismiss()
)
}
}
Here is a gist of a dialog fragment
https://gist.github.com/cutiko/7e307efcf7492ea52ef05cd90f9e3203
The problem is you want to connect a dialog fragment with a another component, and you want to do it straigth forward. This is not considered a good practice because yiu create 2 componentes higly attached, so the best would be to use data persistence and some form of react programming
You can make your mood board title textview static then call it to the alertdialog with edittext to set it text (setText)
like this.
final EditText edittext = new EditText(MainActivity.this);
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("Input Title")
.setView(edittext)
.setCancelable(false)
.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
YourCustomDialog.your_title_textviewMoodboard.setText(edittext.getText().toString());
}
})
.setNegativeButton("Back", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
in your custom dialog. declare your textview static globally
public static TextView your_title_textviewMoodboard;

How can I settext for TextView from another class?

I have an alert Dialog and I use a custom layout for this Alert Dialog, in this custom layout I have a TextView, so how can I set text for this TextView from MainActivity class?
Here is my code :
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var btn_ShowAlert =findViewById<Button>(R.id.Button)
btn_ShowAlert.setOnClickListener {
txtlyric.text ="this Textview is all the problem xD "
val dialog = AlertDialog.Builder(this)
val dialogView = layoutInflater.inflate(R.layout.lyric,null)
dialog.setView(dialogView)
dialog.setCancelable(true)
dialog.show()
}
}
Initialize the widget as in your custom Dialog like this before findViewById:
txtlyric = (TextView) dialog.findViewById(R.id.yourtextviewindialog);
Then you'll be able to setText or your stuff in your custom dialog widgets.
P.s: Note that i used dialog since it's your Dialog view.
I would propose to use DialogFragment and pass necessary value into constructor
public class MyAlertDialogFragment extends DialogFragment {
public static final String TITLE = "dataKey";
public static MyAlertDialogFragment newInstance(String dataToShow) {
MyAlertDialogFragment frag = new MyAlertDialogFragment();
Bundle args = new Bundle();
args.putString(TITLE, dataToShow);
frag.setArguments(args);
return frag;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
String mDataRecieved = getArguments().getString(TITLE,"defaultTitle");
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.alert_layout, null);
TextView mTextView = (TextView) view.findViewById(R.id.textview);
mTextView.setText(mDataRecieved);
setCancelable(false);
builder.setView(view);
Dialog dialog = builder.create();
dialog.getWindow().setBackgroundDrawable(
new ColorDrawable(Color.TRANSPARENT));
return dialog;
}
}
For more details please check here

DialogFragment's inflated view being reused in next instance

I have a dialog fragment with a custom view. The background color of the custom view also changes depending on the passed argument from newInstance() method. To make certain that it's really a different DialogFragment instance, I also passed another argument to the newInstance() method, the dialog title. The background color can also accept a null value, in which case, no background color is set.
Now here is the problem: when I show the dialog fragment with the null value passed for the background color the second time, the inflated view still has the background color of the last shown dialog fragment even though the title is already different. Why is the system reusing the last inflated view? Shouldn't the background color be empty? What am I not understanding properly?
MyDialogFragment.java
public static MyDialogFragment newInstance(String title, Integer bgColor) {
MyDialogFragment df = new MyDialogFragment();
Bundle args = new Bundle();
args.putString(TITLE_ARG, title);
args.putSerializable(BG_ARG, bgColor);
df.setArguments(args);
return df;
}
...
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Bundle args = getArguments();
Integer bgColor = (Integer) args.getSerializable(BG_ARG);
View view = getActivity().getLayoutInflater().inflate(R.layout.my_dialog_fragment, null);
// check if null was passed
if(bgColor != null)
((GradientDrawable) view.getBackground()).setColor(bgColor);
return new AlertDialog.Builder(getActivity())
.setTitle(args.getString(TITLE_ARG))
.setView(view)
.setNegativeButton(R.string.cancel, null)
.setPositiveButton(R.string.ok, null)
.create();
}
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fm = getSupportFragmentManager();
MyDialogFragment df = (MyDialogFragment) fm.findFragmentByTag(MyDialogFragment.TAG);
if(df == null) {
df = MyDialogFragment.newInstance("title1", Color.GREEN);
df.show(fm, MyDialogFragmentTAG);
}
}
});
findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fm = getSupportFragmentManager();
MyDialogFragment df = (MyDialogFragment) fm.findFragmentByTag(MyDialogFragment.TAG);
if(df == null) {
df = MyDialogFragment.newInstance("title2", null);
df.show(fm, MyDialogFragmentTAG);
}
}
});
}
The first click of button1 will create dialog and attach it to the FragmentManager.
The click of button2 (second click) will find your old fragment, so df should not be null, and you should not see any dialog.
Maybe your snippet of code is incomplete.

android keep dialogbox open until user click on button [duplicate]

i am having an custom alert view which pop ups on a button click event.all the things are going fine.but the problem is:
if user clicks outside alert dialog it disappear.i want to restrict user for clicking out side.I am giving him the choice of cancel/cross button to close alert dialog.
so how to restrict user clicking outside the alert box?
code:
the code in onCreate for button click where i am calling show dialog:
final Button cdButton = (Button) findViewById(R.id.denonCdImage);
cdButton.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v)
{
showDialog(CD_CATG_ID);
}
});
protected Dialog onCreateDialog(int id) {
AlertDialog.Builder builder;
Context mContext = this;
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.categorydialog,(ViewGroup) findViewById(R.id.layout_root));
GridView gridview = (GridView)layout.findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this));
/** Check the id for the device type for image tobe change */
switch(id) {
case 1 : // for the cd image
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,final int position, long id) {
Toast.makeText(view.getContext(), "Image selected for CD", 3000).show();
cdImageId = getImageId(position);
int elementId = getApplicationContext().getResources().getIdentifier(cdImageId, "drawable", getPackageName());
cdImageView.setImageResource(elementId);
Log.d("CdImageid", ""+cdImageId);
closeDialog(view);
}
});
builder = new AlertDialog.Builder(mContext);
builder.setView(layout);
dialog = builder.create();
break;
default:
dialog = null;
}
/** onclick listner for the close button */
ImageView close = (ImageView) layout.findViewById(R.id.close);
close.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
dialog.dismiss();
}
});
return dialog;
}
any suggestions?
thanks!
There are two methods concerning this behaviour: setCancelable() and setCanceledOnTouchOutside() as you can see in the reference.

Custom Dialog Execution NPE

I keep my alerts and dialog's in a seperate class to prevent clutter. In my activity, I have a webView and the HTML document has a button that executes a custom dialog in Android. I'm using the JavaScriptInterface to communicate between the JavaScript functions in the HTML Documents and Android Java methods. This all works fine with my toast messages and other functions between each other except for this custom dialog.
UPDATE:
I did some changes and now at least I get a NPE that I cant follow. I moved the Dialog method to the JavaInterface to make it easier to debug and a few other chages; see comments in the code.
I don't know what I have wrong. I get no error info in LogCat with this one; just force closes the app...?? Plz look thru my code below.
Thnx for your help!!
LogCat:
Miss a drag as we are waiting for WebCore's response for touch down.
threadid=9: thread exiting with uncaught exception (group=0x4024ee20)
FATAL EXCEPTION: WebViewCoreThread java.lang.NullPointerException
at android.app.Activity.findViewById(Activity.java:1745) at
com.andaero.JavaScriptInterface.onCreateDialog(JavaScriptInterface.java:45)
at android.app.Activity.onCreateDialog(Activity.java:2758) at
android.app.Activity.createDialog(Activity.java:936) at
android.app.Activity.showDialog(Activity.java:2851) at
android.app.Activity.showDialog(Activity.java:2810) at
com.andaero.JavaScriptInterface.showDashBoard(JavaScriptInterface.java:32)
at android.webkit.WebViewCore.nativeTouchUp(Native Method) at
android.webkit.WebViewCore.nativeTouchUp(Native Method) at
android.webkit.WebViewCore.access$3600(WebViewCore.java:52) at
android.webkit.WebViewCore$EventHub$1.handleMessage(WebViewCore.java:1340)
at android.os.Handler.dispatchMessage(Handler.java:99) at
android.os.Looper.loop(Looper.java:132) at
android.webkit.WebViewCore$WebCoreThread.run(WebViewCore.java:723)
at java.lang.Thread.run(Thread.java:1020)
Alerts And Dialogs Class:
public class AlertsAndDialogs extends Activity
{
public final int CATEGORY_ID = 0;
. . .
//Moved to the JavaScriptInterface Class ----->
/* protected Dialog onCreateDialog(int id)
{
Dialog dialog;
switch (id)
{
case CATEGORY_ID:
AlertDialog.Builder builder;
Context mContext = this;
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.dashboard_dialog, (ViewGroup) findViewById(R.id.webView));
builder = new AlertDialog.Builder(mContext);
builder.setView(layout);
dialog = builder.create();
break;
default:
dialog = null;
}
return dialog;
}*/
}
The JavaScriptInterface Class:
public class JavaScriptInterface extends AlertsAndDialogs
{
public final int CATEGORY_ID = 0;
Context mContext;
/** Instantiate the interface and set the context */
JavaScriptInterface(Context c)
{
mContext = c;
}
. . .
/** Show the DashBoard from the web page */
public void showDashBoard()
{
showDialog(CATEGORY_ID);
}
protected Dialog onCreateDialog(int id)
{
Dialog dialog;
switch (id)
{
case CATEGORY_ID:
AlertDialog.Builder builder;
//Context mContext = this;
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.dashboard_dialog, (ViewGroup) findViewById(R.id.layout_root));
builder = new AlertDialog.Builder(mContext);
builder.setView(layout);
dialog = builder.create();
break;
default:
dialog = null;
}
return dialog;
}
. . .
}
In the Main Activity containing the WebView:
. . .
myWebView.addJavascriptInterface(new JavaScriptInterface(this), "Android");
. . .
The HTML Function:
<script type="text/javascript">
function showDashBoardFunction() {
Android.showDashBoard();
}
</script>
Try setting
View layout = inflater.inflate(R.layout.dashboard_dialog, (ViewGroup) findViewById(R.id.layout_root));
to
View layout = inflater.inflate(R.layout.dashboard_dialog, null);
I find that attaching views to a container rarely (if ever) works, and assuming "layout_root" is something to do with your activity, the Dialog won't be able to find this view anyway.
Remove from the AlertsAndDialogs Class:
protected Dialog onCreateDialog(int id)
{
Dialog dialog;
switch (id)
{
case CATEGORY_ID:
AlertDialog.Builder builder;
Context mContext = this;
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.dashboard_dialog, (ViewGroup) findViewById(R.id.webView));
builder = new AlertDialog.Builder(mContext);
builder.setView(layout);
dialog = builder.create();
break;
default:
dialog = null;
}
return dialog;
}
and add this:
public static void dashBoard(Context mContext)
{
AlertDialog.Builder builder;
Dialog dbDialog;
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.dashboard_dialog, null);
builder = new AlertDialog.Builder(mContext);
builder.setView(layout);
dbDialog = builder.create();
dbDialog.show();
}
Inside the JavaScriptInterface Class, Replace the call with:
public void showDashBoard()
{
AlertsAndDialogs.dashBoard(mContext);
}

Categories