Okay, I know that this is a really weird question, but this is a very weird problem.
What I am making is a note-taking app, and basically the user can create notebooks, and then notes in each notebook. What I am having trouble with is deleting said notes.
Activity Hierarchy: Books(main activity) -> Book -> Note
Basically when you delete a note(which is done from the Note activity), the Note activity finishes, and Book calls an onResume() that looks through the notebook folder, and reloads all of the notes into a ListView. The weird thing is that when the Note activity finishes, you can not see the note in the Book activity. However if you reload it (go to Books and then back), or do anything to call the method to refresh, the note is there again with all of it's data.
Here is the code that I used to delete the note:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Are You Sure?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
File note = new File(Path);
if(note.delete()) {
finish();
} else {
Snackbar.make(edt_note, "An Error Occurred", Snackbar.LENGTH_LONG).setAction("Action", null).show();
}
}
});
builder.setNegativeButton("Cancel", null).create();
builder.show();
note.delete() returns true when run.
As a sidenote, I have permission to delete on these local folders. The code to delete the notebooks runs like a charm:
final AppCompatActivity This = this;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Are You Sure?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
File folder = new File(getFilesDir().getPath() + File.separator + Name);
File[] notes = folder.listFiles();
for(File note : notes) {
note.delete();
}
if(folder.delete()) {
finish();
} else {
Snackbar.make((ListView) This.findViewById(R.id.list_notes), "An Error Occurred", Snackbar.LENGTH_LONG).setAction("Action", null).show();
}
}
});
builder.setNegativeButton("Cancel", null).create();
builder.show();
I'm really stumped on this one, any help would be appreciated.
EDIT:
It won't let me choose my own answer as solved, but I figured it out. Details down below.
WOW I'M DUMB! lol
What was happening is that I had a save method in onStop() that was saving the note just as the activity was ending. Whoops!
Related
public void exit(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setIcon(R.mipmap.ic_launcher_round);
builder.setTitle("Likee Likes");
builder.setMessage("Do you really wanna Exit?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.create();
builder.show();
}
**I am using this code to confirm my user either exit or not. when my user click the "yes" button the app doesn't close and get back to the previous activity. Is there any mistake with this code? **
i am trying to close my app by user confirmation.
I assumes you use AlertDialog in the another activity rather than your first activity, so when you use finish, you are close the activity that isn't the first activity.
If you you want to close you app, you can try use startActivityForResult to process some job accordingto the requestCode.
But now startActivityForResult is deprected, you can try to use new way to do this: OnActivityResult method is deprecated, what is the alternative?.
You can reference to this too How to quit android application programmatically
I'm trying to build an Dialog in android studios with Java.
But the problem is, that however I try it the Error
"D/InputTransport: history resample interval is too short, cannot uses it to resample!!"
appears.
I already searched for a solution, but I found nothing similar.
I also tried it with another mobile phone, but it didn't work as well.
Here is my source-text:
public void add(View view){
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("title");
alertDialog.setMessage("text");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
The method "add" is opened by a button.
I would be happy about every help!
After a check demanding the user to switch on internet services and I try to click on a button my app crashes with the error message
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
On this line it crashes, I have tried doing this but not resolved absolutely
if(alert.getContext() != null){
alert.show();
}
This is the complete code
else if (id == R.id.xyz) {
//startActivity(borrowIntent);
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
alert.setTitle("xyz");
input.setFilters(new InputFilter[] {
// Maximum 2 characters.
new InputFilter.LengthFilter(6),
// Digits only.
DigitsKeyListener.getInstance(),
});
// Digits only & use numeric soft-keyboard.
input.setKeyListener(DigitsKeyListener.getInstance());
input.setHint("xyz");
alert.setView(input);
alert.setPositiveButton("Borrow", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
if(input.getText().length() == 0)
{
input.setError("xyz is required !");
}
else
{
if(isNetworkAvailable())
{
xyz( input.getText().toString());
}else{
//setContentView(R.layout.main);
AlertDialog.Builder builder = new AlertDialog.Builder(
MainActivity.this);
builder.setCancelable(false);
builder.setTitle("xyz");
builder.setMessage("Please enable wifi services");
builder.setInverseBackgroundForced(true);
builder.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
startActivityForResult(new Intent(android.provider.Settings.ACTION_SETTINGS), 0);
dialog.dismiss();
}
});
AlertDialog alerts = builder.create();
alerts.show();
}//end of block
}
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
if(alert.getContext() != null){
alert.show(); //crashes at this line
}
}
Please what am I missing?
The problem is on this line:
alert.setView(input);
You added input View that have already parent.
Create new input instance.
according to this post, add this check to remove input from it's parent and readd it:
if(input.getParent()!=null)
((ViewGroup)input.getParent()).removeView(input); // <- fix
alert.addView(input);
Put following line
final AlertDialog alertd = alert.create();
After
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
Following situation can also happen (happened to me):
Sometimes when you use a listview you initialize it with an adapter, which belongs to a certain layout. Now lets say the root view of this layout file is a <LinearLayout> with the id "root_view".
If you register now for a context menu in your activity and create an AlerdDialog.Builder which appears after choosing a certain menu element and initialize it with a layout file, which also has a root element with an id called "root_view" where all elements which belong to your AlertDialog are children of it, then those elements "will not be found". You will not be able to access those elements with findViewById, instead you can only access the elements from the of your list view and you get the same error message at the line where you call builder.show() (or in the case here alert.show()).
So generally it is a good idea to name the ids of your elements in the layout files uniquely, for your project.
I forgot to call create() on the AlertDialog.Builder. When you call show() without calling the create() method, the AlertDialog instance gets created. This worked the first time but then subsequent clicks got the IllegalStateException. As I was calling show() inside of my onClickListener, it was going to create a new AlertDialog instance every time button was clicked.
I want to display an alert dialog in my app. I am using fragments. I tried the below code to do this:
AlertDialog ad = new AlertDialog.Builder(context)
.create();
ad.setCancelable(false);
ad.setTitle(title);
ad.setMessage(message);
ad.setButton(context.getString(R.string.ok_text), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
ad.show();
but it was crashing and the error in logcat was:
04-18 15:23:01.770: E/AndroidRuntime(9424): android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
From internet I came to know that the crash is due to context issue. I had given context as
context = this.getActivity().getApplicationContext();
I don't know what is the problem with this. Can anybody help me?
Replace context with getActivity().
The ApplicationContext should not be used for tasks such as creating Dialogs. As you are in a fragment you can instead get the Activity-Context simply by calling the Fragments getActivity() method.
More Information about this question (AlertDialog in a fragment, managed inside an event):
If you call AlertDialog within an event like onClick(View v) or onLongClick(View v) you can use
public boolean onClick(View v) {
...
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(v.getContext());
...
}
Try to use DialogFragment, DialogFragment is better when you use Fragments
I have had similar issues whereby I was trying to create an AlertDialog from a Fragment. A NullPointerException arose from it. Initially I did as follows:
AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();
The NullPointerException occurred specifically when calling alertDialog.show() later on in the code.
But after searching the documentation for AlertDialog.Builder(), there seemed to be another way to initialize it [AlertDialog.Builder Doc], which is to include a theme/resId as shown below:
AlertDialog alertDialog = new AlertDialog.Builder(getActivity(), R.style.Theme_AppCompat_Dialog_Alert).create();
This resolved the NullPointerException at hand. Hope this helps you as well!
I used it in an adapter inside a listView, therefore I couldn't use getActivity(). In order to make it work I used getActivity() for the context in the instantiation of the adapter in the fragment:
this.adapter = new myAdapter(getActivity(), factory);
Later in the other class (the adapter's class) I was able to use getContext()and it worked.
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
AlertDialog alert= null;
AlertDialog.Builder build= new AlertDialog.Builder(getActivity());
build.setTitle("title");
build.setItems(stringarrayname, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
//Toast.makeText(getActivity(), "hi", Toast.LENGTH_SHORT).show();
}
});
build.create().show();
You can try this or use DialogFragment
private void showAlert(final int position) {
new AlertDialog.Builder(getActivity().getApplicationContext())
.setTitle("Delete entry")
.setMessage("Are you sure you want to delete this entry?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// deleteSuggestions(position);
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
The solution is to replace by getActivity()
AlertDialog.Builder alert = new AlertDialog.Builder(getActivity(),R.style.MaDialog);
AlertDialog.Builder load_alert = new AlertDialog.Builder(this);
File list = new File("data/data/project/databases/");
if(!list.exists() || !list.isDirectory()){
return;
}
String [] fileList = list.list();
load_alert.setMessage("Please select");
load_alert.setItems(fileList, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
Toast toast = Toast.makeText(getApplicationContext(), "test", Toast.LENGTH_LONG);
toast.show();
}
});
load_alert.show();
This is supposed to display the content of my database folder into an alertdialog. I've checked the fileList array, and it is being populated. For some reason it just isn't displaying via setItems. Any ideas?
I realize I'm a little late to the ballgame and that you have probably already solved your problem, but I was having the same issue and I figured out what the problem was.
Apparently, when you call .setMessage(), that overrides the setItems() declaration and turns the AlertDialog into a message dialog. Instead, call .setTitle() to set the title of the dialog.
Also, in your example you don't seem to call .create(), so it should be load_alert.create().show(). Presumably that's a transcription error, though, because I think AlertDialog.Builder doesn't have a show() method.
Even I am late in posting
but here is what i tried and was able to display all the folders.
AlertDialog.Builder listAlert = new AlertDialog.Builder(this);
String [] filelist = path.list();
listAlert.setTitle("Select Definition File");
listAlert.setItems(filelist, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Stuffs to do after you have selected folder or file.
}
}).show();
and at some point in my code i have
private File path = new File(Environment.getExternalStorageDirectory()+"");
Thanks