I have one custom dialogue in my application which have not any issue. Its working fine but I am getting white space above my dialogue like this image.
I am facing issue only device which have Lollipop and lower API. My code is looking like below
private void showGotoPageDialog() {
if (getActivity() != null) {
if (mPageOptions.length == 0)
return;
final Dialog mDialog = new Dialog(getActivity());
mDialog.setContentView(R.layout.grid_dialogue);
if(mDialog.getWindow()!=null){
mDialog.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);}
GridView mGridView = mDialog.findViewById(R.id.grid_dialog);
ArrayList<String> tmp = new ArrayList<>(mPageOptions.length);
for (int i = 0; i < mPageOptions.length; i++) {
tmp.add(mPageOptions[i].split(" ")[1]);
}
final CustomAdapter adapter = new CustomAdapter(getActivity(), tmp, mPageIndx);
mGridView.setAdapter(adapter);
mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int item, long l) {
adapter.a.cancel();
mDialog.dismiss();
mPageIndx = item + 1;
updateQuotesList();
updatePageInfo();
}
});
mDialog.show();
TextView dismiss =mDialog.findViewById(R.id.dialog_dismiss);
dismiss.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
adapter.a.cancel();
mDialog.dismiss();
}
});
}
}
Let me know if someone have idea to fix it. Thanks
White Space Above Dialogue in Lollipop Device
it is called Dialog Title
Try this use mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); it will remove the Blank title space from your Dialog
Sample code
final Dialog mDialog = new Dialog(getActivity());
mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
mDialog.setContentView(R.layout.grid_dialogue);
mDialog.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);}
GridView mGridView = mDialog.findViewById(R.id.grid_dialog);
// your whole dialog code
Related
In my application I have draft messages which I can edit. Some of my drafts include attachments which I try to send to my edit activity and show it at recyclerview. In general I have managed to send my string arraylist and get it at my activity. But I can't show my attached files, especially their names at the recyclerview. I tried to make smth like that:
adapter.notifyDataSetChanged();
but it didn't help me.
So, firstly I get from my message names of attached files:
file_name = Objects.requireNonNull(response.body()).getAttachesNames();
then put this names into arraylist:
nameList = new ArrayList<>(Arrays.asList(file_name));
such result I can see in my logs:
W: [eZV9f.jpg, index.html]
and then I send my list via intent to another activity:
intent2.putStringArrayListExtra("attached_files", (ArrayList<String>) nameList);
receiving data from intent:
Intent intent = getIntent();
extras = intent.getExtras();
if (extras != null) {
if (extras.containsKey("attached_files")) {
draft_files = getIntent().getStringArrayListExtra("attached_files");
Log.w("MY_TAG", String.valueOf(draft_files));
}
}
results from logcat:
W: [eZV9f.jpg, index.html]
initialising of my adapter and recyclerview:
adapter = new AttachedFileAdapter(mNames);
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(WriteResponseMess.this, LinearLayoutManager.VERTICAL, false));
and then I try to get single element from this list and add to my ArrayList<>:
for (int i = 0; i < draft_files.size(); i++) {
mNames.addAll(Collections.singleton(draft_files.get(i)));
adapter.notifyDataSetChanged();
recyclerView.setAdapter(adapter);
Log.w("MY_TAG", draft_files.get(i));
Log.w("MY_TAG", String.valueOf(mNames));
}
all previous pieces of code are used at my onCreate() method and as a result of all these actions I would like to see income data from another activity. Sometimes I managed to do it, but one element contained all income data and looked like this:
[eZV9f.jpg, index.html]
and it was wrong for me. I try to create the list which will contain all elements separately. I also tried to use some info from this link which is connected with Collections, but I didn't manage to reach the goal of my task. In general I'm sure that the solution is very simple but I can't see it.
update
all my activity class has more than 1000 lines and I will share all code which is connected with adding attachments and show attached data at my writing form:
Here is my dialog for getting directory list and choosing some files:
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
switch (id) {
case CUSTOM_DIALOG_ID:
dialog = new Dialog(WriteResponseMess.this, android.R.style.Theme_DeviceDefault_Light_NoActionBar_Fullscreen);
dialog.setContentView(R.layout.dialog_layout);
dialog.setCanceledOnTouchOutside(true);
Toolbar toolbar = dialog.findViewById(R.id.toolbar_d);
toolbar.setTitle("Add a new file.");
textFolder = dialog.findViewById(R.id.folder);
buttonUp = dialog.findViewById(R.id.up);
buttonUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ListDir(curFolder.getParentFile());
}
});
dialog_ListView = dialog.findViewById(R.id.dialoglist);
final Dialog finalDialog1 = dialog;
dialog_ListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
File selected = new File(curFolder, fileList.get(position));
if (selected.isDirectory()) {
ListDir(selected);
}
if (selected.isFile()) {
if (array.size() == 0) {
array = uploadFiles(array, selected.getName(), convertFileToString(selected.getPath()));
adapter.notifyDataSetChanged();
getImages();
} else {
if (array.toString().contains(selected.getName())) {
Toast.makeText(WriteResponseMess.this, R.string.attaching_message, Toast.LENGTH_SHORT).show();
adapter.notifyDataSetChanged();
getImages();
} else {
array = uploadFiles(array, selected.getName(), convertFileToString(selected.getPath()));
adapter.notifyDataSetChanged();
getImages();
}
}
finalDialog1.dismiss();
ms.setArray(array);
}
}
});
break;
}
return dialog;
}
and method for showing attached list, and in general this method works when I create a new message and attach a new file, it works fine:
private void getImages() {
mNames.clear();
adapter.notifyDataSetChanged();
for (int i = 0; i < array.size(); i++) {
JsonObject object = array.get(i).getAsJsonObject();
if (extras != null) {
if (extras.containsKey("attached_files")) {
for (int j = 0; j < draft_files.size(); j++) {
mNames.clear();
mNames.add(draft_files.get(j));
adapter.notifyDataSetChanged();
//Log.w("MY_TAG", draft_files.get(i));
Log.w("MY_TAG", String.valueOf(mNames));
}
mNames.add(object.get("filename").toString().substring(1, object.get("filename").toString().length() - 1));
adapter.notifyDataSetChanged();
//Log.w("MY_TAG", Arrays.toString(draft_files));
Log.w("MY_TAG", Arrays.toString(new ArrayList[]{mNames}));
} else {
mNames.add(object.get("filename").toString().substring(1, object.get("filename").toString().length() - 1));
adapter.notifyDataSetChanged();
Log.w("MY_TAG", String.valueOf(mNames));
}
}
}
}
no need to set Adapter twice . remove this line
recyclerView.setAdapter(adapter);
From
for (int i = 0; i < draft_files.size(); i++) {
mNames.addAll(Collections.singleton(draft_files.get(i)));
adapter.notifyDataSetChanged();
//recyclerView.setAdapter(adapter); no need
Log.w("MY_TAG", draft_files.get(i));
Log.w("MY_TAG", String.valueOf(mNames));
}
Hi guys I have a custom alert dialog I created. In the builder I set cancelable to false yet it still disappears when I press the back button, any ideas?
This is the code for the dialog:
public final class HemisphereDialogFragment extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View customTitle = inflater.inflate(R.layout.hemisphere_dialog_custom_title, null);
builder.setCustomTitle(customTitle);
String[] entries = new String[2];
entries[0] = getResources().getString(R.string.northern_hemisphere);
entries[1] = getResources().getString(R.string.southern_hemisphere);
builder.setItems(entries, new DialogInterface.OnClickListener() {
//The 'which' argument contains the index position of the selected item
public void onClick(DialogInterface dialog, int which) {
if( which == 0 ) {
GlobalVariables.getShared().setIsInNorthernHemisphere(true);
} else if( which == 1 ) {
GlobalVariables.getShared().setIsInNorthernHemisphere(false);
}
ToolbarActivity.outfitsFragment.hemisphereSelected();
GlobalVariables.getShared().setHasAskedForHemisphere(true);
}
});
builder.setCancelable(false);
//Create the AlertDialog object and return it
return builder.create();
}
And this is how it's displayed:
new HemisphereDialogFragment().show(getSupportFragmentManager(), "hemisphereDialog");
Another small side question, is there a way to change the text size for the items in the dialog?
You set your alert dialog cancelable to false, but your fragment is still set to cancelable, you need to add setCancelable(false) to your fragment as well.
You should call setCancellable(false) in the Dialog fragment itself not the AlertDialog.Builder.
I've got an inputDialog, which allows for some text inputs. On clicking save, the inputDialog checks if the entered text is already available (to prevent double entries). If this is the case, a new AlertDialog is created, simply stating "The value you entered already exists", with just an "Ok" button to dismiss this AlertDialog. This all works.
I would like to have the inputDialog pop back up again, after dismissing the AlertDialog, with the values that were entered by the user before still in the editText fields.
I'm not expecting any problems on getting those values back in the editText fields (Store them in a variable on clicking save, if the double entry error occurs, set those variables on the editText's. If I'm doing this in a stupid way, please let me know).
I am however having trouble with getting the first (inputDialog) dialog to come back. The code you see below is the code for my inputDialog fragment (The code is simplified, so if something seems to be missing, it probably is. Let me know, so I can add it back in.)
So, to repeat myself: How can I return to the previous dialog after dismissing the second one?
StuffManagerInputDialogFragment.java:
public class StuffManagerInputDialogFragment extends DialogFragment {
EditText nameInputField;
EditText tagInputField;
DBHandler dbHandler;
StuffManagerFragment f = new StuffManagerFragment();
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
LayoutInflater inflater = getActivity().getLayoutInflater();
final View v_iew = inflater.inflate(R.layout.fragment_inputdialog, null);
nameInputField = (EditText) v_iew.findViewById(R.id.inputdialogname);
tagInputField = (EditText) v_iew.findViewById(R.id.inputdialogtag);
dbHandler = new DBHandler(getActivity(), null, null, 1);
final MainActivity ma = (MainActivity) getActivity();
final AlertDialog.Builder newLinkDialog = new AlertDialog.Builder(getActivity());
newLinkDialog.setView(v_iew)
.setTitle("New Link")
.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String nameInputFieldText = nameInputField.getText().toString();
String tagInputFieldText = tagInputField.getText().toString();
ArrayList<String> nameArray = dbHandler.nameArrayMethod();
ArrayList<String> tagArray = dbHandler.tagArrayMethod();
NavigationView navigationView = (NavigationView) getActivity().findViewById(R.id.nav_view);
Menu menu = navigationView.getMenu();
if (nameArray.contains(nameInputFieldText) || tagArray.contains(tagInputFieldText)) {
if (nameArray.contains(nameInputFieldText) && tagArray.contains(tagInputFieldText)) {
AlertDialog.Builder errorBoth = new AlertDialog.Builder(getActivity())
.setTitle("Error")
.setMessage("The name and tag you entered are already in use.")
.setIcon(R.drawable.ic_error_black)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Return to previous dialog here
}
});
errorBoth.show();
}
} else {
dbHandler.addLink(nameInputFieldText, tagInputFieldText);
nameArray = dbHandler.nameArrayMethod();
int nameArraySize = (nameArray.size() - 1);
MenuItem item = menu.add(R.id.group1, nameArraySize, 1, nameArray.get(nameArraySize));
Toast.makeText(getContext(), "'" + nameInputFieldText + " - " + tagInputFieldText + "' link saved.", Toast.LENGTH_SHORT).show();
ma.addSMVFFragments();
f.hideDeleteAllButton = false;
getActivity().invalidateOptionsMenu();
}
}
})
.setNegativeButton("Cancel", null);
return newLinkDialog.create();
}
}
A better solution is to have a dialog fragment for your input layout, and that dialog fragment would display an AlertDialog on OK if the text validation fails. The input dialog fragment would not dismiss in this case, it will remain in the background so when you dismiss the alert dialog to tell the user the input is invalid, you return to the input dialog as it was.
To prevent the dialog fragment from dismissing on OK you would override onStart and get a reference to the OK button and set the listener there, like this:
#Override
public void onStart() {
super.onStart();
AlertDialog alertDialog = (AlertDialog) getDialog();
if (alertDialog != null) {
mOKButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
mOkButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (field OK) {
// save data
dismiss();
} else {
// show error dialog
}
}
});
}
}
I've gotten my app to download content from a website but the intent asks you to open the link in the browser and downloads it from there. I wish to change that so when i tap the download button, instead of the intent directing to the browser it opens a popup in my app and shows the download progress.
How am I able to achieve this?
I have searched around stackoverflow and have only found ways that don't work for me. Here is my code -
txtLink = (EditText) findViewById(R.id.input_package);
btnOpenLink = (ImageButton) findViewById(R.id.download);
btnOpenLink.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String page = txtLink.getText().toString();
if (!TextUtils.isEmpty(page)) {
Uri uri = Uri.parse(defaultLink + page);
// Success Toast
LayoutInflater inflater = getLayoutInflater();
// Inflate the Layout
View layout = inflater.inflate(R.layout.custom_toast, null);
TextView text = (TextView) layout.findViewById(R.id.textToShow);
// Set the Text to show in TextView
text.setText("Your download should start shortly");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.FILL_HORIZONTAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
} else {
// Fail Toast
LayoutInflater inflater = getLayoutInflater();
// Inflate the Layout
View layout = inflater.inflate(R.layout.custom_toast, null);
TextView text = (TextView) layout.findViewById(R.id.textToShow);
// Set the Text to show in TextView
text.setText("Please enter a package name");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.FILL_HORIZONTAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
}
}
});
Could someone explain what is the best way to create a popup download progress?
Because i have an input field where one can enter the second part of the url and it downloads that. Eg- download.com/ but the user enters "download" so when he taps the button it changes to download.com/download and it downloads from that url.
Thanks
You can do something like this..
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private ProgressDialog mProgressDialog;
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("waiting 5 minutes..");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
Then write an async task to update progress..
private class DownloadZipFileTask extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... urls) {
//Copy you logic to calculate progress and call
publishProgress("" + progress);
}
protected void onProgressUpdate(String... progress) {
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String result) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
Write your download logic under the doInBackground method of Asynctask.This should solve your purpose and it wont even block UI tread..
I have this .xml file with countries and their countrycodes in them. This is how it looks like:
<?xml version="1.0" encoding="UTF-8"?>
<landen>
<land>
<naam>Afghanistan</naam>
<code>AF</code>
</land>
<land>
<naam>Albani�</naam>
<code>AL</code>
</land>
<land>
<naam>Algerije</naam>
<code>DZ</code>
</land>
<land>
</landen>
Now I want people to choose one country out of an list. I though an AlertDialog would be nice to display everything.
The way i get the values out of my xml-file is like this:
protected ArrayList<Land> getLanden() {
ArrayList<Land> lijst = new ArrayList<Land>();
try {
DocumentBuilder builder =DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(getAssets().open("landenlijst.xml"));
NodeList nl = doc.getElementsByTagName("land");
for (int i=0;i<nl.getLength();i++) {
Node node = nl.item(i);
Land land = new Land();
land.land = Xml.innerHtml(Xml.getChildByTagName(node, "naam"));
land.landcode = Xml.innerHtml(Xml.getChildByTagName(node, "code"));
lijst.add(land);
}
Log.d("Gabug","Klaar met parsen");
Log.d("Gabug","Landen: " + lijst);
} catch (Exception e) {
e.printStackTrace();
}
return lijst;
}
And I use this to make my AlertDialog:
public void KiesLandMenu(){
ArrayList<Land> alleLanden = getLanden();
final CharSequence[] items = alleLanden.toArray(new CharSequence[alleLanden.size()]);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Kies land");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
switch (item){
case 0:
break;
case 1:
break;
case 2:
break;
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
I don't know if this works as DDMS returns some bytecode or something when i Log it. And after that it Force Closes because of ArrayStoreException..
Now my question is; is this the best way to do this? if yes, how can I fix the ArrayStoreException? If no, what are better ways to let my user choose a country (a whole new view maybe)?
Furthermore, how can I register what country someone tapped?
EDIT:
I slightly changed the sample code below and I get an NullPointerException now..
public void KiesLandMenu(){
ArrayAdapter<Land> arrAdapter;
ArrayList<Land> alleLanden = getLanden();
arrAdapter = new ArrayAdapter<Land>(this, android.R.layout.simple_list_item_single_choice, alleLanden);
ListView list = (ListView)findViewById(R.layout.lijstview);
list.setAdapter(arrAdapter);
list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> list, View view, int position,
long id) {
Log.e("item clicked", String.valueOf(position));
}
});
}
The NullPointerException is at list.setAdapter(arrAdapter);
Make a layout with a ListView, then set that layout in your onCreate. To make the list, you can do something like:
public class RunTestProject extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main); //whatever you want your layout to be
}
// getLanden() implementation goes here
public void KiesLandMenu(){
ArrayList<Land> alleLanden = getLanden();
arrAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice, alleLanden);
Dialog dialog = new Dialog(this);
dialog.setTitle("Kies land");
dialog.setContentView(R.layout.withList); // The dialog layout
ListView list = (ListView) dialog.findViewById(android.R.id.list); //note that it's not simply findViewById
list.setAdapter(arrAdapter);
list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> list, View view, int position,
long id) {
Log.e("item clicked", String.valueOf(position));
}
});
dialog.show();
}
}
When the user chooses on an item, you can see in the log that the item's position in the array is shown.
Your layout file can be something like:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ListView android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="1"
/>
</LinearLayout>
You could probably extend AlertDialog and give it a ListView as a view. Then bind the ListView to an ListAdapter which uses your ArrayList.
Edit:
ListView lv = new ListView(context);
ArrayAdapter aa = new ListAdapter(context, viewid, lijst);
lv.setAdapter(aa);
AlertDialog ad = new AlertDialog(context);
ad.setView(lv);
There is a bit more work than that though. You need to specify viewid which is the View representing each item in the ListView.
The sdk reference is very good you know.
new AlertDialog.Builder(this)
.setIcon(R.drawable.alert_dialog_icon)
.setTitle(R.string.alert_dialog_single_choice)
.setSingleChoiceItems(<ListAdapter> or CharaSequnce[] , 0, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked on a radio button do some stuff */
}
})
.setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked Yes so do some stuff */
}
})
.setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked No so do some stuff */
}
})
.create();
Note :
Please see This link to Api for Bold text mentioned below
.setSingleChoiceItems(CharacterSequnce[] , 0, new DialogInterface.OnClickListener()....
Hope this helps . Thanks :)