I'm trying to make a popup box with edit text field on Android Studio and would like to store the data entered by the user in a variable used in that class.
Something like this:
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("New player")
.setMessage("Input new player's name")
.setView(input)
.setPositiveButton("Register", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
name = input.getText().toString(); //<---HERE !want to use this variable
}
})
.setNegativeButton("Cancel", null)
.show();
This doesn't work, so how could I extract the value of name from my popup window to use it in the main code?
Do it this way:
final String[] name = new String[1];
final EditText input = new EditText(this);
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("New player")
.setMessage("Input new player's name")
.setView(input)
.setPositiveButton("Register", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
name[0] = input.getText().toString(); <---HERE! want to use this variable
}
})
.setNegativeButton("Cancel", null)
.show();
Access it using name[0]
Clarification for the followup question by Jox in the comment below: To access the variable inside onClick it needs to be final. But, you cannot assign a value to a simple final variable. However, you can assign a value to a Array member. Hence, the array and not a string variable. Btw, Andriod Studio will do it for you this way itself, just follow the suggested fixes for erroring-out code.
You should declare the DialogInterface.OnCLickListener inside of your Activity. By either creating a listener and assingning it or having your activity implement the interface. And then you won't need to declare name as final.
The reason you have to declare name as final is because you're anonmously creating an object to listen to the click, which require a contract of anything external being used by this anonymous class must be declared as final.
I would recommend creating a listener in your Activity and then assign it to the setOnClickListener(x)
Try this, it works for me :
public class Activity extends AppCompatActivity implements DialogInterface.OnClickListener {
private EditText input;
private String str = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
input = new EditText(this);
}
public void onClickAlert(View v) {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("New player")
.setMessage("Input new player's name")
.setView(input)
.setPositiveButton("Register", this)
.setNegativeButton("Cancel", null)
.show();
//variable str still equal to "" here
}
#Override
public void onClick(DialogInterface dialog, int which) {
str = input.getText().toString(); /*<---HERE! want to use this variable*/
//use it here
Log.d("Activity", "User input : " + str);
}
}
Implement the OnClickListener in your Activity and read the value of the text field in the callback fonction.
Related
I'm having problems with my first app (learning android studio as i go), I'm trying to insert a Alert Dialog whenever the user clicks on the list item to make sure he wants to delete the item. However, I can't get it working, here's the code if you need more just ask for it. Oh I'm portugues btw, so don't get confused by the variables.
public class MainActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemClickListener {
private EditText tarefasET;
private Button btn;
private ListView tarefasList;
private ArrayList<String> tarefas;
private ArrayAdapter<String> adapt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tarefasET = findViewById(R.id.todoEditText);
btn = findViewById(R.id.addBtn);
tarefasList = findViewById(R.id.lvTarefas);
tarefas = FileHelper.lerData(this);
adapt = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, tarefas);
tarefasList.setAdapter(adapt);
btn.setOnClickListener(this);
tarefasList.setOnItemClickListener(this);
}
#Override
public void onClick(View view) {
switch(view.getId()){
case R.id.addBtn:
String newTarefa = tarefasET.getText().toString();
adapt.add(newTarefa);
tarefasET.setText("");
FileHelper.escreve(tarefas, this);
Toast.makeText(this, "Tarefa Adicionada", Toast.LENGTH_SHORT).show();
break;
}
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int posicao, long id) {
AlertDialog confirmDialog = new AlertDialog.Builder(this)
.setTitle("Confirmação")
.setMessage("De certeza que pretende eliminar a tarefa?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
tarefas.remove(posicao);
adapt.notifyDataSetChanged();
FileHelper.escreve(tarefas, this);
Toast.makeText(this, "Tarefa Eliminada", Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
}
What can i do? The app is suposed to be a to-do list, and i can already add and delete files. But i wanted to make a confirmation dialog when the user decides to delete the item he has to-do. But the code gives me the folowing error when i try and lauch the app to the emulator.
the error i'm getting
I suppose you are trying to reference your activity class via this variable. Use class name before this keyword to get outer reference:
FileHelper.escreve(tarefas, MainActivity.this);
Why the problem appears?
Because of the variable scope. The same rules apply to this keyword. Imagine it as a default final variable defined for you by the language.
In your particular case, this keyword references the instance of DialogInterface.OnClickListener you created. The same issue will appear in case any of the MainActivity class level variables names will clash with a variable name of method level variable defined in onClick:
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
ArrayList<String> tarefas = new ArrayList();
ArrayList<String> outerTarefas = MainActivity.this.tarefas; // not just tarefas or this.tarefas
}
}
Currently struggling to handle the user input from my AlertDialog box. Everything works fine, but I don't know what to do with the user input in order to save it and access it within another function.
private void promptUser() {
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
final EditText promptTitle = new EditText(this);
promptTitle.setHint("Title");
layout.addView(promptTitle);
userPrompt = new AlertDialog.Builder(this);
userPrompt.setView(layout);
userPrompt.setTitle("Enter map information").setView(layout);
userPrompt.setPositiveButton("Create", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Log.i("AlertDialog", "Create button was hit");
Log.i("AlertDialog", "This is the text that was entered:" + promptTitle.getText().toString());
userInputs = promptTitle.getText().toString();
}
});
userPrompt.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Log.i("AlertDialog", "Cancel button was hit");
}
});
userPrompt.show();
}
and where I call the function:
public void onMapClick( LatLng point ) {
promptUser()
//Log.d(userInputs.get(0), "COOL");
}
The main error I'm encountering is that after calling my method promptUser(), everything runs but the next several lines of code don't wait for the user to click the PositiveButton. e.g, my Log shows "User inputs: null", since tempString isn't yet available. How can I make my function wait until the user has hit submit before running the next line of code?
Put the call to onMapClick inside the positive button callback.
userPrompt.setPositiveButton("Create", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
userInputs = promptTitle.getText().toString();
onMapClick();
}
});
It's a bit hard to tell if this is exactly what you want since you haven't provided enough code, but this is what you asked for.
I want to build a function that creates an AlertDialog and returns the string that the user entered, this the function I have for creating the dialog, how do I return the value?
String m_Text = "";
private String openDialog(String title) {
AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
builder.setTitle(title);
final EditText input = new EditText(view.getContext());
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_NORMAL);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
m_Text = input.getText().toString();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
// return string
}
The call builder.show() which opens your AlertDialog is not a blocking call, meaning the next instructions will be executed without waiting for the AlertDialog to finish (return). The way you should interact with it is by using some sort of callback. For instance, your OnClickListeners are an implementation of such a pattern.
A simple callback pattern
One clean way to achieve what you want is to create a Functional Interface which is an interface having only one method. You would use it for handling your callbacks.
Example
interface OnOK{
void onTextEntered(String text);
}
And then you would alter you method to be like:
private void openDialog(String title, final OnOK onOK) {
AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
builder.setTitle(title);
final EditText input = new EditText(view.getContext());
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_NORMAL);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Oi, look at this line!
onOK.onTextEntered(input.getText().toString());
}
});
builder.show();
}
You can use it like this:
openDialog("Title", new OnOK() {
#Override
onTextEntered(String text) {
Log.i("LOG", text);
}
});
This looks to me like you have stored the value of the inputted text in the m_Text field. You can either just return that field or have a variable within the function in which you store the value to be returned.
Where you have:
//Return string
simply replacing with:
return m_Text;
should do the job.
Create another method in the same class that accepts a string value, then call that function providing the value of input.getText().toString() from your setPositiveButton onclick event
I have implemented a dialog box, I also get the text field as a string. Now the problem I have is that I want to compare the text input to a String and exit the app if the text on the dialog box matches either a string under (R.strings.stringname) or either a private String variable.
I have implemented this code but it does not seem to work.
public void onBackPressed(){
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setIcon(R.drawable.ic_about_logo);
alert.setTitle("Phoebus Club");
alert.setMessage("Please Insert Security Key");
// Set an EditText view to get user input
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Enter", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
securityKey = input.getText().toString();
if(securityKey == "oneplc"){
System.exit(0);
}
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
}
Have a look at this question
The == operator doesn't really compare values, rather reference equality. You should use the equals() method of the String object instead:
if(securityKey.equels("oneplc")){
System.exit(0);
}
if static string then instead of
securityKey == "oneplc"
do
securityKey.equals("oneplc");
if from strings.xml then
securityKey.equals(getResources().getString(R.string.stringname));
I have the following code:
protected void showSelectToDialog() {
boolean[] checkedDate = new boolean[toDate.length];
int count = toDate.length;
DialogInterface.OnClickListener setD2 = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//TODO Auto-generated method stub
onChangeSelectedTo(which);
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select To Year");
builder.setSingleChoiceItems(toDate, count, setD2);
builder.setCancelable(true);
builder.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
dialog2 = builder.create();
dialog2.show();
}
protected void onChangeSelectedTo(int j) {
bTo.setText(toDate[j]);
sTo = ((AlertDialog)dialog2).getListView().getCheckedItemPosition();
blTo = true;
displayToast(String.valueOf(sTo));
to = j;
dialog2.dismiss();
}
What I am looking to do is, when the dialog loads the first time and the user selects a choice it is stored. So the next time the user opens the dialog, it will remember what was select and scroll to that choice.
How do I accomplish that?
Save the selected choice's position for the first time using Shared Preferences.
Then at the start of showSelectToDialog() check if any value exists in Shared Preferences, if so, then set the value of count from the Shared Preferences else set value of count to toDate.length.
I can't see the rest of your code, but all you have to do is save the user's choice in a variable somewhere else, and then read that choice every time you open the dialogue. It could be a static variable on the class, or it could be an instance variable of the class, or it could be a public field of some other class you have access to, like a parent object. You just need to assign it when you close the dialogue, and read it back and initialize the value to what you read when you open the dialogue.