how can i make a confirm dialog? - java

I have created a todo app in android studio. when you click on the list of task item, it deletes itself. but i want to show a confirm dialog before that.i am using two java classes. MainActivity and Filehelper for this todo app.
so i used this code to delete the item and it was working:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
items.remove(position);
adapter.notifyDataSetChanged();
Toast.makeText(this, "Deleted", Toast.LENGTH_SHORT).show();
}
And now i am using this code with confirm dialog :
#Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Confirm dialog demo !");
builder.setMessage("You are about to delete all records of database. Do you really want to proceed ?");
builder.setCancelable(false);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface parent, int position) {
items.remove(position);
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "You've changed your mind to delete tasks", Toast.LENGTH_SHORT).show();
}
});
builder.show();
}
but when i run it on my android . i see the dialog. but when i press yes it crash itself. so can you give me the right code. and also tell me the problem of my code?.
MainActivity Code:
public class MainActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemClickListener {
private EditText ItemET;
private Button btn;
private ListView itemList;
private ArrayList<String> items;
private ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ItemET = findViewById(R.id.item_edit_text);
btn = findViewById(R.id.add_btn);
itemList = findViewById(R.id.item_list);
items = FileHelper.readData(this);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, items);
itemList.setAdapter(adapter);
btn.setOnClickListener(this);
itemList.setOnItemClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.add_btn:
String ItemEntered = ItemET.getText().toString();
if (ItemEntered.trim().isEmpty()) {
Toast.makeText(getApplicationContext(), "Please Enter some detail", Toast.LENGTH_LONG).show();
} else {
adapter.add(ItemEntered);
ItemET.setText("");
FileHelper.writeData(items, this);
Toast.makeText(this, "item Added", Toast.LENGTH_SHORT).show();
}
break;
}
}
// Confirm box
#Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Confirm dialog demo !");
builder.setMessage("You are about to delete all records of database. Do you really want to proceed ?");
builder.setCancelable(false);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface parent, int position) {
items.remove(position);
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "You've changed your mind to delete all records", Toast.LENGTH_SHORT).show();
}
});
builder.show();
}
}
FileHelper Code :
public class FileHelper {
public static final String FILENAME = "listinfo.dat";
public static void writeData(ArrayList<String> items, Context context){
try {
FileOutputStream fos = context.openFileOutput(FILENAME, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(items);
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static ArrayList<String> readData(Context context) {
ArrayList<String> itemList = null;
try {
FileInputStream fis = context.openFileInput(FILENAME);
ObjectInputStream ois = new ObjectInputStream(fis);
itemList = (ArrayList<String>) ois.readObject();
} catch (FileNotFoundException e) {
itemList = new ArrayList<>();
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return itemList;
}
}
here is also my MainActivity.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_marginTop="12dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginBottom="12dp"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="#+id/item_edit_text"
android:hint="Enter Item"
android:layout_width="0dp"
android:layout_weight="1.9"
android:layout_marginRight="20dp"
android:layout_height="wrap_content" />
<Button
android:background="#drawable/layout_bg"
android:id="#+id/add_btn"
android:text="add"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"/>
</LinearLayout>
<ListView
android:background="#drawable/layout_bg"
android:id="#+id/item_list"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:textAlignment="center"
android:layout_marginBottom="24dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

You can create a method and call it whenever you need it
void confirmDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Discard Data!");// Dialog header
builder.setMessage("Are you sure you want to discard this data?"); //disclaimer text
// yes button
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
edit_text.getText().clear(); //clear EditText
}
});
//No button
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.create().show();
}

Send the logcat picture please. Then it will be easier to identify the problem. Also check
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface parent, int position) {
Toast.makeText(getApplicationContext(), "Check if toast is working or crush. ", Toast.LENGTH_SHORT).show();
}
});
Check toast working when "Yes" button pressed or crushed. Then you will be more sure about the problem.

Related

findViewById respond "none"

I'm trying to getText() from EditText view in an AlertDialog.
In the main activity in the method onCreate() I set the button listener.
public class MainActivity2 extends AppCompatActivity {
private ActivityMain2Binding mainActivity2;
private ArrayAdapter adapter;
private ArrayList<simpleArrayAdapterElement> data;
private final static String KEY_TITLE = "title";
private final static String KEY_DESCRIPTION = "description";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mainActivity2 = ActivityMain2Binding.inflate(getLayoutInflater());
View view = mainActivity2.getRoot();
setContentView(view);
arrayAdapter();
mainActivity2.buttonIddItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showCustomDialog();
}
});
// setupListViewSimple();
}
Then I call the showCustomDialog() in onClick.
private void showCustomDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(R.layout.custom_dialog);
builder.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
EditText alertDialogText = (EditText) findViewById(R.id.setText1);
System.out.println(alertDialogText.getText());
System.out.println(alertDialogText.getText().toString()); // just in case
}
});
builder.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
EditText alertDialogText = (EditText) findViewById(R.id.setText1); // return none
Here is my layout:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto">
<EditText
android:id="#+id/setText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:ignore="MissingConstraints"
android:layout_marginTop="16dp"
android:hint="Type your name here:"
android:text="Some"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
*I also use binding in my activity.
What I'm doing wrong?
You are referring to MainActivity2 itself. you need to refer to its view by using LayoutInflater. You can check example answer here: https://stackoverflow.com/a/36793463/9346054
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.custom_dialog, null);
builder.setView(dialogView);
builder.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
EditText alertDialogText = dialogView.findViewById(R.id.setText1);
System.out.println(alertDialogText.getText());
System.out.println(alertDialogText.getText().toString()); // just in case
}
});
builder.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});

Listview in alertDialog, positioning listview where I want it is where I'm stuck

I have an alertDialog that is read by multiple fragments or activities, on one instance the alert dialog is going to show a listView with 2 editText options plus the standard positive and negative button presses, I want to position the listView after the editTexts and I'm stuck.
Everything displays properly but positioning is where I'm stuck.
Dialog class
public class addTaskDialog extends DialogFragment {
String mString;
taskDialogListener listener;
ArrayList<String> tradeTitles;
/*
* Class interface from jobRoomDetails, interfaces are called from the parent activity class
*/
public interface taskDialogListener {
void onDialogPositiveClick(DialogFragment dialog);
void onDialogNegativeClick(DialogFragment dialog);
void onDialogListSelect();
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
try{
listener = (taskDialogListener) context;
} catch(ClassCastException e) {
throw new ClassCastException(getActivity().toString() + "must implement taskDialogListener");
}
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
AlertDialog alert = builder.create();
mString = getArguments().getString("title");
tradeTitles = getArguments().getStringArrayList("tradeTitleArray");
builder.setTitle(mString);
//Inflate the layout dialog_add_task.xml
LayoutInflater inflater = requireActivity().getLayoutInflater();
//Pattern matcher for literal strings from different addTaskDialog calls
Pattern p = Pattern.compile("Add new task +");
Matcher m = p.matcher(mString);
Pattern q = Pattern.compile("Add Task +");
Matcher n = q.matcher(mString);
/*
*Test for new task and add trade names, this means that the calling window is jobRoomDetails and this is a new task
* and it will be assigned to a trade upon creation
*/
if(m.find()){
Log.d("Line: 56","Test for trade name" + tradeTitles.toString());
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.select_dialog_singlechoice, tradeTitles);
//ListView list = (ListView) alert.findViewById(R.id.tradeItems);
builder.setView(inflater.inflate(R.layout.dialog_add_task, null))
.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Save the new task to task hashmap
listener.onDialogPositiveClick(addTaskDialog.this);
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Cancel operation and return
listener.onDialogNegativeClick(addTaskDialog.this);
}
})
.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
}
});
} else if (n.find()){
builder.setView(inflater.inflate(R.layout.dialog_add_task, null))
.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Save the new task to task hashmap
listener.onDialogPositiveClick(addTaskDialog.this);
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Cancel operation and return
listener.onDialogNegativeClick(addTaskDialog.this);
}
});
} else {
builder.setView(inflater.inflate(R.layout.dialog_add_task, null))
.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Save the new task to task hashmap
listener.onDialogPositiveClick(addTaskDialog.this);
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Cancel operation and return
listener.onDialogNegativeClick(addTaskDialog.this);
}
});
}
return builder.create();
}
}
dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical">
<TextView
style="#style/textBox"
android:layout_margin="20dp"
android:layout_marginTop="5dp"
android:text="#string/add_task_ex"/>
<EditText
android:id="#+id/taskNameEditText"
style="#style/editTextBox"
android:hint="#string/add_task_name"
android:inputType="text"/>
<EditText
android:id="#+id/taskCost"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="0"
android:textSize="25sp"
android:inputType="numberDecimal"/>
<FrameLayout
android:id="#+id/tradeListItems"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ListView
android:id="#+id/tradeItems"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</FrameLayout>
</LinearLayout>
</androidx.appcompat.widget.LinearLayoutCompat>
At one point I tried to add it via a listView but to no success, I think the return type on the onCreateDialog might be hindering things but I'm not sure, I think the return type is necessary because I'm bringing through arguments but I could be wrong. As always help is appreciated.
Simple answer is create your own Alert dialog, you can simply make a fragment that looks and acts similar to an alert dialog but with far more functionality.

Buttons disappear from DialogFragment when the displayed list requires scrolling

AlertDialog displays the content and buttons perfectly until the contents grow to the point that scrolling is required to display it all. At that point the buttons disappear, even though the list shows in its entirety.
I see that in years gone by this question was asked (this one is essentially identical to mine (DialogFragment buttons pushed off screen API 24 and above), but the answers all seemed hit or miss, haphazard even: setting layout_weight, switching from setMessage() to setTitle(), and finally switching away from AlertDialog to Dialog.
None of these are working form me, and avoiding AlertDialog is NOT an appealing option because I am using the setMultiChoiceItems() method that seems (incredibly to me, perhaps given my extremely limited knowledge) available only to AlertDialog.
Thus in desperation and frustration I appeal directly to the collective brains of stackoverflow.
This is a pared down version of my DialogFragment:
public class SurfaceDialog extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = requireActivity().getLayoutInflater();
builder.setView(inflater.inflate(R.layout.surface_dialog, null))
.setTitle(mMessage)
.setMultiChoiceItems(mSurfaceList, mCheckedSurfaces, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked) {
mCheckedSurfacesPositions.add(which);
} else {
mCheckedSurfacesPositions.remove(mCheckedSurfacesPositions.indexOf(which));
}
}
});
// builder.setCancelable(false);
builder.setPositiveButton("Done", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ProcessDialogSelections(mCheckedSurfacesPositions);
dismiss();
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
listener.onSurfaceDialogSelectedSent(mUnitSurfaces);
dismiss();
}
});
return builder.create();
}
That not working, I then coded my own buttons and displayed them:
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = requireActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.surface_dialog, null);
builder.setView(dialogView)
.setTitle(mMessage)
.setMultiChoiceItems(mSurfaceList, mCheckedSurfaces, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked) {
mCheckedSurfacesPositions.add(which);
} else {
mCheckedSurfacesPositions.remove(mCheckedSurfacesPositions.indexOf(which));
}
}
});
Button positiveButton = dialogView.findViewById(R.id.positive_button);
Button negativeButton = dialogView.findViewById(R.id.negative_button);
positiveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ProcessDialogSelections(mCheckedSurfacesPositions);
dismiss();
}
});
negativeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onSurfaceDialogSelectedSent(mUnitSurfaces);
dismiss();
}
});
return builder.create();
}
and here is my revised XML file
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
android:orientation="vertical">
</ScrollView>
<Button
android:id="#+id/positive_button"
android:layout_height="wrap_content"
android:layout_marginBottom="30dp"
android:layout_width="wrap_content"
android:text="Done"
app:layout_constraintBaseline_toBaselineOf="#+id/negative_button"
app:layout_constraintEnd_toStartOf="#+id/negative_button"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="#+id/negative_button"
android:layout_height="wrap_content"
android:layout_marginBottom="30dp"
android:layout_width="wrap_content"
android:text="Cancel"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/positive_button" />
</androidx.constraintlayout.widget.ConstraintLayout>
And with THAT not working, I then followed the advice of Vikas Singh (AlertDialog Buttons not visible when using Custom layout). This is what the new code looks like (essentially creating the layout in Java rather than XML.
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// New code from Vikas Singh
LinearLayout rootLayout = new LinearLayout(getActivity());
rootLayout.setOrientation(LinearLayout.VERTICAL);
ScrollView scrollView = new ScrollView(getActivity());
LinearLayout layout = new LinearLayout(getActivity());
layout.setOrientation(LinearLayout.VERTICAL);
scrollView.addView(layout);
rootLayout.addView(scrollView);
builder.setNegativeButton("Cancel", null);
builder.setPositiveButton("Go", null);
builder.setView(rootLayout);
builder//.setView(dialogView)
//.setTitle(mMessage)
.setMultiChoiceItems(mSurfaceList, mCheckedSurfaces, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked) {
mCheckedSurfacesPositions.add(which);
} else {
mCheckedSurfacesPositions.remove(mCheckedSurfacesPositions.indexOf(which));
}
}
});
return builder.create();
}
Still no buttons when I have to scroll.
Why not and what can I do about it?
Here is the solution:
public class SurfaceDialog extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
//LayoutInflater inflater = requireActivity().getLayoutInflater();
builder
//.setView(inflater.inflate(R.layout.surface_dialog, null)) didn't work
// nor did setView with android.R.layout.select_dialog_multichoice
// nor android.R.layout.simple_list_item_multiple_choice work
.setTitle(mMessage)
.setMultiChoiceItems(mSurfaceList, mCheckedSurfaces, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked) {
mCheckedSurfacesPositions.add(which);
} else {
mCheckedSurfacesPositions.remove(mCheckedSurfacesPositions.indexOf(which));
}
}
});
// builder.setCancelable(false);
builder.setPositiveButton("Done", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ProcessDialogSelections(mCheckedSurfacesPositions);
dismiss();
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
listener.onSurfaceDialogSelectedSent(mUnitSurfaces);
dismiss();
}
});
return builder.create();
}
The multiChoiceItems DialogFragment now works like a charm!
All I had to do was simply comment out the above lines.
As a result, there is no layout explicitly inflated, no view set.
But it works nonetheless.
Now I would love it if someone could explain to me
the details of why this works,
why the other did not, and
in light of the earlier failure, how could a custom layout be implemented to achieve this result of not losing the action buttons when the view scrolled

How Do I Remove Selected Item From ArrayList and ArrayAdapter On Button Click?

I have ListView with a custom list layout. I am using an ArrayList and ArrayAdapter for this. I am having a difficult time removing selected items from the arraylist. I am not sure want I am doing wrong. Here's an example of a arraylist that I have:
Item A
Item B
Item C
Item D
Let's say that I selected Item C next on button clicked labeled "Remove" I want Item C removed from the list. How do I accomplish this? Currently my code only removes the item on index 0. I want selected item index to be removed.
Here's my codes...
Java Class:
public class MainActivity extends AppCompatActivity {
ListView lstVw;
Button addBtn, removeBtn, clearListBtn;
ArrayList<String> arrayList;
ArrayAdapter<String> adapter;
int getPosition = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lstVw = findViewById(R.id.lstView);
addBtn = findViewById(R.id.add_item_btn);
removeBtn = findViewById(R.id.remove_item_btn);
clearListBtn = findViewById(R.id.clear_list_btn);
arrayList = new ArrayList<>();
adapter = new ArrayAdapter<>(getApplicationContext(), R.layout.item_list, R.id.item_tv, arrayList);
lstVw.setAdapter(adapter);
lstVw.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String getItem = adapter.getItem(position);
getPosition = Integer.parseInt(getItem);
}
});
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder adb = new AlertDialog.Builder(MainActivity.this);
adb.setTitle("Enter Item Name");
final EditText itemTxt = new EditText(MainActivity.this);
itemTxt.setText(getString(R.string.default_item_name_value));
itemTxt.setInputType(InputType.TYPE_CLASS_TEXT);
adb.setView(itemTxt);
adb.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String getItem = itemTxt.getText().toString();
Set<String> s = new LinkedHashSet<>(arrayList);
if (s.contains(getItem)) {
arrayList.clear();
arrayList.addAll(s);
Toast.makeText(getApplicationContext(), getItem + " already exists in the list!", Toast.LENGTH_LONG).show();
} else {
arrayList.add(getItem);
adapter.notifyDataSetChanged();
}
}
});
adb.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
adb.create();
adb.show();
}
});
clearListBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!arrayList.isEmpty()) {
arrayList.clear();
adapter.notifyDataSetChanged();
}
}
});
removeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String getItem = arrayList.get(getPosition);
arrayList.remove(getItem);
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), getItem + " is removed!", Toast.LENGTH_LONG).show();
}
});
}
}
Main XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/rl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<ScrollView
android:layout_width="match_parent"
android:layout_height="650dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="650dp">
<ListView
android:id="#+id/lstView"
android:layout_width="match_parent"
android:layout_height="650dp"
tools:ignore="NestedScrolling" />
</RelativeLayout>
</ScrollView>
<include layout="#layout/action_buttons"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"/>
Action Buttons XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_gravity="center|top">
<Button
android:id="#+id/add_item_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:textAllCaps="false"
android:text="#string/add_item_text"
android:textSize="14sp"
android:textStyle="bold"
android:textColor="#android:color/black"/>
<Button
android:id="#+id/remove_item_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_toEndOf="#id/add_item_btn"
android:textAllCaps="false"
android:text="Remove Item"
android:textColor="#android:color/black"
android:textSize="14sp"
android:textStyle="bold"/>
<Button
android:id="#+id/clear_list_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_toEndOf="#id/remove_item_btn"
android:textAllCaps="false"
android:text="#string/clear_list_text"
android:textSize="14sp"
android:textStyle="bold"
android:textColor="#android:color/black"/>
My Custom List Layout XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/item_tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="20sp"
android:textColor="#android:color/black"/>
</ScrollView>
I appreciate the help! Thanks!
removeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String getItem = arrayList.get(getPosition);
arrayList.remove(getItem);
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), getItem + " is removed!", Toast.LENGTH_LONG).show();
}
});
From where are you getting this getPosition?
It looks to me like your int getPosition = 0; variable is not getting updated with your new position. On your click listener you are trying to parse the value of your selected item to an Integer, maybe you could try simply updating with the current position instead?
lstVw.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
getPosition = position;
}
});
Edit:
You could go with something like this:
Create an interface that your activity will implement and will be used by your adapter to notify a position change:
public interface PositionChangeListener {
void onPositionChanged(int newPosition);
}
Create a custom adapter:
public class CustomAdapterView extends BaseAdapter {
private Context context;
private PositionChangeListener listener;
private ArrayList<String> items;
public CustomAdapterView(Context context, ArrayList<String> items, PositionChangeListener listener) {
this.context = context;
this.items = items;
this.listener = listener;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate( R.layout.item_list, null);
viewHolder = new ViewHolder();
viewHolder.txt = convertView.findViewById(R.id.item_tv);
viewHolder.txt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listener.onPositionChanged(position);
}
});
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.txt.setText(items.get(position));
return convertView;
}
private class ViewHolder {
TextView txt;
}
}
And now in your activity:
public class MainActivity extends AppCompatActivity implements PositionChangeListener{
ListView lstVw;
Button addBtn, removeBtn, clearListBtn;
ArrayList<String> arrayList;
BaseAdapter adapter;
int getPosition = 0;
#Override
public void onPositionChanged(int newPosition) {
getPosition = newPosition;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lstVw = findViewById(R.id.lstView);
addBtn = findViewById(R.id.add_item_btn);
removeBtn = findViewById(R.id.remove_item_btn);
clearListBtn = findViewById(R.id.clear_list_btn);
arrayList = new ArrayList<>();
adapter = new CustomAdapterView(this, arrayList, this);
lstVw.setAdapter(adapter);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder adb = new AlertDialog.Builder(MainActivity.this);
adb.setTitle("Enter Item Name");
final EditText itemTxt = new EditText(MainActivity.this);
itemTxt.setText("default item name");
itemTxt.setInputType(InputType.TYPE_CLASS_TEXT);
adb.setView(itemTxt);
adb.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String getItem = itemTxt.getText().toString();
Set<String> s = new LinkedHashSet<>(arrayList);
if (s.contains(getItem)) {
arrayList.clear();
arrayList.addAll(s);
Toast.makeText(getApplicationContext(), getItem + " already exists in the list!", Toast.LENGTH_LONG).show();
} else {
arrayList.add(getItem);
adapter.notifyDataSetChanged();
}
}
});
adb.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
adb.create();
adb.show();
}
});
clearListBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!arrayList.isEmpty()) {
arrayList.clear();
adapter.notifyDataSetChanged();
}
}
});
removeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String getItem = arrayList.get(getPosition);
arrayList.remove(getItem);
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), getItem + " is removed!", Toast.LENGTH_LONG).show();
}
});
}
}

In an AlertDialog, how to set the image on the top

I am working on a coding exercise,which is about AlertDialog. In the Dialog, I hope the image or view can be placed on the top of the dialog,like a header,but it goes to the bottom.
The XML code:
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/star"/>
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:text=" choose your sex"
android:gravity="center_vertical"/>
Activity code:
private void showSingleDialog() {
LayoutInflater factory = LayoutInflater.from(this);
final View view = factory.inflate(R.layout.activity_solo, null);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(view);
final String[] sex = {
"male",
"felmale",
"unknow",
"guess"
};
builder.setSingleChoiceItems(sex, 0, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
Toast.makeText(MainActivity.this, "your choice is:" + sex[i], Toast.LENGTH_LONG).show();
dialog.dismiss();
}
});
builder.show();
}
I tried to place the builder.setView(view) in different place, it still go to the bottom.
Is there any hints for me? Thanks a lot
p.s Sorry for my poor English, I attached the image hereMy Result
I hope the little Star and "choose your sex" go on the top
Alternatively you can achieve the same view with drawable and title methods:
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final String[] array = {"male","felmale","unknow","guess"};
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setIcon(R.drawable.ic_star);
builder.setTitle("Choose your sex")
.setSingleChoiceItems(array, -1, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
sex = array[i];
//handle on click
}
});
return builder.create();
}
I achieved the same view like this:

Categories

Resources