Android Alert Dialog crashes my application - java

Whenever I debug the application it crashes when I click the button that pops up the dialog.
What should I do to make that dialog work?
public class Actionbar_BtnHandler extends Activity {
Context context;
public Actionbar_BtnHandler (Context context)
{
this.context=context;
}
public void btn_handler (Button btn_mic,Button btn_post)
{
btn_mic.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context,"MICROPHONE",Toast.LENGTH_LONG).show();
}
});
btn_post.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
// Get the layout inflater
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(inflater.inflate(R.layout.dialog_signin, null))
// Add action buttons
.setPositiveButton("Post", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// sign in the user ...
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder.create();
}
});
}
}
Thanks in advance...

LayoutInflater inflater = ((Activity) context).getLayoutInflater();
is inaccurate... The cast seems to fail
Try :
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
// Get the layout inflater
LayoutInflater inflater = Actionbar_BtnHandler.this.getLayoutInflater();

Try this write your AlertDialog code using Handler..
btn_post.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Handler handler = new Handler();
handler.post(MessagealertDisplay);
}
});
}
Runnable MessagealertDisplay = new Runnable() {
#Override
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
// Get the layout inflater
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(inflater.inflate(R.layout.dialog_signin, null))
// Add action buttons
.setPositiveButton("Post", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// sign in the user ...
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder.create();
}
};

i used
Actionbar_BtnHandler btns = new Actionbar_BtnHandle(Class.this);
btns.btn_handler(btn_post, btn_mic);
instead of
Actionbar_BtnHandler btns = new Actionbar_BtnHandler(getApplicationContext);
btns.btn_handler(btn_post, btn_mic);
and it worked

Related

Images are not displayed in android list view

I'm making a todo app and when an item is marked as finished an image should be displayed in front of the list item. But images are not visible in the list view even if the item status in the database is changed as finished.
This is my adapter class.
public class ToDoAdapter extends ArrayAdapter {
private Context context;
private int resource;
List<ToDoModel> todos;
public ToDoAdapter(#NonNull Context context, int resource, #NonNull List<ToDoModel> objects) {
super(context, resource, objects);
this.context = context;
this.resource = resource;
this.todos = objects;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
//Inflate card view
LayoutInflater inflater = LayoutInflater.from(context);
View row = inflater.inflate(resource, parent, false);
TextView title = row.findViewById(R.id.title);
TextView description = row.findViewById(R.id.txtDescription);
ImageView img = (ImageView)row.findViewById(R.id.img_done);
img.setVisibility(View.VISIBLE);
//Set data in card view
ToDoModel todo = todos.get(position);
title.setText(todo.getTitle());
description.setText(todo.getDescription());
//Show done image
if(todo.getFinished() > 0){
img.setVisibility(View.VISIBLE);
}
return row;
}
}
This is MainActivity.
public class MainActivity extends AppCompatActivity {
private ListView todoList;
private TextView countTxt;
private Button addTodo;
private List<ToDoModel> toDos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
todoList = (ListView)findViewById(R.id.listViewToDo);
countTxt = (TextView)findViewById(R.id.txtCount);
addTodo = (Button)findViewById(R.id.btnAdd);
toDos = new ArrayList<>();
addTodo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Go to next activity
startActivity(new Intent(getApplicationContext(), AddToDO.class));
}
});
}
#Override
protected void onResume() {
super.onResume();
DBHandler dbh = new DBHandler(getApplicationContext());
//Set count
int count = dbh.getCountTODO();
countTxt.setText("You have " + count + " TODOs");
//Save list
toDos = dbh.getAllToDos();
//Set adapter to list
ToDoAdapter toDoAdapter = new ToDoAdapter(getApplicationContext(), R.layout.todo_cardview, toDos);
todoList.setAdapter(toDoAdapter);
//Add click listener to list element
todoList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Get clicked item
ToDoModel todo = toDos.get(position);
//Dialog box
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(todo.getTitle());
builder.setMessage(todo.getDescription());
//Buttons
builder.setNegativeButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dbh.deleteItem(todo.getId());
Toast.makeText(getApplicationContext(), "ToDo Deleted", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
});
builder.setPositiveButton("Finished", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
long time = System.currentTimeMillis();
//Update status
dbh.updateFinished(todo.getId(), time);
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
});
builder.setNeutralButton("Edit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(MainActivity.this, AddToDO.class);
intent.putExtra("id", todo.getId());
intent.putExtra("title", todo.getTitle());
intent.putExtra("description", todo.getDescription());
intent.putExtra("finished", todo.getFinished());
startActivity(intent);
}
});
builder.show();
}
});
}
}
Use Glide or Picasso Library to Displaying Image with any other Shape.
Glide Example:
Glide.with(mContext).load(responseList.getLogoUrl()).apply(RequestOptions.circleCropTransform()).into(holder.imageName);
Picasso Example:
Picasso.get().load(clsobjname.getLogoUrl())
.into(viewHolder.imagename);

custom dialog - specified child already has a parent

I've seen other posts but can't make heads nor tails of the following error.
Trying to have a dialog pop up on Recycler View item. I do have a similar dialog that works. I must use a different dialog because of different options in the second instance.
public class EditItemDialog extends AppCompatDialogFragment{
private EditText projectAmountEditText;
private EditDialogListener listener;
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View v = inflater.inflate(R.layout.activity_inventory_item, null);
builder.setView(v)
.setTitle("Edit Amount")
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
})
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
int amountChanged = Integer.parseInt(projectAmountEditText.getText().toString());
listener.editAmount(amountChanged);
}
});
projectAmountEditText = v.findViewById(R.id.amount_edit_text_item_activity);
if(projectAmountEditText == null){
//TODO
}
builder.show();
return builder.create();
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
try {
listener = (EditDialogListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() +
"must implement EditDialogLister");
}
}
public interface EditDialogListener{
void editAmount(int amountChanged);
}
}
Here is the logcat
Process: com.x.x, PID: 8485
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
at android.view.ViewGroup.addViewInner(ViewGroup.java:5235)
at android.view.ViewGroup.addView(ViewGroup.java:5064)
at android.view.ViewGroup.addView(ViewGroup.java:5036)
I had to add a onDestroy override on the dialog to free the View.

Custom Dialog error 'android.text.Editable android.widget.EditText.getText()' on a null object reference

I have created a custom dialog showing a grid of items. When another option is clicked, it will also open another custom dialog with an editText field. The problem I am facing is getting a null object error for the textfield. I found an answer here but when I applied it, the result is still the same.
Basically, the app is crashing when retrieving the textfield value in the custom dialog that opens from another custom dialog. Here is what I have so far:
onCreate()
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button donate = findViewById(R.id.button);
donate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDonateDialog();
}
});
}
showDonateDialog()
//Donate dialog with grid options
private void showDonateDialog() {
// Prepare grid view
GridView gridView = new GridView(this);
String[] donateAmount = getResources().getStringArray(R.array.donationAmount);
List<String> donateList = new ArrayList<String>();
Collections.addAll(donateList, donateAmount);
gridView.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, donateList));
gridView.setNumColumns(3);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "Thank you for your donation!", Toast.LENGTH_SHORT).show();
}
});
// Set grid view to alertDialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(gridView);
builder.setTitle("Donate");
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.setNeutralButton("Other amount", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
showCustomDonate();
}
});
builder.setCancelable(false);
builder.show();
}
showCustomDonate()
//Donate dialog for custom amount
private void showCustomDonate() {
AlertDialog.Builder builderCustom = new AlertDialog.Builder(this);
Context context = builderCustom.getContext();
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.custom_donate_amount, null, false);
final EditText donateAmount = findViewById(R.id.editAmount);
final DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_NEGATIVE) {
dialog.cancel();
} else {
String amount = donateAmount.getText().toString(); //Error null object reference here
Toast.makeText(getApplicationContext(), "Thank you for donating " + amount, Toast.LENGTH_LONG).show();
}
}
};
builderCustom.setView(view)
.setTitle("Custom Donation")
.setCancelable(false)
.setPositiveButton("OK", listener)
.setNegativeButton("CANCEL", listener)
.show();
}
Log
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.customdialog, PID: 12011
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at com.example.customdialog.MainActivity$5.onClick(MainActivity.java:94)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
i hope it is work for you
showCustomDonate()
//Donate dialog for custom amount
private void showCustomDonate() {
AlertDialog.Builder builderCustom = new AlertDialog.Builder(this);
Context context = builderCustom.getContext();
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.custom_donate_amount, null, false);
final EditText donateAmount = findViewById(R.id.editAmount);
final DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_NEGATIVE) {
dialog.cancel();
} else {
String amount = donateAmount.getText().toString(); //Error null object reference here
Toast.makeText(getApplicationContext(), "Thank you for donating " + amount, Toast.LENGTH_LONG).show();
}
}
};
builderCustom.setView(view)
.setTitle("Custom Donation")
.setCancelable(false)
.setPositiveButton("OK", listener)
.setNegativeButton("CANCEL", listener)
.show();
}
Change on this line
final EditText donateAmount = view.findViewById(R.id.editAmount);

NullPointerException trying to get PositiveButton of DialogFragment

In my Android application I created a custom DialogFragment with a custom View but I want the Positive and Negative Button with transparent background.
So I saw some SO answers and i did something like this:
private class PersonalInfoDialogFragment extends DialogFragment {
#Override
public void onStart(){
super.onStart();
Button pButton = ((AlertDialog) getDialog()).getButton(DialogInterface.BUTTON_POSITIVE);
Button nButton = ((AlertDialog) getDialog()).getButton(DialogInterface.BUTTON_NEGATIVE);
pButton.setBackgroundColor(getResources().getColor(Color.TRANSPARENT));
nButton.setBackgroundColor(getResources().getColor(Color.TRANSPARENT));
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
LayoutInflater inflater = getActivity().getLayoutInflater();
final View view=inflater.inflate(R.layout.personalinformation_dialog, null);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.personalinformation)
.setView(view)
.setPositiveButton(R.string.edit, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//Some code
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
final AlertDialog dialog = builder.create();
//I also tried this: dialog.getButton(DialogInterface.BUTTON_POSITIVE).setBackgroundColor(Color.TRANSPARENT);
return dialog;
}
}
I don't get why I am facing NullPointerException. Any idea?
public Button pButton ,nButton ;
#Override
public void onStart(){
super.onStart();
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
LayoutInflater inflater = getActivity().getLayoutInflater();
final View view=inflater.inflate(R.layout.personalinformation_dialog, null);
pButton = ((AlertDialog) getDialog()).getButton(DialogInterface.BUTTON_POSITIVE);
nButton = ((AlertDialog) getDialog()).getButton(DialogInterface.BUTTON_NEGATIVE);
pButton.setBackgroundColor(getResources().getColor(Color.TRANSPARENT));
nButton.setBackgroundColor(getResources().getColor(Color.TRANSPARENT));
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.personalinformation)
.setView(view)
.setPositiveButton(R.string.edit, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//Some code
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
final AlertDialog dialog = builder.create();
//I also tried this: dialog.getButton(DialogInterface.BUTTON_POSITIVE).setBackgroundColor(Color.TRANSPARENT);
return dialog;
}
}

How to open a DialogFragment by clicking on a TextView

I have a MainActivity like this one below:
My question is how to open a DialogFragment clicking on the TextView "click HERE to give a name to the task" placed next to "play" button.
Here is the code of my TextView:
TextView buttonView = new TextView(this);
buttonView.setHint("click HERE to give a name to the task");
buttonView.setX(50);
buttonView.setY(50);
and the code of the DialogFragent:
public class ButtonNameDialogFragment extends DialogFragment {
private IFragment iButNamFrag;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder setButNameAlert = new AlertDialog.Builder(getActivity());
setButNameAlert.setTitle("Set Task name");
LayoutInflater inflater = getActivity().getLayoutInflater();
setButNameAlert.setView(inflater.inflate(R.layout.button_name_fragment, null))
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Implement dialogPositiveClick
}
})
.setNegativeButton(R.string.undo, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Implement dialogNegativeClick
}
});
return setButNameAlert.create();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
iButNamFrag = (IFragment) activity;
}
}
and here is the interface:
public interface IFragment {
public void onDialogPositiveClick(DialogFragment dialog);
public void onDialogNegativeClick(DialogFragment dialog);
}
You can set an onClickListener to any view in Android and then perform any behavior you would like
buttonView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Create new DiaglogFragment and display it
}
};
This is the same method used for any kind of button pressing. There are plenty of other answers already out on StackOverflow with further examples of this. If you need more information on tap recognition or displaying fragments, a quick search will find it on Stack.
buttonView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment frag = new ButtonNameDialogFragment();
frag.show(*context*, ButtonNameDialogFragment.class.getCanonicalName());
}
});

Categories

Resources