In my code I can choose checkbox items and set their in my array:
protected ArrayList<Integer> selectedStatusId = new ArrayList<>();
But when I choose same checkbox item, need delet it from my array and... I cna't do it, becouse id in my array differs of my mStatuses.
How can I delete my desired item?
Maybe can I get all selected items after click positive button?
final ArrayList<String> statusesTitles = new ArrayList<>();
for (int i = 0; i < mStatuses.size(); i++) {
statusesTitles.add(mStatuses.get(i).StatusTitle);
}
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.order_dialog_status_title)
.setMultiChoiceItems(statusesTitles.toArray(new String[statusesTitles.size()]), null, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i, boolean b) {
if (b){
selectedStatusId.add(mStatuses.get(i).StatusId);
} else {
// TODO How I can delete my position from array?
}
}
})
.setPositiveButton(R.string.order_dialog_status_positive_button, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
refreshContent();
}
})
.setNegativeButton(R.string.order_dialog_status_negative_button, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
builder.show();
You can remove item by the following method.
ArrayList<Integer> selectedStatusId = new ArrayList<>();
if (true){
selectedStatusId.add(mStatuses.get(i).StatusId);
} else {
// delete the first occurrence of the specified element from array
selectedStatusId.remove(new Integer(mStatuses.get(i).StatusId));
}
final ArrayList<String> selectedStatusId = new ArrayList<>();
//MAKE IT STRING TYPE
final ArrayList<String> statusesTitles = new ArrayList<>();
for (int i = 0; i < mStatuses.size(); i++) {
statusesTitles.add(mStatuses.get(i).StatusTitle);
}
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.order_dialog_status_title)
.setMultiChoiceItems(statusesTitles.toArray(new String[statusesTitles.size()]), null, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i, boolean b) {
if (b) {
selectedStatusId.add(String.valueOf(mStatuses.get(i).StatusId));
} else {
// TODO How I can delete my position from array?
selectedStatusId.remove(String.valueOf(mStatuses.get(i).StatusId));
}
//OR_______________________YOU CAN USE THIS ALSO
// if (selectedStatusId.contains(String.valueOf(mStatuses.get(i).StatusId))) {
// selectedStatusId.remove(String.valueOf(mStatuses.get(i).StatusId));
// } else {
// selectedStatusId.add(String.valueOf(mStatuses.get(i).StatusId));
// }
}
})
.setPositiveButton(R.string.order_dialog_status_positive_button, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
refreshContent();
}
})
.setNegativeButton(R.string.order_dialog_status_negative_button, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
builder.show();
Hope this helps..
Related
I am implementing a simple dialog with a checked listview in it. This is what I've done so far:
CharSequence[] items = {"Brand A", "Brand B", "Brand C"};
AlertDialog.Builder builder = new AlertDialog.Builder(StrengthOfDemandsView.this);
builder.setTitle("Select Brands");
final ArrayList seletedItems=new ArrayList();
builder.setMultiChoiceItems(items, null,
new DialogInterface.OnMultiChoiceClickListener() {
// indexSelected contains the index of item (of which checkbox checked)
#Override
public void onClick(DialogInterface dialog, int indexSelected,
boolean isChecked) {
if (isChecked) {
seletedItems.add(indexSelected);
} else{
seletedItems.remove(Integer.valueOf(indexSelected));
}
}
})
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
}
});
dialog = builder.create();
dialog.show();
PROBLEM:
Initially, I'm passing an Array to setMultiChoiceItems method and it works fine but how to pass an ArrayList instead of an array? Like this:
ArrayList<Products> brandList = new ArrayList<>();
Whenever I'm trying to pass an ArrayList to setMultiChoiceItems method it gives me this error:
Cannot resolve method 'setMultiChoiceItems(java.util.ArrayList<com.application.marketvisit.dataItem.Products>, null, anonymous android.content.DialogInterface.OnMultiChoiceClickListener)'
You need to pass a String array to AlertDialog.Builder#setMultiChoiceItemsso collect it as a String array
String arr = new String[brandList.size()];
for(int i=0 ; i< brandList.size();i++){
arr[i] = brandList.get(i).getProductName();
//getProductName or any suitable method
}
Try this...and let me know if it works..
ArrayList<String> strBrandList = new ArrayList<String>();
for (int i = 0; i < brandList.size(); i++) {
strBrandList.add(brandList.get(i).getProductName())
}
am trying to add this this line in my Activity builder.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
but I find find this error Cannot resolve method'getwindow'
as am trying to add my code like this
NewGuestCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(TabsActivity.this);
builder.setTitle("Insert Table Name");
// Set up the input
final EditText input = new EditText(TabsActivity.this);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(input, InputMethodManager.SHOW_IMPLICIT);
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_CLASS_TEXT);
builder.setView(input);
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
final String Table_Name = input.getText().toString();
AlertDialog.Builder builder = new AlertDialog.Builder(TabsActivity.this);
builder.setTitle("Insert number of Covers");
// Set up the input
final EditText input2 = new EditText(TabsActivity.this);
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
input.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_CLASS_NUMBER);
builder.setView(input2);
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String Cover_check = input2.getText().toString();
TablesFragment.Check_Items = ConnectionClass.Ret_dt("Select * From ChecksItems Where Check_ID = 0");
if (!TablesFragment.Check_Items.containsKey("Change_Temp")) {
if (TablesFragment.Check_Items.size() > 0) {
ArrayList<Object> Valrows = new ArrayList<Object>();
if (TablesFragment.Check_Items.get("Item_ID").size() > 0) {
for (int i = 0; i < TablesFragment.Check_Items.get("Item_ID").size(); i++) {
Valrows.add("");
}
}
TablesFragment.Check_Items.put("Change_Temp", Valrows);
}
}
if (Integer.parseInt(Cover_check) > 0) {
String st = ConnectionClass.Ret_Col("Select Max (CheckSerail) AS Ser From Checks_V where Officer = 0 AND OutLet_ID = " + ConnectionClass.OutletID + " And Rest_ID_Active = " + ConnectionClass.Rest_ID);
if (st.trim() == "")
st = "0";
int Check_Serial = Integer.parseInt(st) + 1;
long Check_ID = Long.parseLong(ConnectionClass.SelectNewIDCheck());
st = "insert into Checks .......
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
builder.show();
as I need from this method that when the alert dialog start the keyboard starts automatically that I don't need to touch the edit text to show the key board
sorry if any thing is not clear and sorry for my bad english
I hope this case could be solved
by the way activity looks
public class TabsActivity extends AppCompatActivity {
There is a similar question on StackOverflow. You need to call getWindow() on the Dialog Class.
call getWindow() by giving any views reference.ex
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
want to validate edit text according to SQLite table data types
I have one table in my SQLite database which has three data types integer,integer,text respectively. edit texts are creates dynamically according to columns present in table. now I want to give validation on each text box like if I enter string value for integer datatype then one popup should display which shows message "can't insert text value for data type integer". so what can I do now?
here is my code
public class DisplayTable_Grid extends Activity
{
TableLayout table_layout;
SQL_crud sqlcon;
TableRow rw;
TextView gettxt_onLongclik;
ArrayList<String> storeColumnNames;
EditText enter_text;
TextView set_txt;
List<EditText> allEds = new ArrayList<EditText>();
ArrayList<String> storeallEds=new ArrayList<String>();
ArrayList<String> storeEditextText=new ArrayList<String>();
List<TextView> textViewlst = new ArrayList<TextView>();
ArrayList<String> getColumnNames=new ArrayList<String>();
ArrayList<HashMap<String, String>> arraylist = new ArrayList<HashMap<String, String>>();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.displaytable);
sqlcon = new SQL_crud(this);
table_layout = (TableLayout) findViewById(R.id.diplay_table);
BuildTable();
}
private void BuildTable()
{
sqlcon.open();
storeColumnNames=sqlcon.getColumnNames(DisaplayTables_list.getTableNameFromListView.toString());
Cursor c = sqlcon.readEntryofTable(DisaplayTables_list.getTableNameFromListView.toString());
int rows = c.getCount();
int cols = c.getColumnCount();
String colN=c.getColumnNames().toString();
arraylist=sqlcon.readColumn_Datatypes(DisaplayTables_list.getTableNameFromListView.toString ());
ArrayList<String> colName=new ArrayList<String>();
colName=sqlcon.getColumnNames(DisaplayTables_list.getTableNameFromListView.toString());
//colName.add(colN);
c.moveToFirst();
System.out.println("size of hash map:"+arraylist.size());
for(int k=0;k<1;k++)
{
TableRow rowcolumnName = new TableRow(this);
rowcolumnName.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
rowcolumnName.setBackgroundColor(Color.GRAY);
for(int a=0;a<cols/*arraylist.size()*/;a++)
{
TextView columnName = new TextView(this);
columnName.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
columnName.setGravity(Gravity.CENTER);
columnName.setTextSize(18);
columnName.setPadding(0, 5, 0, 5);
columnName.setText(colName.get(a)+" "+arraylist.get(a).toString());
rowcolumnName.addView(columnName);}
table_layout.addView(rowcolumnName);
// c.moveToNext();
}
// outer for loop
if(rows==0)
{
Toast.makeText(getApplicationContext(), "rows not found..cant build table", Toast.LENGTH_LONG);
}
else{
for (int i = 0; i < rows; i++)
{
TableRow row = new TableRow(this);
row.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
// inner for loop
for (int j = 0; j < cols; j++)
{
TextView tv = new TextView(this);
tv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
tv.setGravity(Gravity.CENTER);
tv.setTextSize(18);
tv.setPadding(0, 5, 0, 5);
tv.setText(c.getString(j));
row.addView(tv);
}
row.setClickable(true);
row.requestFocus();
row.setOnLongClickListener(new OnLongClickListener()
{
#Override
public boolean onLongClick(View viewlong)
{
rw=(TableRow) viewlong;
gettxt_onLongclik=(TextView)rw.getChildAt(0);
Toast.makeText(getApplicationContext(),gettxt_onLongclik.getText().toString(),Toast.LENGTH_SHORT).show();
final AlertDialog.Builder alertForSelectOperation=new AlertDialog.Builder(DisplayTable_Grid.this);
final LinearLayout linear=new LinearLayout(DisplayTable_Grid.this);
linear.setOrientation(LinearLayout.VERTICAL);
//TextView update=(TextView)new TextView(DisplayTable_Grid.this);
Button update=(Button)new Button(DisplayTable_Grid.this);
//update.setBackgroundColor(Color.rgb(3,12,90));
update.setText(Html.fromHtml("<font size=10>Update</font>"));
update.setOnClickListener(new OnClickListener()
{ #Override
public void onClick(View arg0)
{
final AlertDialog.Builder alertDialogOK_CANCEL=new AlertDialog.Builder(DisplayTable_Grid.this);
final LinearLayout linearlayout=new LinearLayout(DisplayTable_Grid.this);
linearlayout.setOrientation(LinearLayout.VERTICAL);
sqlcon.open();
getColumnNames=sqlcon.getColumnNames(DisaplayTables_list.getTableNameFromListView.toString());
Cursor crs=sqlcon.readColumnCnt(DisaplayTables_list.getTableNameFromListView.toString());
int count=crs.getColumnCount();
Cursor cr=sqlcon.getSinlgeEntryof_table(DisaplayTables_list.getTableNameFromListView.toString(),getColumnNames.get(0), gettxt_onLongclik.getText().toString());
cr.moveToFirst();
for(int i=0;i<count;i++)
{ //add edittext to arralist
enter_text=new EditText(DisplayTable_Grid.this);
allEds.add(enter_text);
allEds.get(i).setText(cr.getString(cr.getColumnIndex(getColumnNames.get(i))));
linearlayout.addView(enter_text);
}
sqlcon.close();
//finish();
alertDialogOK_CANCEL.setPositiveButton("Update", new DialogInterface.OnClickListener()
{ #Override
public void onClick(DialogInterface arg0, int arg1)
{
for(int i=0;i<allEds.size();i++)
{
//System.out.println(allEds.get(i).getText().toString());
storeallEds.add(allEds.get(i).getText().toString());
String getarraylist=arraylist.get(i).toString();
String datatype_text="{datatype=text}";
String datatype_integer="{datatype=integer}";
if(getarraylist.equals(datatype_text) || getarraylist.equals(datatype_integer))
{
if(getarraylist.equals(datatype_text))
{
Toast.makeText(getApplicationContext(), "text"+storeallEds.get(i),Toast.LENGTH_LONG).show();
//enter_text.setInputType(InputType.TYPE_CLASS_TEXT);
}
else if(getarraylist.equals(datatype_integer))
{
if(storeallEds.get(i).contains("a"))//allEds.get(i).getText().toString().contains("a")||allEds.get(i).getText().toString().contains("b"))
{
Toast.makeText(getApplicationContext(), "String in integer value",Toast.LENGTH_LONG).show();
//enter_text.setInputType(InputType.TYPE_CLASS_NUMBER);
}
else
{
//storeallEds.add(allEds.get(i).getText().toString());
Toast.makeText(getApplicationContext(), "integer"+storeallEds.get(i),Toast.LENGTH_LONG).show();
}
}
else
{
Toast.makeText(getApplicationContext(), "no datatype found",Toast.LENGTH_LONG).show();
}
}
}
//System.out.println(storeallEds);
sqlcon.open();
try
{
sqlcon.updateRecord(DisaplayTables_list.getTableNameFromListView.toString(), gettxt_onLongclik.getText().toString(), storeallEds);
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(),"Can't Update column already exists ",Toast.LENGTH_LONG).show();
}
Intent i=new Intent(getApplicationContext(),DisplayTable_Grid.class);
startActivity(i);
sqlcon.close();
}
});
alertDialogOK_CANCEL.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{ #Override
public void onClick(DialogInterface dialog, int arg1)
{
dialog.dismiss();
}
});
alertDialogOK_CANCEL.setView(linearlayout);
alertDialogOK_CANCEL.setTitle("insert values here");
alertDialogOK_CANCEL.create();
alertDialogOK_CANCEL.show();
}
});
//TextView delete=(TextView)new TextView(DisplayTable_Grid.this);
Button delete=(Button)new Button(DisplayTable_Grid.this);
delete.setText(Html.fromHtml("<font size=10> Delete</font>"));
//delete.setBackgroundColor(Color.rgb(3,12,90));
delete.setOnClickListener(new OnClickListener()
{ #Override
public void onClick(View arg0)
{
final AlertDialog.Builder alertDialogOK_CANCEL=new AlertDialog.Builder(DisplayTable_Grid.this);
alertDialogOK_CANCEL.setMessage("Press OK to Delete this Record");
alertDialogOK_CANCEL.setPositiveButton("OK", new DialogInterface.OnClickListener()
{ #Override
public void onClick(DialogInterface arg0, int arg1)
{
sqlcon.open();
sqlcon.deleteEntry(DisaplayTables_list.getTableNameFromListView, storeColumnNames.get(0), gettxt_onLongclik.getText().toString());
sqlcon.close();
Intent i=new Intent(getApplicationContext(),DisplayTable_Grid.class);
startActivity(i);
}
});
alertDialogOK_CANCEL.setNegativeButton("CANCEL",new DialogInterface.OnClickListener()
{ #Override
public void onClick(DialogInterface dialog, int arg1)
{
dialog.dismiss();
}
});
alertDialogOK_CANCEL.create();
alertDialogOK_CANCEL.show();
}
});
//TextView insert=(TextView)new TextView(DisplayTable_Grid.this);
Button insert=(Button)new Button(DisplayTable_Grid.this);
insert.setText(Html.fromHtml("<font size=10>Insert</font>"));
//insert.setBackgroundColor(Color.rgb(3,12,90));
insert.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
final AlertDialog.Builder alertDialog=new AlertDialog.Builder(DisplayTable_Grid.this);
final LinearLayout linearlayout=new LinearLayout(DisplayTable_Grid.this);
linearlayout.setOrientation(LinearLayout.VERTICAL);
sqlcon.open();
getColumnNames=sqlcon.getColumnNames(DisaplayTables_list.getTableNameFromListView);
Cursor crs=sqlcon.readColumnCnt(DisaplayTables_list.getTableNameFromListView);
int count=crs.getColumnCount();
for(int i=0;i<count;i++)
{ //add edittext to arralist
enter_text=new EditText(DisplayTable_Grid.this);
allEds.add(enter_text);
String getarraylist=arraylist.get(i).toString();
String datatype_text="{datatype=text}";
String datatype_integer="{datatype=integer}";
if(getarraylist.equals(datatype_text))
{
Toast.makeText(getApplicationContext(), "text",Toast.LENGTH_LONG).show();
enter_text.setInputType(InputType.TYPE_CLASS_TEXT);
}
else if(getarraylist.equals(datatype_integer))
{
Toast.makeText(getApplicationContext(), "integer",Toast.LENGTH_LONG).show();
//enter_text.setInputType(InputType.TYPE_CLASS_NUMBER);
}
else
{
Toast.makeText(getApplicationContext(), "no datatype found",Toast.LENGTH_LONG).show();
}
//add textview to ayyalist
set_txt=new TextView(DisplayTable_Grid.this);
set_txt.setText(getColumnNames.get(i));
set_txt.setTextSize(15);
textViewlst.add(set_txt);
linearlayout.addView(set_txt);
linearlayout.addView(enter_text);
}
sqlcon.close();
alertDialog.setPositiveButton("Insert", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface arg0, int arg1)
{
if(allEds.size()==0)
{Toast.makeText(getApplicationContext(), "value not found",Toast.LENGTH_LONG).show();}
else
{
for(int i=0; i < allEds.size(); i++)
{ storeEditextText.add(allEds.get(i).getText().toString());
System.out.println("show gettext: "+storeEditextText.get(i).toString());
String getarraylist=arraylist.get(i).toString();
String datatype_text="{datatype=text}";
String datatype_integer="{datatype=integer}";
if(getarraylist.equals(datatype_text))
{
Toast.makeText(getApplicationContext(), "text",Toast.LENGTH_LONG).show();
}
else if(getarraylist.equals(datatype_integer))
{
Toast.makeText(getApplicationContext(), "integer",Toast.LENGTH_LONG).show();
if(storeEditextText.contains("a")||storeEditextText.contains("b"))
{
try
{
int edittxtint=Integer.parseInt(allEds.get(i).getText().toString());//enter_text.setInputType(InputType.TYPE_CLASS_NUMBER);
}
catch(Exception e)
{
System.out.println("exception....."+e);
Toast.makeText(getApplicationContext(),"value must be an integer",Toast.LENGTH_LONG).show();
}
}
}
else
{
Toast.makeText(getApplicationContext(), "no datatype found",Toast.LENGTH_LONG).show();
}
}
if(storeEditextText.size()==0)
{Toast.makeText(getApplicationContext(), "Text is empty",Toast.LENGTH_LONG).show();}
else
{
sqlcon.open();
try
{sqlcon.insert(DisaplayTables_list.getTableNameFromListView,storeEditextText);}
catch(Exception e)
{Toast.makeText(getApplicationContext(),"emp_id is Primary key", Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(),"column value already exists",Toast.LENGTH_LONG).show();}
System.out.println("size of storeEdittext="+storeEditextText.size());
System.out.println("size of Edit Texts: "+allEds.size());
}
Intent i=new Intent(getApplicationContext(),DisplayTable_Grid.class);
startActivity(i);
sqlcon.close();
}
}
});
alertDialog.setView(linearlayout);
alertDialog.setTitle("insert values here");
alertDialog.create();
alertDialog.show();
}
});
linear.addView(insert);
linear.addView(update);
linear.addView(delete);
alertForSelectOperation.setView(linear);
alertForSelectOperation.setTitle("perform operations here");
alertForSelectOperation.create();
alertForSelectOperation.show();
alertForSelectOperation.setCancelable(true);
return false;
}
});
row.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
TableRow rw=(TableRow) v;
TextView gettxt=(TextView)rw.getChildAt(0);
Toast.makeText(getApplicationContext(), gettxt.getText().toString(),Toast.LENGTH_SHORT).show();
}
});
c.moveToNext();
table_layout.addView(row);
}
}//end of else for null rows
sqlcon.close();
}
}
You can modify your table definition and add "CHECK" constraint, like this:
CREATE TABLE tab (
column1 INTEGER CHECK(typeof(column1) == "integer"),
column2 INTEGER CHECK(typeof(column2) == "integer"),
column3 TEXT CHECK(typeof(column3) == "text")
);
This will enable your database to enforce datatype checking for this table. This will slow down the insertions/updates on this table just a bit.
I'm trying to follow the android docs about multiple selection dialog boxes. I'm having an issue, and I think it's with the type of arrays i'm trying to load in.
public void addCondition(View view){
ArrayList<String> mHelperNames= new ArrayList<String>();
mHelperNames.add("Test Item");
mHelperNames.add("Test Item");
mHelperNames.add("Test Item");
mSelectedItems = new ArrayList();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("My Title")
.setMultiChoiceItems(mHelperNames, null,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
if (isChecked) {
mSelectedItems.add(which);
} else if (mSelectedItems.contains(which)) {
mSelectedItems.remove(Integer.valueOf(which));
}
}
})
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
//Create onlcick method
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
//Create onlcick method
}
});
builder.show();
}
Above is my code, but it's red-line city in eclipse:
In the docs, mSelectedItems is never declared, and I'm not too sure what I'm declaring it as.
The error on .SetMultipleChoiceItems is:
The method setMultiChoiceItems(int, boolean[], DialogInterface.OnMultiChoiceClickListener) in the type AlertDialog.Builder is not applicable for the arguments (ArrayList, null, new DialogInterface.OnMultiChoiceClickListener(){})
But if i change it from a string, how do I show text items in it? Any help will be really appreciated.
Tom
You must provide a CharSequence[] to setMultiChoiceItems method, not an ArrayList.
You could create mHelperNames like this:
CharSequence[] mHelperNames = new CharSequence[] { "test item 1", "test item 2" };
And don't forget to declare mSelectedItems too:
final List<Integer> mSelectedItems = new ArrayList<Integer>();
(It has to be final because you access it from an inner class)
You can also keep mHelperNames as an ArrayList if you need to modify it later. Then you need to convert it to an array when calling setMultiChoiceItems:
List<CharSequence> mHelperNames = new ArrayList<CharSequence>();
mHelperNames.add("Test Item 1");
mHelperNames.add("Test Item 2");
final List<Integer> mSelectedItems = new ArrayList<Integer>();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("My Title")
.setMultiChoiceItems(mHelperNames.toArray(new CharSequence[mHelperNames.size()]), null,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which, boolean isChecked) {
if (isChecked) {
mSelectedItems.add(which);
} else if (mSelectedItems.contains(which)) {
mSelectedItems.remove(Integer
.valueOf(which));
}
}
})
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();
}
});