I need to change positive button's text of an AlertBox from nothing to OK or Add according to the entered text. I have the following code for the AlertBox creation and displaying:
public void show() {
View inputView = LinearLayout.inflate(mContext, R.layout.goal_tag_input, null);
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setView(inputView);
mInput = inputView.findViewById(R.id.goal_tag_input);
mInput.addTextChangedListener(mTagNameTextWatcher);
List<Tag> availableTags = AppDatabase.getInstance(mContext).tagDao().getAll();
mAvailableTagLabels = new ArrayList<>();
for (Tag tag : availableTags) {
mAvailableTagLabels.add(tag.getName());
}
ArrayAdapter<String> inputAdapter = new ArrayAdapter<>(mContext,
android.R.layout.select_dialog_item, mAvailableTagLabels);
mInput.setAdapter(inputAdapter);
builder.setCancelable(true);
builder.setPositiveButton("", mAddTagClickListener);
builder.setNegativeButton(R.string.Cancel, null);
mDialog = builder.create();
mDialog.show();
}
Also I have a TextWatcher implementation:
private TextWatcher mTagNameTextWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
#Override
public void afterTextChanged(Editable s) {
String tagName = mInput.getText().toString();
if (tagName.trim() != "") {
Button buttonPositive = mDialog.getButton(DialogInterface.BUTTON_POSITIVE);
if (mAvailableTagLabels.contains(tagName)) {
buttonPositive.setText(R.string.OK);
} else {
buttonPositive.setText(R.string.Add);
}
}
}
};
During debugging I observed that the text value of the buttonPositive is changed appropriately, but it is not reflected in the interface. Do you have any ideas why is it so? I checked this answer but it didn't help.
Well, it appeared that the problem was in the setting a positive button using the AlertDialog builder here: builder.setPositiveButton("", mAddTagClickListener);. Apparently, a button is not created if you pass an empty string as the first argument. The minute I tried to change it to (at least) one-space-string - everything began to work as expected.Later on I changed the approach to enabling/disabling the button.
Well you can try this
public void show() {
View inputView = LinearLayout.inflate(AppIntroActivity.this, R.layout.goal_tag_input, null);
AlertDialog.Builder builder = new AlertDialog.Builder(AppIntroActivity.this);
builder.setView(inputView);
final EditText mInput =(EditText) inputView.findViewById(R.id.goal_tag_input);
final Button buttonPositive = (Button) inputView.findViewById(R.id.button_id);
mInput.addTextChangedListener( new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
#Override
public void afterTextChanged(Editable s) {
String tagName = mInput.getText().toString();
if (tagName.trim() != "") {
if (mAvailableTagLabels.contains(tagName)) {
buttonPositive.setText(R.string.OK);
} else {
buttonPositive.setText(R.string.Add);
}
}
}
};);
List<Tag> availableTags = AppDatabase.getInstance(mContext).tagDao().getAll();
mAvailableTagLabels = new ArrayList<>();
for (Tag tag : availableTags) {
mAvailableTagLabels.add(tag.getName());
}
ArrayAdapter<String> inputAdapter = new ArrayAdapter<>(mContext,
android.R.layout.select_dialog_item, mAvailableTagLabels);
mInput.setAdapter(inputAdapter);
builder.setCancelable(true);
builder.setPositiveButton("", mAddTagClickListener);
builder.setNegativeButton(R.string.Cancel, null);
mDialog = builder.create();
mDialog.show();
}
Related
based on the image below, I have NIK & NAMA fields. the concept is when I fill in the NIK field then I press the GET button it will display the name(NAMA FIELD)
Picture : Menu add
Database structure example
NIK
NAMA
96296
Farrasta
94878
Alfian
Java class
btnGet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NikKry = etNik.getText().toString();
getNama(); // THE FUNCTION
}
});
private void getNama(){
APIRequestData armNama = RetroMaster.konekRetrofit().create(APIRequestData.class);
Call<ResponseMaster> tampilNama = armNama.ardGetNama(NikKry);
tampilNama.enqueue(new Callback<ResponseMaster>() {
#Override
public void onResponse(Call<ResponseMaster> call, Response<ResponseMaster> response) {
// HOW TO CODE PROPERLY ?
}
#Override
public void onFailure(Call<ResponseMaster> call, Throwable t) {
}
});
}
PHP file
<?php
include ("koneksi.php");
$response = array();
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$NIK = $_POST["NIK"];
$query = "SELECT NAMA FROM MASTER_KRY WHERE NIK = '$NIK'";
$eksekusi = oci_parse($conn, $query);
$cek = oci_execute($eksekusi);
if($cek > 0){
$response["data"] = array();
while($ambil = oci_fetch_object($eksekusi)){
$F["NAMA"] = $ambil->NAMA;
array_push($response["data"], $F);
}
}else{
$response["pesan"] = "Data tidak tersedia";
}
}
else{
$response["pesan"] = "*&*%4668%*%^$%#*&*(()%$!##%";
}
echo json_encode($response);
oci_close($conn);
?>
If you used EditText then this method will be help you to notify when text change in EditText.
editTextObject.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
// here you get text via "s.toString();"
NikKry = s.toString();
getNama();
}
});
If you used AutoCompleteTextView then this method will be help you like:
autoCompleteTextView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
NikKry = yourArrayList.get(position).getText().toString();
getNama();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
This depends on your entity of ResponseMaster. If the entity has field Nama and getter setter exists, you can use below:
if(response.isSuccessful()){
edNama.setText(response.body().getNama());
}else{
// show toast or log error
}
I have a form. I want to display a calculation in "live time" when the user enters different values into some int fields. I made my Activity implement the TextWatcher interface and set a listener on 3 different EditText fields but it appears the Textwatcher only detects the first EditText declared in the Activity's code.
You can see from the code below, I'm trying to grabe a few fields, convert them to ints and display the output in an EditText field at the bottom of the form. Where am I going wrong? Do I need to implement a textWatcher individually on all of the EditText fields involved? That would be a rather verbose solution making my code a lot longer than I would like
public class NewStageFormActivity extends AppCompatActivity implements TextWatcher{
Context mContext;
EditText mStageName, mPaperTargets, mHitsPerTarget, mSteelTargets, mSteelNPMs, mOutput;
Spinner mScoringType, mStrings;
CheckBox mNoShoots, mNPMs;
Button mSaveButton;
Match mGlobalMatch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stage_form);
mContext = this;
mGlobalMatch = GlobalMatch.getMatch();
mStageName = (EditText)findViewById(R.id.stage_name_et);
mPaperTargets = (EditText)findViewById(R.id.paper_targets_et);
mHitsPerTarget = (EditText)findViewById(R.id.hits_per_target_et);
mSteelTargets = (EditText)findViewById(R.id.steel_targets_et);
mSteelNPMs = (EditText)findViewById(R.id.steel_npm_et);
mScoringType = (Spinner)findViewById(R.id.scoring_type_spinner);
mStrings = (Spinner)findViewById(R.id.strings_spinner);
mNoShoots = (CheckBox)findViewById(R.id.no_shoots_cb);
mNPMs = (CheckBox)findViewById(R.id.npm_cb);
mSaveButton = (Button)findViewById(R.id.save_button);
mOutput = (EditText)findViewById(R.id.output_et);
// paper * hitsPer + steel
mPaperTargets.addTextChangedListener(this);
mSteelTargets.addTextChangedListener(this);
mSteelTargets.addTextChangedListener(this);
mSaveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(mStageName.getText().toString().equals("") || mPaperTargets.getText().toString().equals("") ||
mHitsPerTarget.getText().toString().equals("") || mSteelTargets.getText().toString().equals("") ||
mSteelNPMs.getText().toString().equals("")){
Toast.makeText(mContext, "You must fill in all form fields", Toast.LENGTH_SHORT).show();
} else {
String name = mStageName.getText().toString();
String type = mScoringType.getSelectedItem().toString();
int strings = Integer.valueOf(mStrings.getSelectedItem().toString());
int paperTargets = Integer.valueOf(mPaperTargets.getText().toString());
int hitsPerTarget = Integer.valueOf(mHitsPerTarget.getText().toString());
boolean noShoots;
boolean npms;
if(mNoShoots.isChecked()){
noShoots = true;
} else {
noShoots = false;
}
if(mNPMs.isChecked()){
npms = true;
} else {
npms = false;
}
int steelTargets = Integer.valueOf(mSteelTargets.getText().toString());
int steelNPMs = Integer.valueOf(mSteelNPMs.getText().toString());
MatchStage matchStage = new MatchStage(name, type, strings, paperTargets, hitsPerTarget,
noShoots, npms, steelTargets, steelNPMs);
mGlobalMatch.getStages().add(matchStage);
String jsonString = new Gson().toJson(mGlobalMatch);
MatchHelper.updateFile(mContext, MatchHelper.createFileName(mGlobalMatch.getMatchId()),
jsonString);
Intent intent = new Intent(mContext, StagesListActivity.class);
startActivity(intent);
}
}
});
}
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
int paper = Integer.valueOf(mPaperTargets.getText().toString());
int hitsPer = Integer.valueOf(mHitsPerTarget.getText().toString());
int steel = Integer.valueOf(mSteelTargets.getText().toString());
int minRound = (paper * hitsPer) + steel;
int points = minRound * 5;
mOutput.setText("Minimum rounds: " + (minRound) + "\t\t Points: " + points);
}
#Override
public void afterTextChanged(Editable editable) {
}
}
In my experience I've had issues with using the same TextWatcher on multiple EditText. You could get around this by creating a method that produces a new instance of TextWatcher for each EditText so your code isn't all verbose. Try something like this:
Get rid of implements TextWatcher for your Activity and it's associated methods. Implement a method createTextWatcher():
private TextWatcher createTextWatcher() {
return new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
// Copy your original code
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
// Copy your original code
}
#Override
public void afterTextChanged(Editable editable) {
// Copy your original code
}
};
}
Now to use it like this:
mPaperTargets.addTextChangedListener(createTextWatcher());
mSteelTargets.addTextChangedListener(createTextWatcher());
The most up-voted answer on #Natan Felipe's link also demonstrates using one instance of TextWatcher per EditText.
I have multiple EditText views , each EditText view can contain only 1 char.
I need to make this rule - if I focus on one EditText , and it already has some text inside - then overwrite it . Also - if I press on delete key - I need the text to be cleared inside that view.
Then - I am checking if the EditText views has 1 empty cell - if not - checking if the EditText views has the correct letters.
I could have managed to make the clear button work, but I can not make the overwrite.
I did tried to use the TextWatcher , but it didn't work for me.
The EditText views are created dynamically .
Here is my code :
Answer.java
public class Answer {
String answer;
int answer_length;
int cell_margin=10;
int cell_size=180;
EditText[] EditTextArray;
public Answer(RelativeLayout rLayout1, Context context , String answer) {
this.answer = answer;
answer_length = answer.length();
if (answer_length>6){
cell_margin = 4;
cell_size = 110;
}
EditTextArray = new EditText[answer_length];
AnswerCell EditTextToSeeFirst = new AnswerCell(context,cell_size);
setListener(EditTextToSeeFirst);
EditTextArray[0] = EditTextToSeeFirst;
RelativeLayout.LayoutParams fparams = new RelativeLayout.LayoutParams
(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
fparams.setMargins(cell_margin,0,cell_margin,0);
rLayout1.addView(EditTextToSeeFirst, fparams);
for (int i = 1; i<answer_length ; i++){
RelativeLayout.LayoutParams lparams = new RelativeLayout.LayoutParams
(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lparams.addRule(RelativeLayout.LEFT_OF, EditTextArray[i-1].getId());
lparams.setMargins(cell_margin,0,cell_margin,0);
AnswerCell newEditText = new AnswerCell(context,cell_size);
setListener(newEditText);
EditTextArray[i] = newEditText;
rLayout1.addView(EditTextArray[i], lparams);
}
rLayout1.setGravity(Gravity.CENTER );
}
public void setListener(AnswerCell ac){
ac.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Log.d("test","test");
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
goToNextAvailableCell();
}
});
}
public void goToNextAvailableCell(){
for (int i = 0; i<answer_length ; i++) {
if(EditTextArray[i].getText().toString().matches("")){
EditTextArray[i].requestFocus();
return;
}
}
//Did not found empty cell
checkCorrectAnswer();
}
private void checkCorrectAnswer(){
String tryAnswer = "";
for (int i = 0; i<answer_length ; i++) {
tryAnswer += EditTextArray[i].getText().toString();
}
if (tryAnswer.matches(answer)){
Log.d("Correct !!","Correct Answer");
}
}
}
AnswerCell.java
public class AnswerCell extends EditText{
public AnswerCell(final Context context, int cell_size) {
super(context);
this.setId(View.generateViewId());
this.setBackgroundResource(R.color.answerCellBackground);
this.setHeight(cell_size);
this.setWidth(cell_size);
this.setFilters(new InputFilter[] {new InputFilter.LengthFilter(1)});
this.setCursorVisible(false);
this.setGravity(Gravity.CENTER);
this.setOnFocusChangeListener( new View.OnFocusChangeListener(){
public void onFocusChange( View view, boolean hasfocus){
if(hasfocus){
view.setBackgroundResource( R.drawable.answer_cell_has_focus);
}
else{
view.setBackgroundResource( R.drawable.answer_cell_lost_focus);
}
}
});
this.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
//You can identify which key pressed buy checking keyCode value with KeyEvent.KEYCODE_
if(keyCode == KeyEvent.KEYCODE_DEL) {
((EditText)v).setText("");
return true;
}
return false;
}
});
}
}
thanks !
It will work with this code
TextWatcher watcher = new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//YOUR CODE
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//YOUR CODE
}
#Override
public void afterTextChanged(Editable s) {
String outputedText = s.toString();
// mOutputText.setText(outputedText);
}
};
Then add this in oncreate
mInputText.addTextChangedListener(watcher);
e2.addTextChangedListener(watcher);
e3.addTextChangedListener(watcher);
e4.addTextChangedListener(watcher);
After declaring and creating the textWatcher object, I would like to disable the send button and set it to gray if the chatText (edit text) is empty
I think it's a problem of ranking. Please help.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
list = (ListView)findViewById(R.id.listView);
list.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
chatText = (EditText)findViewById(R.id.editText);
//chatText.setOnKeyListener(this);
me = true;
send = (Button)findViewById(R.id.button);
change = (Button)findViewById(R.id.button2);
list.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
adp = new TheAdapter(getApplicationContext(),R.layout.chat);
list.setAdapter(adp);
chatText.addTextChangedListener(textWatcher);
checkFieldsForEmptyValues();
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
envoyer();
}
});
change.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
me = !me;
if (!me) {
change.setText(R.string.sender2);
} else {
change.setText(R.string.sender);
}
}
});
}
public void envoyer(){
adp.add(new messages(me, chatText.getText().toString()));
chatText.setText("");
}
private void checkFieldsForEmptyValues(){
String s1 = chatText.getText().toString();
if (s1.length() < 0 ) {
send.setEnabled(false);
} else {
send.setEnabled(true);
send.setBackgroundColor(Color.BLUE);
//send.setBackgroundColor((getResources().getColor(R.color.blue)));
}
}
In the onTextChanged is where you would check to see if the text field is empty:
chatText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() > 0) { //enable}
else if (s.length() == 0 { //disable }
In your code, you have if (s1.length() < 0 ) which I don't think will ever be true because the text size will never be less than 0.
// Disable on init
send.setEnabled(false);
// add text changer
chatText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Enable when input is != null and not empty. You can check string lenght too
send.setEnabled(s != null && !s.toString().isEmpty());
}
#Override
public void afterTextChanged(Editable s) {
}
});
disable button before and add textwatch. You can also check if edittext value is not empty or verify string length.
I hope it will help you
i've placed a button on my dialog layout that i would like to trigger a complete redraw of the Dialog. However, it appears you can't open dialogs from within onCreateDialog, and i can't find a way to dismiss dialogs without using setPositiveButton and the like, as it's the only Button override that gives the dialog as a parameter (and i can't find a way to get it for a Button that's part of the layout). here's all the relevant code:
case DIALOG_WIFI_PREF:
{
Dialog dialog = new Dialog(this);
final View dialogLayout = inflater.inflate(R.layout.dialog_wifi_pref, null);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(dialogLayout);
builder.setTitle("IP Configuration");
final EditText ipIn = (EditText)dialogLayout.findViewById(R.id.wifi_ip_in);
final EditText portIn = (EditText)dialogLayout.findViewById(R.id.wifi_port_in);
final EditText labelIn = (EditText)dialogLayout.findViewById(R.id.site_label_in);
final EditText codeIn = (EditText)dialogLayout.findViewById(R.id.activation_code);
final Spinner siteSpn = (Spinner)dialogLayout.findViewById(R.id.site_spn);
final Button deleteBtn = (Button)dialogLayout.findViewById(R.id.delete_btn);
final Cursor cur = mDb.rawQuery("SELECT * FROM " + DbSchema.SiteSchema.TABLE_NAME, null);
cur.moveToFirst();
final SimpleCursorAdapter tempAdapter = new SimpleCursorAdapter(
this,
android.R.layout.simple_spinner_item,
cur,
new String[] { DbSchema.SiteSchema.COLUMN_LABEL },
new int[] { android.R.id.text1 }
);
tempAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
siteSpn.setAdapter(tempAdapter);
//fill the initial values
String initSite = pref.getString("site_id", "New Site");
String spnLabel = null;
final Cursor initCur = mDb.query(DbSchema.SiteSchema.TABLE_NAME, null, DbSchema.SiteSchema.COLUMN_LABEL + "=?", new String[] { initSite }, null, null, null);
initCur.moveToFirst();
cur.moveToFirst();
if(initCur.getCount()>0) {
ipIn.setText(initCur.getString(initCur.getColumnIndex(DbSchema.SiteSchema.COLUMN_IP)));
portIn.setText(initCur.getString(initCur.getColumnIndex(DbSchema.SiteSchema.COLUMN_PORT)));
codeIn.setText(initCur.getString(initCur.getColumnIndex(DbSchema.SiteSchema.COLUMN_ACTIVATION_CODE)));
spnLabel = initCur.getString(initCur.getColumnIndex(DbSchema.SiteSchema.COLUMN_LABEL));
labelIn.setText(spnLabel);
if(cur.getCount()>0) {
do {
if(spnLabel.equals(cur.getString(cur.getColumnIndex(DbSchema.SiteSchema.COLUMN_LABEL)))) {
siteSpn.setSelection(cur.getPosition());
}
} while(cur.moveToNext());
}
}
siteSpn.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
cur.moveToFirst();
if(cur.getCount()>0) {
do {
String tempLabel = cur.getString(cur.getColumnIndex(DbSchema.SiteSchema.COLUMN_LABEL));
if(tempLabel.equals(((TextView)view.findViewById(android.R.id.text1)).getText().toString())) {
labelIn.setText(tempLabel);
portIn.setText(cur.getString(cur.getColumnIndex(DbSchema.SiteSchema.COLUMN_PORT)));
ipIn.setText(cur.getString(cur.getColumnIndex(DbSchema.SiteSchema.COLUMN_IP)));
codeIn.setText(cur.getString(cur.getColumnIndex(DbSchema.SiteSchema.COLUMN_ACTIVATION_CODE)));
}
} while(cur.moveToNext());
}
}
public void onNothingSelected(AdapterView<?> parent) {
//
}
});
deleteBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//do things
cur.moveToFirst();
while(cur.moveToNext()) {
String tempLabel = cur.getString(cur.getColumnIndex(DbSchema.SiteSchema.COLUMN_LABEL));
View selectedSiteView = siteSpn.getSelectedView();
String label = ((TextView)selectedSiteView.findViewById(android.R.id.text1)).getText().toString();
if(tempLabel.equals(label)) {
mDb.delete(DbSchema.SiteSchema.TABLE_NAME, DbSchema.SiteSchema.COLUMN_LABEL+"=?", new String[] { label });
//dialogLayout.invalidate();
//dialog.dismiss();
//dialog.invalidate();
//v.getParent().invalidate();
}
}
}
});
builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
cur.moveToFirst();
boolean newRecord = true;
do {
String tempLabel = null;
if(cur.getCount()>0) {
tempLabel = cur.getString(cur.getColumnIndex(DbSchema.SiteSchema.COLUMN_LABEL));
}
if(tempLabel!=null && tempLabel.equals(labelIn.getText().toString())) {
//update
ContentValues cv = new ContentValues();
cv.put(DbSchema.SiteSchema.COLUMN_IP, ipIn.getText().toString());
cv.put(DbSchema.SiteSchema.COLUMN_PORT, portIn.getText().toString());
cv.put(DbSchema.SiteSchema.COLUMN_ACTIVATION_CODE, codeIn.getText().toString());
MobileDashboardActivity.this.mDb.update(DbSchema.SiteSchema.TABLE_NAME, cv, DbSchema.SiteSchema.COLUMN_LABEL+"=?", new String[] { tempLabel });
newRecord = false;
break;
}
} while(cur.moveToNext());
if(newRecord) {
//new entry
ContentValues cv = new ContentValues();
cv.put(DbSchema.SiteSchema.COLUMN_IP, ipIn.getText().toString());
cv.put(DbSchema.SiteSchema.COLUMN_PORT, portIn.getText().toString());
cv.put(DbSchema.SiteSchema.COLUMN_LABEL, labelIn.getText().toString());
cv.put(DbSchema.SiteSchema.COLUMN_ACTIVATION_CODE, codeIn.getText().toString());
MobileDashboardActivity.this.mDb.insert(DbSchema.SiteSchema.TABLE_NAME, null, cv);
}
SharedPreferences.Editor editor = pref.edit();
editor.putString("site_id", labelIn.getText().toString());
editor.putString("activation", codeIn.getText().toString());
editor.commit();
MobileDashboardActivity.this.writeCSVFile("dashboard_settings.csv");
dialog.dismiss();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
dialog = builder.create();
return dialog;
}
i ended up following this example:
http://developmentality.wordpress.com/2009/10/31/android-dialog-box-tutorial/
which uses the Command pattern to proc outer logic:
http://en.wikipedia.org/wiki/Command_pattern
and here are the files:
Command.java:
package com.conceptualsystems.dialog;
[...import statements...]
public interface Command {
public void execute();
public static final Command NO_OP = new Command() { public void execute() {} };
}
CommandWrapper.java:
package com.conceptualsystems.dialog;
[...import statements...]
public class CommandWrapper implements DialogInterface.OnClickListener {
private Command command;
public CommandWrapper(Command command) {
this.command = command;
}
public void execute() {
command.execute();
}
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
command.execute();
}
}
relevant code from MainActivity.java (member variable definition):
Command delete = new Command() {
public void execute() {
removeDialog(DIALOG_WIFI_PREF);
showDialog(DIALOG_WIFI_PREF);
}
};
dialog code utilizing Command class and CommandWrapper:
builder.setNeutralButton("Delete", new CommandWrapper(delete) {
public void onClick(DialogInterface dialog, int which) {
//do things
cur.moveToFirst();
while(cur.moveToNext()) {
String tempLabel = cur.getString(cur.getColumnIndex(DbSchema.SiteSchema.COLUMN_LABEL));
View selectedSiteView = siteSpn.getSelectedView();
String label = ((TextView)selectedSiteView.findViewById(android.R.id.text1)).getText().toString();
if(tempLabel.equals(label)) {
mDb.delete(DbSchema.SiteSchema.TABLE_NAME, DbSchema.SiteSchema.COLUMN_LABEL+"=?", new String[] { label });
}
}
dialog.dismiss();
this.execute();
}
});