AlertDialog not displaying file list - java

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

Related

dialog - The specified child already has a parent. You must call removeView() on the child's parent first

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.

Android Java File.delete() deletes file, then it undeletes itself

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!

Alert Dialog Builder wont show ArrayList

I have a class that retrieves ArrayList from Database. And I need to show this items in Alert Dialog builder. But im getting an error in this. Please Help!
Here is my error:
Error: The method setSingleChoiceItems(int, int,
DialogInterface.OnClickListener) in the type AlertDialog.Builder is
not applicable for the arguments (Name[], int, new
DialogInterface.OnClickListener(){})
ArrayList<Name> n_names = null;
n_names = db.getAllNames();
AlertDialog.Builder builder = new AlertDialog.Builder(Name.this);
builder.setTitle("Choose Name");
builder.setSingleChoiceItems(n_names.toArray(new Name[n_names.size()]), -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
}});
builder.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}});
builder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}});
AlertDialog alert = builder.create();
alert.show();
I think the error is that you're providing a customized class object to the setSingleChoiceItems method. The first parameter has to be a a CharSequence[], a ListAdapter or a Cursor. If you're not intended to put one of them, you'll have to extend the Dialog class an implement your own setSingleChoiceItems method.
---- EDIT ----
In your case, I'd recommend extending the ArrayAdapter class, as you have some customized structures to show (in your case, a CheckBox). To help you do that, you may see my answer to a similar question and also a little basic explaination on how to extend the ArrayAdapter class, here. Hope this helps you!

How to display AlertDialog in a Fragment?

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 - trying to understand this syntax

This is code from the book sample:
new AlertDialog.Builder(this)
.setTitle(getResources().getString(R.string.alert_label))
.setMessage(validationText.toString())
.setPositiveButton("Continue", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int arg1) {
// in this case, don't need to do anything other than close alert
}
})
.show();
I want to understand this code, please rewrite it in several statements, so that each statement makes exactly one operation. Thanks!
// Create a builder
AlertDialog.Builder adb = new AlertDialog.Builder(this);
// Set a title
adb.setTitle(getResources().getString(R.string.alert_label));
// Set the dialogs message
adb.setMessage(validationText.toString());
// Set label and even handling of the "positive button"
//
// NOTE: If you don't want to do anything here except to close the dlg
// use the next line instead (you don't have to specifiy an event handler)
// adb.setPositiveButton("Continue", null);
adb.setPositiveButton("Continue",
new android.content.DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int arg1) {
// in this case, don't need to do anything other than close alert
}
});
// Show the dialog
adb.show();
Seperate statements, each executed on a normal builder object.
Alternatively you can chain builder methods to save a few chars (like your orginal source), though you can write it more readable. To do so remove the semicolons and the object reference at the beginning of each line. Each builder method returns the original builder object, which you can use to run the next statement on it.
Here's a small, better readable example for that:
new AlertDialog.Builder(this)
.setTitle("Title")
.setMessage("42 is the answer")
.show();
AlertDialog.Builder has numerous methods that all return the AlertDialog.Builder they operate on.
This allows you to write:
builder.A();
builder.B();
builder.C() ;
as
builder.A().B().C();
I find this extra annoying, but that's just me.
AlerDialog.Builder d = new AlertDialog.Builder(this); // get an Object of AlertDialog.Builder
d.setTitle(getResources().getString(R.string.alert_label)); //Set its title
d.setMessage(validationText.toString()); //set message body
d.setPositiveButton("Continue",new android.content.DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int arg1) {
// in this case, don't need to do anything other than close alert
}
}); //this dialog will have single button called Continue
d.show(); // this pops up the dialog..
This technic is known as Method chaining
try putting line breaks before each . Then it'll be more readable.
new AlertDialog.Builder(this)
.setTitle(
getResources().getString(R.string.alert_label))
.setMessage(validationText.toString()).setPositiveButton("Continue",
new android.content.DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int arg1) {
// in this case, don't need to do anything other than close alert
}
})
.show();

Categories