DialogFragments for users to enter data - android

I've been trying to make a dialogFragment for my app but it's proving to be quite hard to do with a lack of examples available on the internet. Below is an image of something similar that I'd want.
Having a similar design to the image above would be great. I'm not sure if what I'm doing is correct and so far this is what I have done.
I don't know how to lay out the dialogFragment like the way it has been done for the first picture and I'm not sure how to get fields where my users can enter data to. Below is the code I currently have.
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.*;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class Reminders extends Activity
{
Button add, edit, remove;
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.reminders);
initializeVariables();
add.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog();
}
});
List<ListViewItem> items = new ArrayList<Reminders.ListViewItem>();
items.add(new ListViewItem()
{
{
ThumbnailResource = R.drawable.ic_launcher;
Title = "Item1 Title";
Date = "Item1 Date";
Time = "Item1 Time";
Amount = "£0.00";
}
});
items.add(new ListViewItem()
{
{
ThumbnailResource = R.drawable.ic_launcher;
Title = "Item2 Title";
Date = "Item2 Date";
Time = "Item2 Time";
Amount = "£0.00";
}
});
CustomListViewAdapter adapter = new CustomListViewAdapter(this, items);
lv.setAdapter(adapter);
}
private void initializeVariables()
{
add = (Button) findViewById(R.id.bAdd);
edit = (Button) findViewById(R.id.bEdit);
remove = (Button) findViewById(R.id.bRemove);
lv = (ListView) findViewById(R.id.LVReminder);
}
class ListViewItem
{
public int ThumbnailResource;
public String Title;
public String Date;
public String Time;
public String Amount;
}
void showDialog() {
DialogFragment newFragment = MyAlertDialogFragment
.newInstance(R.string.dialog_title);
newFragment.show(getFragmentManager(), "New");
}
public void doPositiveClick() {
// Do stuff here.
Log.i("FragmentAlertDialog", "Positive click!");
}
public void doNegativeClick() {
// Do stuff here.
Log.i("FragmentAlertDialog", "Negative click!");
}
public static class MyAlertDialogFragment extends DialogFragment
{
public static MyAlertDialogFragment newInstance(int title)
{
MyAlertDialogFragment frag = new MyAlertDialogFragment();
Bundle args = new Bundle();
args.putInt("title", title);
frag.setArguments(args);
return frag;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
int title = getArguments().getInt("title");
return new AlertDialog.Builder(getActivity())
.setIcon(R.drawable.ic_launcher)
.setTitle(title)
.setPositiveButton(R.string.alert_dialog_ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
((Reminders) getActivity())
.doPositiveClick();
}
})
.setNegativeButton(R.string.alert_dialog_cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
((Reminders) getActivity())
.doNegativeClick();
}
}).create();
}
}
}
I'd appreciate any advice on how to get a DialogFragment like the one in the first pic I provided. Thanks to anyone who tries to help me with this.

You can create the layout that you wish to achieve via XML document. Then from there you could change your onCreateDialog as follows:
#Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
int title = getArguments().getInt("title");
LayoutInflater inflater = getActivity().getLayoutInflater();
View v = inflater.inflate(R.layout.my_dialog_layout, null);
return new AlertDialog.Builder(getActivity())
.setView(v)
.setIcon(R.drawable.ic_launcher)
.setTitle(title)
.setPositiveButton(R.string.alert_dialog_ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
((Reminders) getActivity())
.doPositiveClick();
}
})
.setNegativeButton(R.string.alert_dialog_cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
((Reminders) getActivity())
.doNegativeClick();
}
}).create();
}
}

It seems more to me that that 'dialog' is an activity with a dialog theme, try this:
<activity android:theme="#android:style/Theme.Dialog">

I wouldn't recommend creating the layout you've supplied as it's too complex for mobile. But a simplified version with 1 option per line could be created.
You can see all supported Buttons, options, etc supported for AlertDialog.Builder in the official docs.
As #TronicZomB pointed out, you can use your own XML layout with setView(View view).

Related

Cast Dialog to AlertDialog

I had the exact same code in antoher project, but it continues to crash here. I have implementation 'com.android.support:design:26.1.0' in my gradle. I'm really unsure of what the problem is. I've tried switching the gradle version, changing from v7 Dialog to the app Dialog. All fails regardless
java.lang.ClassCastException: android.app.Dialog cannot be cast to android.support.v7.app.AlertDialog
at com.example.weather.CreateCityDialog.onResume(CreateCityDialog.java:58)
import android.app.Dialog;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v4.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class CreateCityDialog extends DialogFragment {
public interface NewCityHandler {
void onNewCityCreated(String cityName);
}
private NewCityHandler newCityHandler;
private EditText etName;
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof NewCityHandler)
newCityHandler = (NewCityHandler) context;
else
throw new RuntimeException("Error");
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Add new city");
View rootView = getActivity().getLayoutInflater().inflate(R.layout.activity_create_city_dialog, null);
etName = rootView.findViewById(R.id.etName);
builder.setView(rootView);
builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
return super.onCreateDialog(savedInstanceState);
}
#Override
public void onResume() {
super.onResume();
final AlertDialog d = (AlertDialog) getDialog();
if (d != null) {
Button positiveButton = d.getButton(Dialog.BUTTON_POSITIVE);
positiveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!TextUtils.isEmpty(etName.getText())) {
newCityHandler.onNewCityCreated(etName.getText().toString());
d.dismiss();
} else {
etName.setError("Empty field");
}
}
});
}
}
}
You have to return AlertDialog from onCreateDialog().
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Add new city");
View rootView = getActivity().getLayoutInflater().inflate(R.layout.activity_create_city_dialog, null);
etName = rootView.findViewById(R.id.etName);
builder.setView(rootView);
builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
return builder.create();
}

I want to display data from AlertDialog with an editText and then display it to a list view it'snot working, this is my code

package com.example.riplee07.trydialog;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList<String> listss = new ArrayList<String>();
ArrayAdapter <String>adapter;
String add1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText tt = (EditText)findViewById(R.id.editText);
final ListView lv = (ListView)findViewById(R.id.listView1);
Button br = (Button)findViewById(R.id.button);
add1 = tt.getText().toString();
adapter=new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,listss);
lv.setAdapter(adapter);
listss.add(add1);
adapter.notifyDataSetChanged();
br.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View ss = LayoutInflater.from(MainActivity.this).inflate(R.layout.textt,null);
final AlertDialog.Builder builderDialog = new AlertDialog.Builder(MainActivity.this);
builderDialog.setView(ss)
.setPositiveButton("Print", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
listss.add(add1);
adapter.notifyDataSetChanged();
}
}).setNegativeButton("Cancel", null)
.setCancelable(false);
AlertDialog alert = builderDialog.create();
alert.show();
}
});
}
}
Try this code below (for getting edittext data):
br.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View ss = LayoutInflater.from(MainActivity.this).inflate(R.layout.textt,null);
final AlertDialog.Builder builderDialog = new AlertDialog.Builder(MainActivity.this);
builderDialog.setView(ss)
.setPositiveButton("Print", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
EditText et = (EditText) ss.findViewById(E.id.editText);
listss.add(et.getText().toString());
adapter.notifyDataSetChanged();
}
}).setNegativeButton("Cancel", null)
.setCancelable(false);
AlertDialog alert = builderDialog.create();
alert.show();
}
});
Here is the method in which i call on Button button.setOnClickListener
public void saveNote(View view){
final Dialog dialog = new Dialog(MainActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.add_new_note_layout);
mTitle = (EditText)dialog.findViewById(R.id.titleID);
mMessage = (EditText)dialog.findViewById(R.id.messageID);
save = (Button)dialog.findViewById(R.id.saveBtn);
setFilePathll();
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int titleLength = mTitle.getText().length();
if(titleLength != 0){
String title = mTitle.getText().toString();
String msg = mMessage.getText().toString();
helper.addNote(title, mFilePath, msg);
dialog.dismiss();
}
else
{
Toast.makeText(MainActivity.this,"Empty Message is not valid",Toast.LENGTH_LONG).show();
}
}
});
dialog.show();
}
Here helper.addNote(title, mFilePath, msg); is the method which i declared in the database helper class to insert data.
you Should use RecyclerView for what you want instead of using 'ListView'

What's wrong with my code, it won't recognize position?

I am making a simple planner app, with one xml and one activity. Here is MainActivity, where basically I take editText input, turn it into a listView item with button onClick, and save it. The only probmlem is my alert dialog for when you want to delete an item has an error - it won't recognize the word "position". I feel like it's just some dumb typo..? Thank you.
package com.kass.planner2;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends Activity {
EditText et;
ListView lv;
ArrayAdapter<String> adapter;
Button btn;
ArrayList<String> list = new ArrayList<String>();
final Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = (EditText) findViewById(R.id.editText);
lv = (ListView) findViewById(R.id.listView);
btn = (Button) findViewById(R.id.button);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
lv.setAdapter(adapter);
LoadPreferences();
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String task = et.getText().toString();
adapter.add(task);
adapter.notifyDataSetChanged();
SavePreferences("LISTS", task);
}
});
// set ListView item listener
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view; final int position, long id) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setTitle("Confirm Delete");
alertDialogBuilder.setMessage("Sure you want to delete?");
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
adapter.remove(adapter.getItem(position));
}
});
alertDialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
});}
protected void SavePreferences(String key, String value) {
// TODO Auto-generated method stub
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = data.edit();
editor.putString(key, value);
editor.commit();
}
protected void LoadPreferences(){
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(this);
String dataSet = data.getString("LISTS", " ");
adapter.add(dataSet);
adapter.notifyDataSetChanged();
}
}`
Try this way :
ArrayAdapter<String> adapter = (ArrayAdapter<String>)getListView().getAdapter();
adapter.remove(adapter.getItem(info.position));
adapter.notifyDataSetChanged();
May be, this needed.... adapter.notifyDataSetChanged(); when remove..
alertDialogBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
adapter.remove(adapter.getItem(position));
adapter.notifyDataSetChanged();
}
});
The position variable needs to be final if you want to access it there.
Do it as follows:
final int p = position; // just before setPositiveButton
alertDialogBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
adapter.remove(adapter.getItem(p));
}
});

Error in Alert dialog

There is an error in 'return view' at listview.setOnItemLongClickListener method. The error says cannot return a value from a method with void result type. I am trying to create an alert dialog where it will notify the user whether it wants to delete.
package com.example.user.swen;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import com.example.user.swen.DB.RecordsDataSource;
import com.example.user.swen.Model.Records;
public class Record extends ListActivity {
public Button NewButton;
public RecordsDataSource Recordsdatasource;
ArrayAdapter<Records> RecordAdapter;
List<Records> records;
ListView listview;
Records selectedRecord;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_record);
Addrecords();
//Referencing the Database
Recordsdatasource = new RecordsDataSource(this);
Recordsdatasource.open();
LayoutInflater inflater = LayoutInflater.from(Record.this);
View view = inflater.inflate(R.layout.activity_record, null);
//set the listView to use the custom List Adapter
records = (List<Records>) Recordsdatasource.getAll();
RecordAdapter = new RecordAdapter(this, 0, (ArrayList<Records>) records);
listview = (ListView) findViewById(android.R.id.list);
listview.setAdapter(RecordAdapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectedRecord = records.get(position);
AlertDialog.Builder a_builder = new AlertDialog.Builder(Record.this);
a_builder.setMessage("Duty: " + selectedRecord.getType())
.setCancelable(false)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog alert = a_builder.create();
alert.setTitle(Html.fromHtml("<font color='#08ae9e'>Information</font>"));
alert.show();
}
});
listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
selectedRecord = records.get(position);
AlertDialog.Builder a_builder = new AlertDialog.Builder(Record.this);
a_builder.setMessage("Are you sure you want to delete?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
deleteItem(selectedRecord);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = a_builder.create();
alert.setTitle(Html.fromHtml("<font color='#08ae9e'>Alert!!</font>"));
alert.show();
return true;
}
});
return view;
}
public void Addrecords() {
NewButton = (Button) findViewById(R.id.NewButton);
NewButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent addrecords = new Intent(Record.this, NewRecord.class);
startActivity(addrecords);
}
});
}
public static void showToast(Context context, String text) {
Toast.makeText(context, text, Toast.LENGTH_LONG).show();
}
private void deleteItem(Records selectedRecord) {
Recordsdatasource.removeRecords(selectedRecord);
showToast(this, "Usage deleted");
RecordAdapter.notifyDataSetChanged();
RecordAdapter.notifyDataSetInvalidated();
refreshDisplay();
}
private void refreshDisplay() {
records = Recordsdatasource.getAll();
RecordAdapter.clear();
RecordAdapter.addAll(records);
}
}
You are trying to return a View from your Activity's onCreate() method.
#Override
protected void onCreate(Bundle savedInstanceState) {
LayoutInflater inflater = LayoutInflater.from(Record.this);
View view = inflater.inflate(R.layout.activity_record, null);
//...
return view;
}
As you can see, onCreate() in an Activity has a void return type, meaning you shouldn't be returning anything in this method.
From the looks of your code, you are attempting to use this layout as the Activity's layout, but you are confusing the View inflation code with that used in a Fragment's onCreateView() method, which does indeed require you to return a View.
In an Activity, you need to call setContentView() to set the layout. You can either set the layout using the resource ID via setContentView(R.layout.activity_record), or if you want to inflate the View yourself you can call setContentView(view).
The call return view is actually located in onCreate. The function onCreate is declared to return nothing (void). Therefore, you cannot return an instance of View. You just have to remove that line or replace it with return; Also, onItemLongClick must return a boolean. So you can't move return view there either.

AlertDialog crashes application

Can someone explain to me why this AlertDialog crashes?
package com.clicker;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Clicker extends Activity
{
public int clickerNumber = 0;
private TextView clickerText;
private Button clickerButton;
private Button resetButton;
// Called when the activity is first created.
#SuppressWarnings("null")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Declare each of the layout objects
clickerText = (TextView)findViewById(R.id.clickerText);
clickerButton = (Button)findViewById(R.id.clickerButton);
resetButton = (Button)findViewById(R.id.resetButton);
clickerText.setText("0");
final AlertDialog.Builder resetQuestion = null;
resetQuestion.setTitle("Reset?");
resetQuestion.setMessage("Are you sure you want to reset the counter?");
resetQuestion.setPositiveButton("Yes", new OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
clickerNumber = 0;
clickerText.setText("0");
}
});
resetQuestion.setNegativeButton("No", new OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
clickerButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
clickerNumber++;
clickerText.setText(Integer.toString(clickerNumber));
}
});
resetButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
resetQuestion.show();
}
});
};
};
This is a great fail:
final AlertDialog.Builder resetQuestion = null;
resetQuestion.setTitle("Reset?");
You are trying to use a null object, and that (of course) will throw a NullPointerException
This is how I create dialogs (and I think it's the best way to do it):
LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(R.layout.dialogo_layout, null);
final AlertDialog.Builder resetQuestion = new AlertDialog.Builder(YourActivity.this)
// do whatever you want with the resetQuestion AlertDialog
Here, R.layout.dialogo_layout represent a file called dialogo_layout.xml in the res/layout dir that contains the dialog layout.

Categories

Resources