i am new to developing apps for android and i want to create a simple Conterter app, just for the start. In my view i have a edittext and a Button. If i click the button, it will open a AlertDialog with list of strings. I cant figure out how to manage this: When i click on one item in the AlertView i want to set the text of the button to the selected string and dismiss the AlertDialog. Can somebody please help me ?
public class VypocetDlzkyActivity extends Activity {
EditText HodnotaDlzka;
Button prevodDlzkaZtlacidlo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vypocet_dlzky);
}
public void zmenPrevodZ(View view){
final String[] jednotkyDlzky = {"milimeter", "centimeter", "decimeter", "meter", "kilometer", "svetelny rok"};
AlertDialog.Builder builder = new AlertDialog.Builder(VypocetDlzkyActivity.this);
builder.setTitle("Vyberte jednotku");
builder.setItems(jednotkyDlzky,null);
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
String value = jednotkyDlzky[item].toString();
prevodDlzkaZtlacidlo.setText(value);
dialog.cancel();
}
};
final AlertDialog alert = builder.create();
alert.show();
}
You need to set the values of these 2 member variables in your onCreate() method, like this:
HodnotaDlzka = (EditText)findViewById(R.id.xxxx);
prevodDlzkaZtlacidlo = (Button)findViewById(R.id.yyyy);
xxxx is the ID you gave the EditText in activity_vypocet_dlzky.xml and yyyy is the ID you gave to the Button.
Also, after a button is clicked in the AlertDialog, the dialog is automatically dismissed, so you don't need to call dialog.cancel().
Problem is you didnt add any onClick listnerz.On clicking on button you need to call the required method.
public class MainActivity extends Activity implements OnClickListener {
EditText HodnotaDlzka;
Button prevodDlzkaZtlacidlo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
HodnotaDlzka = (EditText) findViewById(R.id.e1);
prevodDlzkaZtlacidlo = (Button) findViewById(R.id.b1);
prevodDlzkaZtlacidlo.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
final String[] jednotkyDlzky = {"milimeter", "centimeter", "decimeter", "meter", "kilometer", "svetelny rok"};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Vyberte jednotku");
builder.setItems(jednotkyDlzky,new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
String value = jednotkyDlzky[item].toString();
prevodDlzkaZtlacidlo.setText(value);
}
});
enter code here
final AlertDialog alert = builder.create();
alert.show();
}
}
Related
I have this button to show a dialog which in turn has an EditText for the users to write something and then tap the done button to save it otherwise another button to close the dialog. The problem here is that I am not able to fetch that String that the user wrote. It returns me a null sting instead and causes the app to crash. Here's the code :
I call the dialog up on clicking on a button:
//Write Review Dialog Box
writeReviewBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("HAPPENED", "This Onclick is working");
try{
// Create custom dialog object
final Dialog dialog = new Dialog(GetReviewActivity.this);
// Include dialog's xml file
dialog.setContentView(R.layout.write_review_activity);
// Set dialog title
dialog.setTitle("Your review is valuable");
final EditText etWR = (EditText)findViewById(R.id.etWR);
Button writeButton = (Button) dialog.findViewById(R.id.buttonWR);
Button declineButton = (Button) dialog.findViewById(R.id.buttonNoThanks);
dialog.show();
//Done Button
writeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("HAPPENED: ","writeButton Block Is WORKING!");
Activity activity = GetReviewActivity.this;
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
String Review = etWR.getText().toString();
StoreAReview(Review);
}
});
}
});
// if decline button is clicked, close the custom dialog
declineButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Close dialog
dialog.dismiss();
}
});
}catch (Exception e){
e.printStackTrace();
}
}
});
final EditText etWR = (EditText)findViewById(R.id.etWR); is resolving to Activity#findViewById. But your dialog's layout is not attached to your activity window, it's attached to the dialog. so you have to inflate EditText from your dialog's view:
Try
final EditText etWR = (EditText)dialog.findViewById(R.id.etWR);
instead of
final EditText etWR = (EditText)findViewById(R.id.etWR);
Been through this issue before. I tried initiating EditText with Dialog reference but this didn't work
final EditText etWR = (EditText)dialog.findViewById(R.id.etWR);
Solution:
This is how I solved it:
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
View dialogWR = getActivity().getLayoutInflater().inflate(R.layout.write_review_activity, null);
etWR = (EditText) dialogWR.findViewById(R.id.etWR);
}
You should initialize EditText
EditText etWR = (EditText)dailog.findViewById(R.id.etWR);
becoz your EditText is coming from dailog. So
U just miss the dialog.findViewById(R.id.etWR)
change this line
final EditText etWR = (EditText)findViewById(R.id.etWR);
to this one
final EditText etWR = (EditText)dialog.findViewById(R.id.etWR);
then, add click event code
i have an activity that when user click on button , a dialog open. in this dialog there is a spinner that have 3 choices: Blue,Red,Green. and there is a submit button. i want that when user select a color and click on submit, in caller activity, its String color set to selected color in dialog. i try this: but not worked. please help me....
String color;
String dialogColor;
showDialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.custom_dialog);
dialog.setTitle("my dialog");
Spinner spinner = (Spinner) dialog.findViewById(R.id.spinner);
final TextView status = (TextView) dialog.findViewById(R.id.status);
Button submit = (Button) dialog.findViewById(R.id.submit);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
dialogColor = parent.getItemAtPosition(position).toString();
status.setText("Color is: "+dialogColor);
color = dialogColor;
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("Color",dialogColor);
dialog.dismiss();
}
});
dialog.show();
}
});
i use both of direct and with intent ways to assign my color String to selected value. but not worked. where i have mistake?
I think the best way to create custom dialogs now is the Dialog Fragment, because the simple dialog it's limited. For example it's the way to create a dialogs with material design. And you have a differents ways to take info from dialog fragment, the first and the second for example.
This is basic code to create a dialog fragment:
//Method to call and start dialog fragment class
public void ShowPhotoFilesDialog(Activity context,File photo){
//Declaration of classes
Custom_DialogFragment custom_dialogFragment = new Custom_DialogFragment ();
FragmentManager fragmentManager = context.getFragmentManager();
// The device is using a large layout, so show the fragment as a dialog
custom_dialogFragment.show(fragmentManager, "dialog");
}
And this is the basic dialog fragment class:
public class Custom_DialogFragment extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
try {
// The only reason you might override this method when using onCreateView() is
// to modify any dialog characteristics. For example, the dialog includes a
// title by default, but your custom layout might not need it. So here you can
// remove the dialog title, but you must call the superclass to get the Dialog.
Dialog dialog = super.onCreateDialog(savedInstanceState);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
//To hide action bar from layout
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
//Declaration of controls
View v = getActivity().getLayoutInflater().inflate(R.layout.my_custom_layout);
builder.setView(v);
//My code
return builder.create();
}
catch (Exception ex){
Log.e("-- Custom_DialogFragment.onCreateDialog --","",ex);
return null;
}
}
}
Tell me if I helped you, good programming!
in my MainActivity i have a method showPopUp that is called by a button's listener. So MainActivity's layout only contain a button.
ShowPopUp method reads button states and returns null pointer expception.
activity_toggle is my layout that contains toggleButton.
following is my mainactivity code snippet.
public class MainActivity extends ActionBarActivity {
ToggleButton toggleButton;
String i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showAlertDialog(MainActivity.this);
}
public void showAlertDialog(final Context context){
AlertDialog.Builder ab = new AlertDialog.Builder(context);
View v = LayoutInflater.from(context).inflate(R.layout.activity_toggle,null);
ab.setView(v);
ab.setTitle("toggle mera dil toggle meri jaan");
toggleButton = (ToggleButton)findViewById(R.id.toggleButton1);
toggleButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(toggleButton.isChecked()){
i+=i;
Toast.makeText(MainActivity.this,"Button is on "+i,Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(MainActivity.this,"Button is off mode",Toast.LENGTH_SHORT).show();
}
}
});
ab.setPositiveButton("Ok",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this,"ok button pressed",Toast.LENGTH_SHORT).show();
boolean tButton = toggleButton.isChecked();
if(tButton){
Toast.makeText(MainActivity.this,"Button is off on a ",Toast.LENGTH_SHORT).show();
}
dialog.dismiss();
}
});
ab.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
ab.create().show();
}
}
Try below code. You have to give reference of View when you find view from inflater view.
toggleButton = (ToggleButton)v.findViewById(R.id.toggleButton1);
View v = LayoutInflater.from(context).inflate(R.layout.activity_toggle,null);
ab.setView(v);
ab.setTitle("toggle mera dil toggle meri jaan");
toggleButton = (ToggleButton)v.findViewById(R.id.toggleButton1);
Use v View object which passing in setView method of AlertDialog for accessing ToggleButton from Dialog layout:
toggleButton = (ToggleButton)v.findViewById(R.id.toggleButton1);
toggleButton = (ToggleButton)findViewById(R.id.toggleButton1);
This line find view in your activity but this R.id.toggleButton1 control is defined in activity_toggle.xml layout which is used in dialog.
Try the
toggleButton = (ToggleButton)v.findViewById(R.id.toggleButton1);
after doing a lot of research and trying (i think) every lifecycle method i could find, i´m really stuck:
What i want: Basically i have this DialogFragment ("ProfileUsernameDialogFragment")which should present my layout file ("fragment_profile_header_username_dialog").
in this layout file i have some TextViews and some EditTexts. I want to set the text of these EditTexts to some value i obtain in my programm, so setting it beforehand is not possible.
What i have:
public class ProfileUsernameDialogFragment extends DialogFragment {
...
#Override
public void onActivityCreated(Bundle savedInstanceState) {
EditText usernameText = (EditText) this.getView().findViewById(R.id.username_field);
usernameText.setText("TEST");
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Log.d(AppController.LOG_STRING, this.getClass().toString() + " - onCreateDialog - START");
AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());
View view = this.getActivity().getLayoutInflater().inflate(R.layout.fragment_profile_header_username_dialog, null);
builder.setView(view);
builder.setPositiveButton(SAVE_SETTINGS, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int whichButton) {
// Tried this too:
// EditText usernameText = (EditText)
// ProfileUsernameDialogFragment.this.getView().findViewById(R.id.forename_label);
// usernameText.setText("TEST");
}
});
builder.setNegativeButton(ABORT_ACTION, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
builder.setTitle(CHANGE_NAME_SETTINGS);
Dialog dialog = builder.create();
return dialog;
}
}
What i get: is a NullPointerException, no matter which position for the findViewById(R.id.username_field) i tried.
(I also tried onCreate and some other methods, i start thinking i might have another problem than the code location, but i really hav no clue) I tried to follow at least 6 similar questions about NullPointers in DialogFragments so i guess i need advanced help ^^
i should add i´m completely new to android so please be nice, but convention tipps etc. are very welcome! thx in advance :)
Following is what you need:
mAlertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(final DialogInterface dialog) {
final Button b = mAlertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
v.findViewById(R.id...)
}
});
}
});
});
}
});
Another option in addition to #David's answer is to use the onStart() method.
It looks like you were thinking along these lines in your question, except you used the onActivityCreated() method.
So for example:
#Override
public void onStart()
{
super.onStart();
EditText usernameText = (EditText) this.getDialog().findViewById(R.id.username_field);
usernameText.setText("TEST");
}
Android documentation has good example
So, if You wont set text in Your layout You need set it in onCreateView() method, for example:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup cont,
Bundle savedInstanceState) {
// Inflate the layout to use as dialog or embedded fragment
View view = inflater.inflate(R.layout.app_info, cont, false);
TextView title = (TextView)view.findViewById(R.id.dialog_header);
TextView content = (TextView)view.findViewById(R.id.dialog_content);
Button button = (Button)view.findViewById(R.id.dialog_button);
title.setText(this.dialogTitle);
content.setText(this.dialogContent);
button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
getDialog().dismiss();
}
});
return view;
}
Hi I'm an android newbie and I've been stuck for a week on this. Any help would be appreciated! I've done a lot of research and can't figure out what is wrong. I've successfully run the bluetoothchat sample code on two phones and successfully communicated via bluetooth. I've also successfully written and run a standalone app that, after a button click on the main activity, opens a custom alertdialog which accepts user input, and passes the input back to the main activity. But when I write the alertdialog code into the BluetoothChat code, nothing happens when I click the button. I've tried to step through the debugger with the phone but with no luck. It doesn't seem to step to the code containing the button click. There are no errors showing. Why won't the alertdialog pop up on button click? Here's the BluetoothChat.java code I've modified :
public class BluetoothChat extends Activity implements OnClickListener{
final Context context = this;
private Button rButton;
View rScreen;
private EditText mAlertDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(D) Log.e(TAG, "+++ ON CREATE +++");
// Set up the window layout
setContentView(R.layout.main);
// Get local Bluetooth adapter
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// If the adapter is null, then Bluetooth is not supported
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
return;
}
//components from main.xml
//When button is clicked, the alert dialog is pulled up
rButton = (Button)findViewById(R.id.buttonr);
mAlertDialog = (EditText)findViewById(R.id.edittextresultm);
//add button listener
rButton.setOnClickListener(new OnClickListener() {
//#Override
public void onClick_register(View view) {
String title = "title";
String buttonOk = "OK";
String buttonCancel = "Cancel";
String madd, name;
//get review.xml view
LayoutInflater li = LayoutInflater.from(context);
View rView = li.inflate(R.layout.review, null);
//AlertDialog dialog;
AlertDialog.Builder adRegister = new AlertDialog.Builder(context);
//set review.xml to adRegister builder
adRegister.setView(rView);
//set title
adRegister.setTitle(title);
//Set EditText views to get user input
final EditText mField = (EditText)rView.findViewById(R.id.editTextm);
final EditText nField = (EditText)rView.findViewById(R.id.editTextn);
//set dialog message
adRegister.setMessage("Message")
.setCancelable(false)
.setPositiveButton(buttonOk, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String madd = mField.getText().toString();
String name = nField.getText().toString();
//get user input and set it to result on main activity
mAlertDialog.setText(mField.getText());
}
})
.setNegativeButton(buttonCancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
//if this button is clicked, close current activity
dialog.cancel();
}
});
//Create alert dialog
AlertDialog alertDialog = adRegister.create();
//dialog= adRegister.create();
//show it
adRegister.show();
//dialog.show();
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
});
}
}
Write your inputDialog code in OnClick Method.
Enjoy!!