Combine AlertDialog with AutoCompleteText - java

So what I'm trying to do is to have an AlertDialog where the user can add their own groceries to the database. I want the program to give suggestions while the user is typing. I want to combine an AlertDialog with an AutoCompleteTextView. I followed this guide for the AutoComplete section https://developer.android.com/reference/android/widget/AutoCompleteTextView.html, but I can't seem to get it right.
In main:
public void add(View caller) {
MaterialAlertDialogBuilder mBuilder = new MaterialAlertDialogBuilder(mainActivity.this);
mBuilder.setTitle(R.string.dialog_title);
mBuilder.setView(R.layout.add_items_dialog);
mBuilder.setMessage("Enter a grocery");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, GROCERIES);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.name_text_field);
textView.setAdapter(adapter);
mBuilder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int which) {
}
});
mBuilder.setNegativeButton(R.string.dismiss_label, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
AlertDialog mDialog = mBuilder.create();
mDialog.show();
add_items_dialog.xml:
<?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="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/name_text_field"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="#dimen/dp_16"
android:layout_marginEnd="#dimen/dp_16"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:hint="#string/enter_text"
android:textColorHint="#color/colorDarkGreen"
style="#style/Widget.MaterialComponents.TextInputLayout.OutlinedBox">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/et_input"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:inputType="text"
android:singleLine="true" />
</com.google.android.material.textfield.TextInputLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Error at the line textView.setAdapter(adapter):
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.AutoCompleteTextView.setAdapter(android.widget.ListAdapter)' on a null object reference
I guess that it has something to do with setting the adapter to the wrong textview but it can also be something entirely different. Any suggestions?

You need to change mbuilder.addView(R.layout.add_itemes_dialog)
by
View view =LayoutInflater.from(this).inflate(R.layout.add_itemes_dialog, null);
builder.setView(view);
// and to find your AutoCompleteTextView
AutoCompleteTextView textView = (AutoCompleteTextView) view.findViewById(R.id.et_input);
and also in your xml file change TextInputEditText by MaterialAutoCompleteTextView and it should work

Related

How to show Cancel and Accept button in AlertDialog Android

I am having troubles setting the two buttons on the lower part of the alert what I am trying to do is get a similar look to the IOS look of the buttons.
here is my current code:
public void openInstructions() {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
final AlertDialog dialog = builder.setNegativeButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
setNewDateOnView();
dialog.cancel();
}
}).setPositiveButton("CANCEL", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
}).create();
TextView myMsg = new TextView(getActivity());
myMsg.setText("ExampleText ");
myMsg.setTextSize(15);
myMsg.setGravity(Gravity.CENTER_HORIZONTAL);
dialog.setView(myMsg);
dialog.setTitle("Confirm Date of Purchase");
dialog.setOnShowListener( new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface arg0) {
Button negativeButton = dialog.getButton(AlertDialog.BUTTON_NEGATIVE);
negativeButton.setTextColor(0xFFFF0000);
Button positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
positiveButton.setTextColor(0xFF0000FF);
}
});
dialog.show();
}
Example of how it looks right now:
How I wanted it to look:
To design Dialog like ios , we can create custom dialog using custom layout like this :
dialog_custom.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:orientation="vertical"
app:layout_constraintHeight_max="wrap">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#drawable/custom_bg">
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_below="#+id/title"
android:gravity="center"
android:text="Confirm Date of Purchase"
android:textAlignment="center"
android:textColor="#android:color/black"
android:textSize="17sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/back_ll"
android:orientation="vertical"
android:padding="5dp">
<TextView
android:id="#+id/rebooking_single_tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:textAlignment="center"
android:text="#string/dummuy"
android:textColor="#android:color/black"
android:textSize="17sp" />
</LinearLayout>
<LinearLayout
android:id="#+id/back_ll"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_below="#+id/end_time_recycle"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#8F8F8F" />
<LinearLayout
android:id="#+id/rebooking_back_button_ll"
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal"
android:gravity="center">
<TextView
android:id="#+id/ok_btn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".49"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="Ok"
android:textAlignment="center"
android:textColor="#FF6363"
android:textSize="17sp"
android:textStyle="bold" />
<View
android:layout_width="0dp"
android:layout_weight=".01"
android:layout_height="match_parent"
android:layout_below="#+id/end_time_recycle"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#8F8F8F" />
<TextView
android:id="#+id/cancel_btn"
android:layout_width="0dp"
android:layout_weight=".5"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:textAlignment="center"
android:paddingRight="10dp"
android:text="Cancle"
android:textColor="#7BC5FF"
android:textSize="17sp"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
Main_Activity
final Dialog dialog=new Dialog(FirstActivity.this);
dialog.setCancelable(false);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.setContentView(R.layout.dialog_custom);
TextView cancel_btn=dialog.findViewById(R.id.cancel_btn);
cancel_btn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
dialog.dismiss();
}
});
TextView ok_btn=dialog.findViewById(R.id.ok_btn);
ok_btn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
dialog.dismiss();
}
});
dialog.show();
Well, as a start, google recommends you use the Android Design Guidelines when creating Android apps, really you should be sticking to those as that's what your users will be used to (not Apple's).
Also there's no reason to be assigning the dialog a TextView if all you're doing is showing text, the AlertDialog provides this functionality with setMessage.
If that hasn't convinced you to stick to the normal design rules, the only other option would be creating a Custom View and assign it to the AlertDialog with setView(similar to how you're doing it with the TextView).
Here's a tutorial on creating a Custom View
You can create a custom view such as the one sent and inflate it
Example:
AlertDialog.Builder mBuilder = new AlertDialog.Builder(getActivity());
View mView=getActivity().getLayoutInflater().inflate(R.layout.custom_layout, null);
mBuilder.setView(mView);
Button close = (Button) mView.findViewById(R.id.close);
Button OK = (Button) mView.findViewById(R.id.ok);
close.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//close the dialog
hideDialog1();
}
});
OK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do something
}
});
dialog = mBuilder.create();
dialog.setCanceledOnTouchOutside(false);
dialog.show();
Use .setNeutralButton that make place left most
TextView textview;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button =(Button)findViewById(R.id.button1);
textview = (TextView)findViewById(R.id.textView1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new AlertDialog.Builder(MainActivity.this).setIcon(R.drawable.ic_launcher_background)
.setTitle("Alert Dialog Box Title")
.setMessage("Are you sure( Alert Dialog Message )")
.setPositiveButton("YES", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
Toast.makeText(MainActivity.this, "You Clicked on Yes", Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
Toast.makeText(MainActivity.this, "You Clicked on Cancel", Toast.LENGTH_SHORT).show();
}
})
.setNeutralButton("NO", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
Toast.makeText(MainActivity.this, "You Clicked on NO", Toast.LENGTH_SHORT).show();
}
})
.show();
}
});
}
===============================================

How to insert a text from an EditText into a database?

I'm trying to get the text from editText and input it into my database. The problem I am having is a NullPointerException once i try to submit the text. Any help would be appreciated.
ERROR:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
This is from my MainActivity:
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.action_add_task:
final EditText text = (EditText)findViewById(R.id.editText);
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle("Add New Task")
.setMessage("what do you want to do next")
.setView(R.layout.custom_view)
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String task;
task = text.getText().toString();
dbHelper.insertNewTask(task);
if(getFragmentRefreshListener()!=null) {
getFragmentRefreshListener().onRefresh();
}
loadTaskList();
}
})
.setNegativeButton("Cancel",null)
.create();
dialog.show();
return true;
}
return super.onOptionsItemSelected(item);
}
my custom_view.xml:
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter a task"
android:id="#+id/editText" />
my activity_main.xml:
<android.support.design.widget.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tablayout"
android:background="#color/colorPrimaryDark"
android:minHeight="?attr/actionBarSize"
>
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:backgroundTint="#android:color/darker_gray"
android:visibility="visible">
<ListView
android:id="#+id/lstTask"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:text="#string/tasks"
android:textSize="30sp" />
</android.support.v4.view.ViewPager>
Well since I cant see the xml for MainActivity layout, here it's what most likely it's causing the NPE.
final EditText text = (EditText)findViewById(R.id.editText);
Your searching your edit text in you activity view hierarchy when (assuming from what is shown in the Dialog creation) you should be searching it in the Dialog view hierarchy.
.setView(R.layout.custom_view)
There you are setting that view as the view of the dialog and thats probably what is causing the exception. Try fining the reference to the edit text in the onClick method like this:
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle("Add New Task")
.setMessage("what do you want to do next")
.setView(R.layout.custom_view)
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
final EditText text = ((AlertDialog)dialog).findViewById(R.id.editText);
String task;
task = text.getText().toString();
dbHelper.insertNewTask(task);
if(getFragmentRefreshListener()!=null) {
getFragmentRefreshListener().onRefresh();
}
loadTaskList();
}
})
.setNegativeButton("Cancel",null)
.create();
dialog.show();
Here is what fixed my problem:
I changed this line:
final EditText text = ((AlertDialog)dialog).findViewById(R.id.editText);
To this:
final EditText text = (EditText) ((AlertDialog)dialog).findViewById(R.id.editText);

I have set onItemLongClickListener to my listview but upon clicking on the list item, nothing happens. How can i fix this?

I am taking data from my database using and want to set that as my list item. Upon clicking and holding an item, I want a dialog to open prompting the user to select one of the given options. My code is as follows:
My MainActivity.java class
public class MainActivity extends AppCompatActivity {
ListView todoList;
DbHelper dbHelper;
ArrayAdapter<String> myAdapter;
Button rename, delete;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHelper=new DbHelper(this);
todoList=(ListView)findViewById(R.id.to_do);
loadTaskList();
todoList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int i, long l) {
Dialog dialog=new Dialog(MainActivity.this);
dialog.setContentView(R.layout.item_dialog);
dialog.setTitle("Select");
rename = dialog.findViewById(R.id.rename_task);
delete = dialog.findViewById(R.id.delete_task);
dialog.show();
return false;
}
});
}
private void loadTaskList() {
ArrayList<String> taskList=dbHelper.getTask();
if(myAdapter==null){
myAdapter=new ArrayAdapter<String>(this,R.layout.todo_item,R.id.task_title,taskList);
todoList.setAdapter(myAdapter);
}else {
myAdapter.clear();
myAdapter.addAll(taskList);
myAdapter.notifyDataSetChanged();
}
}
My activity_main.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.mylist.MainActivity">
<ListView
android:id="#+id/to_do"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp"/>
</LinearLayout>
My Layout for the list item:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true">
<TextView
android:id="#+id/task_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Task"
android:textSize="20sp"
android:layout_centerVertical="true"
android:padding="5dp"/>
<ImageButton
android:id="#+id/task_delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:src="#drawable/ic_delete_black_24dp" />
<ImageButton
android:id="#+id/task_done"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_done_black_24dp"
android:layout_toLeftOf="#id/task_delete"/>
</RelativeLayout>
Try like this;
todoList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Dialog dialog=new Dialog(MainActivity.this);
dialog.setContentView(R.layout.item_dialog);
dialog.setTitle("Select");
rename = dialog.findViewById(R.id.rename_task);
delete = dialog.findViewById(R.id.delete_task);
dialog.show();
}
});
To detect that an item is clicked, you custom adapter must know which one so you should add this in your adapter class.
public ItemClicked getItem(int position){
return items.get(position);
}
I think returning true from your OnItemLongClick() method rather than false should work.
You are saying that you are trying to do onItemClickListener.
But you have written onItemLongClickListner.

Customize alertdialog android api 10

I would like to know how to customize theme/style of AlertDialog using sdk api 10. I know how to do that from 11 onwards but not how to do it on the 10.
XML Layout file
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/scrollView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
style="#style/dialog_theme" >
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/disclaimerText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/disclaimer"
android:padding="5dp"/>
<CheckBox
android:id="#+id/checkDisclaimer"
style="?android:attr/textAppearanceMedium"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="#string/agree" />
</LinearLayout>
</ScrollView>
JAVA Resource file
AlertDialog.Builder builder = new AlertDialog.Builder(this);
//Setting Dialog Title
builder.setTitle("Disclaimer");
//Setting Dialog Message
builder.setMessage(R.string.disclaimer);
View view = (View) LayoutInflater.from(this).inflate(R.layout.layout_disclaimer, null);
builder.setView(view);
You could try this:
View myView = View.inflate(this, R.layout.customize_dialog, null);
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setView(myView);
builder.setTitle("Customize dialog");
builder.setCancelable(false);
AlertDialog alert=builder.create();
alert.show();
You have to create a layout in res/layout/ called customize_dialog.xml,
you can also add to "myView" other view object.
To add tipical Alert button:
builder.setPositiveButton("Ok",new OnClickListener(){
public void onClick(DialogInterface dialog, int id){
//action to do
dialog.dismiss();
}
});
builder.setNegativeButton("Close",new OnClickListener(){
public void onClick(DialogInterface dialog, int id){
//action to do
dialog.dismiss();
}
});
I hope it helps you.

Android ListView and EditView on AlertDialog crash

I test my application on debug and crash on this line:
listAdapter = new ArrayAdapter<String>(this, R.layout.cd_edittext_for_listview, planetList);
with this error:
System services not available to Activities before onCreate()
I solved this error whit this code (change this with context):
listAdapter = new ArrayAdapter(promptsView.getContext(), R.layout.cd_edittext_for_listview, planetList);
And change on XML file "EditView" with "EditText"!*
I have this layout for the items "editText_for_listview.xml":
<EditView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rowEditView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textSize="16sp">
</EditView>
And my main layout "items_listview.xml"
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginTop="10dp"
xmlns:android="http://schemas.android.com/apk/res/android">
<ListView
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/mylistview"
android:layout_gravity="center" />
</LinearLayout>
The code is this:
public void _ShowItems(String sTitle,android.content.Context context) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(sTitle);
LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
final View promptsView = inflater.inflate(R.layout.items_listview, null);
ListView mainListView ;
ArrayAdapter<String> listAdapter ;
mainListView = (ListView) promptsView.findViewById( R.id.editText_for_listview );
String[] planets = new String[] { "Test1", "Test2", "Test3" };
ArrayList<String> planetList = new ArrayList<String>();
planetList.addAll( Arrays.asList(planets) );
listAdapter = new ArrayAdapter<String>(this, R.layout.cd_edittext_for_listview, planetList);
// Set the ArrayAdapter as the ListView's adapter.
mainListView.setAdapter( listAdapter );
builder.setView(promptsView)
.setPositiveButton("One", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton("Two", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder.show();
}
Can you help me?
Where I wrong?
Thanks
Obviously you are trying to use the Activity Context prior to the Activity's onCreate() method being called. Try moving your call to _ShowItems() to onResume() method.
Could you show up more code of your activity. You could just be calling the method in a spot where the context isn't initialized but something else could be going on that will be revealed once we have a better look at the activity.
I would have made this a comment but I don't have the reputation to do so.

Categories