How to retrieve value from EditText in AlertDialog? - android

When selected, a context menu option brings up an AlertDialog. I want the user to enter text into an EditText in the AlertDialog, and when the user presses PositiveButton, the value of EditText is able to be "returned" to the main method. Here is the relevant code from my class:
public class PassPlay extends ListActivity {
public static final int PENALTY_ID = Menu.FIRST+1;
public static final int FUMBLE_ID = Menu.FIRST+2;
public static final int ADDLYDS_ID = Menu.FIRST+3;
public static final int SAFETY_ID = Menu.FIRST+4;
EditText ydsFromAlertDialog;
String penYdsStr;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.passplay);
ydsFromAlertDialog=(EditText)findViewById(R.id.passYdsLabel);
registerForContextMenu(getListView());
}
public boolean onCreateOptionsMenu(Menu menu) {
populateMenu(menu);
return(super.onCreateOptionsMenu(menu));
}
public boolean onOptionsItemSelected(MenuItem item) {
return(applyMenuChoice(item) || super.onOptionsItemSelected(item));
}
public boolean onContextItemSelected(MenuItem item) {
return(applyMenuChoice(item) || super.onContextItemSelected(item));
}
private void populateMenu(Menu menu) {
menu.add(Menu.NONE, PENALTY_ID, Menu.NONE, "Penalty");
menu.add(Menu.NONE, FUMBLE_ID, Menu.NONE, "Fumble");
menu.add(Menu.NONE, ADDLYDS_ID, Menu.NONE, "Additional Yards");
menu.add(Menu.NONE, SAFETY_ID, Menu.NONE, "Safety");
}
private boolean applyMenuChoice(MenuItem item) {
LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView;
switch (item.getItemId()) {
case PENALTY_ID:
textEntryView = factory.inflate(R.layout.textdialog, null);
new AlertDialog.Builder(this)
.setView(textEntryView)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(R.string.timeout)
.setPositiveButton(R.string.offense, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Actions for offensive timeout
EditText penaltyYds=(EditText)findViewById(R.id.ydsAssessedLabel);
penYdsStr = penaltyYds.getText().toString();
ydsFromAlertDialog.setText(penYdsStr);
}
})
.setNeutralButton(R.string.defense, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Actions for defensive timeout
}
})
.setNegativeButton(R.string.cancel, null)
.show();
return true;
case FUMBLE_ID:
//Fumble window
return true;
case ADDLYDS_ID:
//Additional Yards window
return true;
case SAFETY_ID:
//Safety window
return true;
}
return(false);
}
}
The main XML layout (passplay.xml) has your normal TextViews, EditTexts, CheckBoxes, etc. I want to set one of those EditTexts (ydsFromAlertDialog) to be assigned the value entered in the AlertDialog (EditText penaltyYds). The AlertDialog's XML layout (textdialog.xml) is very simple with one TextView and one EditText.
When I run the program, the following line errors out with "The application has stopped unexpectedly."
penYdsStr = penaltyYds.getText().toString();
So in summary, I want to press the menu option "Penalty", have an AlertDialog with an EditText where I enter a number, and when I press PositiveButton, the EditText ydsFromAlertDialog's value is changed to what was entered in the Dialog.
In reality, I have a database table with 5 columns, 4 of which will be populated by normal fields, but the 5th will be populated by the value entered in the Dialog. I figured if I can "return" it to "be with" the rest of the values, I'll be able to save it to same table record as the others, too.
Let me know if you need any more information. Thank you!

You have to get the ydsAssessedLabel from the view you inflated
EditText penaltyYds=(EditText)textEntryView.findViewById(R.id.ydsAssessedLabel);

Related

Show the value of an item at a position in a Material Dialog

I have a List of Array String that I populate the values in a Material Dialog. When I click on an item in the dialog, I want to get the item at that position and set the value to a TextView. Unfortunately no matter the item I choose I still get the last value set to the TextView.
My code:
new MaterialDialog.Builder(DetailProfileActivity.this)
.title(R.string.id_types_title)
.items(set)
.itemsCallbackSingleChoice(0, new MaterialDialog.ListCallbackSingleChoice() {
#Override
public boolean onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
idType = which;
switch (idType){
case 0:
txtIdType.setText("Voters");
case 1:
txtIdType.setText("Passport");
case 2:
txtIdType.setText("DriversLicense");
}
return true;
}
})
.positiveText(R.string.choose)
.show();
Try this onSelection() giving the string result you can use directly
new MaterialDialog.Builder(DetailProfileActivity.this)
.title(R.string.id_types_title)
.items(set)
.itemsCallbackSingleChoice(0, new MaterialDialog.ListCallbackSingleChoice() {
#Override
public boolean onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
txtIdType.setText(text);
return true;
}
})
.positiveText(R.string.choose)
.show();
}

Alert Dialog weird trouble on Contextual Action Mode

I have a very strange situation. I am using Contextual Action Mode for selecting multiple items of the ListView. The flow goes as follows:
User selects the list items using long press on them --> Uses the action item "Operations" to choose what he wants to do --> This action item creates a AlertDialog with 4 list items (call it dialog1) where the 3rd item calls another AlertDialog (call it dialog2) which includes an EditText for some data input and later calls a method to perform it.
Later the user hits Back button or Home button to exit the Action Mode.
The problem is that dialog2 shows up alternatively like first time user selects the list items, Chooses "Operations" action item and chooses the 3rd item which calls dialog2. Now dialog2 will appear as it is supposed to. Later the user hits the Back button to quit the Action Mode.
The SECOND TIME user performs the same steps dialog2 doesn't appear.
The logcat shows this error in both the cases:
09-04 10:53:12.096 6299-6299/com.project.pcmanager
W/InputEventReceiver: Attempted to finish an input event but the input
event receiver has already been disposed.
Some code:
public void sendAction(final Context context, final EventModel model, int position) {
JSONObject object = new JSONObject();
String[] operations = getResources().getStringArray(R.array.operations);
// null set before is modified here
model.setEventTitle(operations[position]);
final String ip = model.getEventIP();
switch (position) {
case 0:
try {
object.put("command", "power_off");
notifyUser();
LogUtils.addEntry(model.toString());
execCommand(ip,object);
} catch (JSONException e) {
e.printStackTrace();
}
break;
case 1:
try {
object.put("command", "reboot");
notifyUser();
LogUtils.addEntry(model.toString());
execCommand(ip,object);
} catch (JSONException e) {
e.printStackTrace();
}
break;
case 2:
//Show AlertDialog with EditText on it for command input
final EditText txtCommand = new EditText(context);
// Set some properties to EditText
txtCommand.setPadding(16, 16, 16, 16);
txtCommand.setMinHeight(150);
txtCommand.setHint("Ex: ping google.com");
txtCommand.setSingleLine();
new AlertDialog.Builder(context)
.setTitle("Run a task")
.setView(txtCommand)
.setCancelable(false)
.setPositiveButton("Run",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String command = txtCommand.getText().toString();
if (command.length() > 0) {
JSONObject object = new JSONObject();
try {
object.put("run", command);
object.put("ip", ip);
notifyUser();
LogUtils.addEntry(model.toString());
performRemoteExec(object);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(context, "Please provide a command first!", Toast.LENGTH_SHORT).show();
}
}
}).setNeutralButton("Cancel", null).show();
break;
case 3:
notifyUser();
LogUtils.addEntry(model.toString());
getScreenshot(ip);
break;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
listView.setAdapter(adapter);
listView.setEmptyView(emptyView);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
listView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
//Change the title bar with the items selected
mode.setTitle(listView.getCheckedItemCount() + " selected");
//select the clicked item
adapter.toggleSelection(position);
}
/**
* Called when action mode is first created.
* The menu supplied will be used to generate action buttons for the action mode.
* #param mode ActionMode being created
* #param menu Menu used to populate action buttons
* #return true if the action mode should be created,
* false if entering this mode should be aborted.
*/
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
onContextMode = true;
mode.getMenuInflater().inflate(R.menu.menu_client_select_main, menu);
return true;
}
/**
* Called to refresh an action mode's action menu whenever it is invalidated.
* #return true if the menu or action mode was updated, false otherwise.
*/
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
/**
* Called to report a user click on an action button.
* #return true if this callback handled the event,
* false if the standard MenuItem invocation should continue.
*/
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
int id = item.getItemId();
if (id == R.id.menu_operations) {
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setItems(R.array.operations, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
SparseBooleanArray selectedIds = adapter.getSelectedIds();
// traverse the array to find chosen clients
for (int i = 0; i < selectedIds.size(); i++) {
if (selectedIds.get(i)) {
ClientModel item = adapter.getItem(i);
String ip = item.getClientIP();
String os = item.getOSType();
// null will be treated soon
EventModel model = new EventModel(ip, null, os);
sendAction(builder.getContext(),model, which);
}
}
}
});
builder.show();
}
return true;
}
/**
* Called when an action mode is about to be exited and destroyed.
*/
#Override
public void onDestroyActionMode(ActionMode mode) {
onContextMode = false;
}
});
}
Ok so I figured the problem myself. It turns out the culprit was me using SparseBooleanArray to get selected clients and I was wrong.
In my code it was:
SparseBooleanArray selectedIds = adapter.getSelectedIds();
So, I removed this SparseBooleanArray with a new implementation technique. I used ArrayList<ClientMode> selectedItems to store all the selected models in my Adapter class.
Also, I created a simple method called clearSelections that calls selectedItems.clear() method in it. I call this method at on onDestroyActionMode as per my app requirement.
HOW I FOUND THIS?
I simply placed a bunch of System.out.println statements all around onCreate and sendAction to find out the culprit.

Alertdialog selected items Arraylist is growing when i came from child activity

I have 2 Activities A(user input) and B (Display based on user input). Where in Activity A, i am selecting multiple values from alert dialog and put it in arraylist then pass it on to the activity B. So when i want to change the values i need to comeback to Activity A and i can reselect. But When i am reselecting the value or removing any values the older selected values are also exist so that my Arraylist is keep on growing. Please help.
Activity A:
public class AllMovieRating extends ActionBarActivity implements View.OnClickListener {
private Views mViews;
final ArrayList ilist = new ArrayList();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_movie_rating);
mViews=new Views();
mViews.irating.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.imdb_rating:
ilist();
break;
}
}
private void filtervalues() {
Intent intent = new Intent(AllRating.this,sharedcollect.class);
intent.putExtra("im",ilist);
startActivity(intent);
}
public ArrayList ilist() {
final CharSequence[] ratings = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
final boolean[] ratingschecked = {false, false, false, false, false, false, false, false, false, false};
SharedPreferences sharedPreferences = this.getSharedPreferences("checkedrate_i", Context.MODE_PRIVATE);
final SharedPreferences.Editor editor = sharedPreferences.edit();
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
int size = sharedPreferences.getInt("size", 0);
for(int j=0;j<size;j++)
{
ilist.add(sharedPreferences.getString("selectedratings" + j, null));
//Log.e("Kumar", "" + selectedratings);
}
for(int j=0;j<=ratingschecked.length;j++){
if(ilist.contains((String.valueOf(j)))) {
ratingschecked[j-1] = true;
}
}
builder.setTitle("Select Ratings");
builder.setMultiChoiceItems(ratings, ratingschecked, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked) {
if(!ilist.contains((String)String.valueOf(ratings[which]))){
ilist.add(String.valueOf(ratings[which]));
ratingschecked[which]=true;
}
} else if ((ilist.contains((String)String.valueOf(ratings[which])))) {
ilist.remove(String.valueOf(ratings[which]));
// Log.e("Kumar", String.valueOf(ratings[which]));
ratingschecked[which]=false;
}
}
}).setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// editor.putString("checked", String.valueOf(selectedratings));
for (int i = 0; i < ilist.size(); i++) {
editor.putString("selectedratings" + i, String.valueOf(ilist.get(i)));
}
editor.putInt("size", ilist.size());
editor.apply();
//Log.e("Shiva", String.valueOf(selectedratings));
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog dialog = builder.create();
builder.show();
return ilist;
}
Activity B:
public class sharedcollect extends ActionBarActivity {
ListView movielist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sharedcollect);
Intent i = getIntent();
ArrayList<String> list = i.getStringArrayListExtra("im");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_sharedcollect, menu);
return true;
}
#Override
public void onBackPressed() {
//do whatever to save the settings
moveTaskToBack(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()){
case R.id.action_settings:
Intent intent = new Intent(sharedcollect.this,AllMovieRating.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
} }}
Tried using OnBackPressed() inside onOptionsItemSelected(MenuItem item) in Activity B but that doesn't helped. How can i control array list so that i will send only the selected items.
You will need to clear the array Before every reselecting in Activity A.
ilist.clear();
In your case my guess is to do add the following in your Activity A.
EDITED:
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.imdb_rating:
ilist.clear();
ilist();
break;
}}

Saving and Restoring AlertDialog SetSingleChoice Option After Application Exit and Restarting

I am using SingleChoiceItems in ActionBar using DialogBuilder. I need to save the item selected even after exiting the application then restore the saved setting when accessing the application again.
I saw many examples of shared preferences and onRestoreInstanceState() and onSaveInstanceState() but I am quite confused. Below is the code with explanations of what I did.
Dialog Builder
I saved the present state of the selected option in - > selectPosition .. Then saving the selectedPosition in the global variable isChecked and setting it to the SelectSingleChoice arguments.
public void displaySortDialog(final Context context) {
int selection = context.getSharedPreferences(PREF_NAME,
Context.MODE_MULTI_PROCESS).getInt("Selection_key", 0);
Toast.makeText(getApplicationContext(), "Start Sel :"+selection , Toast.LENGTH_SHORT).show();
CharSequence[] sort_options = { "Z-A", "A-Z", "Size" };
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.sort_apps));
builder.setSingleChoiceItems(sort_options, selection,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int selected_sort) {
/*
* Toast.makeText(getApplicationContext(),
* sort_options[selected_sort], Toast.LENGTH_SHORT)
* .show(); // isChecked = restoredChecked;
*/
}
});
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// saving
context.getSharedPreferences(PREF_NAME,
Context.MODE_MULTI_PROCESS).edit()
.putInt("Selection_key", id ).commit();
Toast.makeText(getApplicationContext(), "Choosen :"+id, Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.create().show();
}
Declaring and using the displaySortDialog funtion
public boolean onOptionsItemSelected(MenuItem item) {
boolean result = true;
result = menuChoice(item);
switch (item.getItemId()) {
case R.id.menu_Sort_By_Size: {
displaySortDialog(getBaseContext());
break;
}
case R.id.menu_Action_Search: {
// openSearch();
break;
}
default: {
result = super.onOptionsItemSelected(item);
break;
}
}
return result;
}
Using the below code when I long press the home button or press the home button from the application the selected setting seems OK. They are selected and saved as I toast the message to make sure they are selected which means onSaveInstanceState is working because the toast message in onSaveInstanceState is displayed. But when I try to restore the settings saved through onRestoreInstanceState() then it doesn't work. After exiting the application the settings go back to default.
public void onRestoreInstanceState(Bundle savedInstanceState) {
if(savedInstanceState != null){
isChecked = savedInstanceState.getInt("SELECTED_SORT_ITEM");
Toast.makeText(getApplicationContext(), "RESTORED: "+isChecked, Toast.LENGTH_SHORT).show();
}
}
public void onSaveInstanceState(Bundle savedInstanceState) {
//outState.putInt(SELECTED_SORT_ITEM, getActionBar().getSelectedNavigationIndex());
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putInt(SELECTED_SORT_ITEM, isChecked);
Toast.makeText(getApplicationContext(), SELECTED_SORT_ITEM+isChecked, Toast.LENGTH_SHORT).show();
}
The toast OnSaveInstanceRestore is shown when I press the home button from the app or long press the home button and again select the app. But after exiting the app I am unable to restore the selected settings.
If you can help me with these methods or know some other method it would be appreciated.
Use shared preference,
like:
// For saving
context.getSharedPreferences(PREF_NAME,Context.MODE_MULTI_PROCESS)
.edit()
.put("Selection_key",selectedPosition)
.commit();
//For retrieve
int selection = context.getSharedPreferences(PREF_NAME,Context.MODE_MULTI_PROCESS)
.getInt("Selection_key",0); // 0 being default selection value, put whatever u want
// int selection, Use this Selection for your UI

Retaining items in a List View

I'm new to android development having some problems. I created a list view that is based on the user input. User has to enter a category in a dialog box and then it's added into the list. Works like a charm. The question is how do I retain those categories once the user exits from an app and starts it again ? When the user starts the app, the list is blank. Do I have to create a preference screen or something to save what the user types ? Here is my code:
public class MainActivity extends Activity {
final Context context = this;
ArrayAdapter<String> arrayAdapter;
ArrayList<String> listItems = new ArrayList<String>();
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lv = (ListView)findViewById(R.id.listView1);
arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, listItems);
lv.setAdapter(arrayAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.menu_add_cat:
LayoutInflater li = LayoutInflater.from(context);
View promptAdd = li.inflate(R.layout.prompt_add, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
//set prompts.xml to alertDialogBuilder
alertDialogBuilder.setView(promptAdd);
final EditText etAddCat = (EditText)promptAdd.findViewById(R.id.etDialogInput);
//set a dialog message
alertDialogBuilder.setPositiveButton("Done", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
/*
* add a cat here
*/
String input = etAddCat.getText().toString();
if(null != input && input.length() > 0){
listItems.add(input);
arrayAdapter.notifyDataSetChanged();
}else{
Toast.makeText(getApplicationContext(), "Please enter a new category", Toast.LENGTH_LONG).show();
}
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
break;
}
//return super.onOptionsItemSelected(item);
return true;
}
}// end of MainActivity
You can save it in SQLite DB, use CursorAdapter for your list view.
If the amount of data you want to save is relatively small you can use SharedPreferences to save the String data in your onClick method.
#Override
public void onClick(DialogInterface dialog, int which) {
String input = etAddCat.getText().toString();
if(null != input && input.length() > 0){
listItems.add(input);
// Add all string data to List<String> listItem
listItem.add(input);
arrayAdapter.notifyDataSetChanged();
}else{
Toast.makeText(getApplicationContext(), "Please enter a new category", Toast.LENGTH_LONG).show();
}
}
When the user leaves your activity, use the onStop() callback method to save your List<Strings> and store it through SharedPreferences.
#Override
private void onStop() {
super.onStop();
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putString(getResources().getString(R.string.list_of_strings), new HashSet<String>(listItem));
editor.commit;
}
Using the onStart() callback, initialize your List and SharedPreferences. When the user navigates to your activity, your list will be reinitialized when it was saved via onStop().
Finally, iterate through your list, add your items to your ArrayList', create yourArrayAdapter` and set it to your list.
#Override
private onStart(){
super.onStart();
SharedPreferences mSharedPreferences;
mSharedPreferences = this.getApplicationContext().getSharedPreferences("MyPreferences", 0);
List<String> listItems = new ArrayList<String>(mSharedPreferences.getStringSet("ListOfStrings", null));
ListIterator li = listItem.listIterator(0);
while (li.hasNext()) {
newStatusList.add((String)li.next());
}
arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, listItems);
lv.setAdapter(arrayAdapter);
}

Categories

Resources