String options[] = new String[3];
// options[0] = "Select IVC Option";
int i =0;
IDataObject emailobject = inMemoryCache_getDataObject("EMAIL_CONTACT");
IDataObject smsobject = inMemoryCache_getDataObject("SMS_CONTACT");
IDataObject voicecallobject = inMemoryCache_getDataObject("VOICE_CONTACT");
try {
if(emailobject != null){
options [i] = "Email";
i++;
}
if(smsobject != null){
options [i] = "SMS";
i++;
}
if(voicecallobject != null){
options [i] = "VoiceCall";
i++;
}
}catch (Exception e){
}Spinner ivcoptions; ivcoptions = (Spinner)view.findViewById(R.id.spinner);
ArrayAdapter<String> x = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_spinner_item,options);
x.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
ivcoptions.setAdapter(x);
I want the spinner click be disabled , if and only if the Spinner contains 1 item.
I have tried with controlling with the string array length. But it doesn't help.
If you want to disable spinner item click event, you'd need to change the adapter, however if you only want to prevent the spinner from being clicked on, you can simply register a data observer on your adapter:
final Spinner ivcoptions = (Spinner) findViewById(R.id.spinner);
final ArrayAdapter<String> x = new ArrayAdapter<>(this,
android.R.layout.simple_spinner_item,options);
x.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Register a data observer
x.registerDataSetObserver(new DataSetObserver() {
#Override
public void onChanged() {
super.onChanged();
if (x.getCount() == 1) {
ivcoptions.setEnabled(false);
} else {
ivcoptions.setEnabled(true);
}
}
});
// Set your adapter
ivcoptions.setAdapter(x);
Related
I'm having an issue while i'm looking to sort my Variables to fees Menues, i mean i have an ArrayList with data as "WITH PEPERONI,1," or "CHAMPAGNE,1,2," where ,1, or ,1,2, means the menu of the variable so when i press on Menu 1 i have to see only variables that had ,1, or ,1,2, or ,1,2,3, (where there is 1) in their array.
And actually what i've done works but only with variables that has multiple menues i mean if a variable is in menu 1,2,3,4 and i press on 2 that will be visible but if the variable is just in one menu as 1 so ,1, in array that will be not visualized and i can't get why.
here is my code where i filter the variables and set them in a new Array:
public void FilterVariable() {
filteredVariable = new ArrayList<>();
for (VariantiConstructor varianti : variantiConstructors) {
String data = varianti.getMenu();
String[] items = data.split("," + positionMenu + ",");
try {
if (items[0].equals(data)) {
//
} else {
filteredVariable.add(varianti);
}
} catch (Exception e) {
//
}
}
}
While here is a screen from where i was debugging and where there was a ,2, and it skipped it insteam of adding in the ArrayList:
You need to use the following code for the shorting the ArrayList
ArrayList<String> YOUR_ARRAYLIST = new ArrayList<>();
private void searchDataFromList(String serachString) {
ArrayList<String> SEARCH_ARRAYLIST = new ArrayList<>();
for (int i = 0; i < YOUR_ARRAYLIST.size(); i++) {
if (serachString.contains(YOUR_ARRAYLIST.get(i))) {
SEARCH_ARRAYLIST.add(YOUR_ARRAYLIST.get(i));
}
}
}
On your click listener, u need to call this searchDataFromList() method as following
YOUR_CLICK.setOnClickListener(view -> {
String searchString ="WITH PEPERONI,1,";
String YOUR_SEARCH_STRING ="";
List<String> YOUR_SELECETD_LIST = Arrays.asList(searchString.split(","));
for (int i = 0; i <YOUR_SELECETD_LIST.size(); i++) {
if (YOUR_SELECETD_LIST.get(i).length()==1)
{
YOUR_SEARCH_STRING = YOUR_SELECETD_LIST.get(i);
System.out.println("VALUE IS ==>>>>> "+YOUR_SEARCH_STRING);
}
}
if (!YOUR_SEARCH_STRING.isEmpty())
{
searchDataFromList(YOUR_SEARCH_STRING);
}
I call the method below to update my listview
ListView list = (ListView) listView.findViewById(R.id.plan_list);
itemsList = sortAndAddSections(getItems_search(name));
ListAdapter adapter = new ListAdapter(getActivity(), itemsList);
list.setAdapter(adapter);
but that code is associated with a value that changes and also this is the other code
private ArrayList<plan_model> getItems_search(String param_cusname) {
Cursor data = myDb.get_search_plan(pattern_email, param_name);
int i = 0;
while (data.moveToNext()) {
String date = data.getString(3);
String remarks = data.getString(4);
items.add(new plan_model(cusname, remarks);
}
return items;
}
and this is my sorter
private ArrayList sortAndAddSections(ArrayList<plan_model> itemList) {
Collections.sort(itemList);
plan_model sectionCell;
tempList.clear();
tmpHeaderPositions.clear();
String header = "";
int addedRow = 0;
int bgColor = R.color.alt_gray;
for (int i = 0; i < itemList.size(); i++) {
String remarks = itemList.get(i).getRemarks();
String date = itemList.get(i).getDate();
if (!(header.equals(itemList.get(i).getDate()))) {
sectionCell = new plan_model(remarks, date);
sectionCell.setToSectionHeader();
tmpHeaderPositions.add(i + addedRow);
addedRow++;
tempList.add(sectionCell);
header = itemList.get(i).getDate();
bgColor = R.color.alt_gray;
}
sectionCell = itemList.get(i);
sectionCell.setBgColor(bgColor);
tempList.add(sectionCell);
if (bgColor == R.color.alt_gray) bgColor = R.color.alt_white;
else bgColor = R.color.alt_gray;
}
tmpHeaderPositions.add(tempList.size());
for (int i = 0; i < tmpHeaderPositions.size() - 1; i++) {
sectionCell = tempList.get(tmpHeaderPositions.get(i));
sectionCell.setDate(sectionCell.getDate() + " (" +
(tmpHeaderPositions.get(i + 1) - tmpHeaderPositions.get(i) - 1) + ")");
}
return tempList;
}
my question is the value name changes but my listview is not how can I update my listview? because i need to update it based on search parameter
If your itemList is being updated properly, you don't need to create another instance of the adapter, just use notifyDataSetChanged():
private void createList() {
ListView list = (ListView) listView.findViewById(R.id.plan_list);
itemsList = sortAndAddSections(getItems_search(name));
adapter = new ListAdapter(getActivity(), itemsList);
list.setAdapter(adapter);
}
private void updateList() {
sortAndAddSections(getItems_search(name)); // Update itemList without re-assign its value, otherwise the adapter will loose reference
adapter.notifyDataSetChanged()
}
In getItems_search() add this line at the beginning:
items.clear();
Every time the value of name changes you have to do the following:
itemsList.clear();
itemsList = sortAndAddSections(getItems_search(name));
list.setAdapter(new ListAdapter(getActivity(), itemsList));
I'm using two Spinners to show the items I'm getting from the json response. I have 2 problems right now. When u check my logcat u can see there are items repeating (Right side list, u can see so many pan). I want to have 1 item only once in my Spinner. I want to use something similar to distinct we use in sql databases.
My second problem is,
Select pan in the 1 spinner then 2nd spinner should contain items related to pan. (select pan in 1st spinner and 2nd should display only Pan large, pan medium and personal pan)
#Override
public void onTaskCompleted(JSONArray responseJson) {
try {
List<String> crust = new ArrayList<String>();
List<String> description = new ArrayList<String>();
List<String> extraDescription = new ArrayList<String>();
for (int i = 0; i < responseJson.length(); ++i) {
JSONObject object = responseJson.getJSONObject(i);
if ((object.getString("MainCategoryID")).equals("1")
&& (object.getString("SubCategoryID")).equals("1")) {
JSONArray subMenuArray = object
.getJSONArray("SubMenuEntity");
for (int j = 0; j < subMenuArray.length(); ++j) {
JSONObject subMenuObject = subMenuArray
.getJSONObject(j);
Log.i("Crust", subMenuObject.getString("Crust"));
crust.add(subMenuObject.getString("Crust"));
Log.i("Description",
subMenuObject.getString("Description"));
description.add(subMenuObject.getString("Description"));
JSONArray extraItemEntityArray = subMenuObject
.getJSONArray("ExtraItemEntity");
}
}
crustSP = (Spinner) findViewById(R.id.sp_crust);
ArrayAdapter<String> dataAdapterCru = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, crust);
dataAdapterCru
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
crustSP.setAdapter(dataAdapterCru);
sizeSP = (Spinner) findViewById(R.id.sp_pizza_size);
ArrayAdapter<String> dataAdapterDes = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, description);
dataAdapterDes
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sizeSP.setAdapter(dataAdapterDes);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Output of this
Call this method to get distinct descriptions and then set the adapter using the return value of this function...
public static ArrayList<String> removeDuplicatesFromList(ArrayList<String> descriptions)
{
ArrayList<String> tempList = new ArrayList<String>();
for(String desc : descriptions)
{
if(!tempList.contains(desc))
{
tempList.add(desc);
}
}
descriptions = tempList;
tempList = null;
return descriptions;
}
For instance
description = Utils.removeDuplicatesFromList(description);
ArrayAdapter<String> dataAdapterDes = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, description);
NOTE:
I would suggest you make a new class call it Utils.java and place the above method inside it and then call it i have mentioned above.
Like this...
import java.util.ArrayList;
public class Utils
{
private Utils()
{
//Its constructor should not exist.Hence this.
}
public static ArrayList<String> removeDuplicatesFromList(ArrayList<String> descriptions)
{
ArrayList<String> tempList = new ArrayList<String>();
for(String desc : descriptions)
{
if(!tempList.contains(desc))
{
tempList.add(desc);
}
}
descriptions = tempList;
tempList = null;
return descriptions;
}
}
I hope it helps.
I have two spinners in an AlertDialog, the spinners look good, and the list of items is correct, it shows the first items of each list. But when I click any of the two spinner, the dropdown list is not displayed to select some other item. The spinners do nothing. This does not happen when I was the same two spinners outside the AlertDialog.
This is the code of AlertDialog:
private void mostrar_alertdialog_spinners() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
TextView title = new TextView(this);
title.setText("Selecciona un archivo:");
title.setPadding(10, 10, 10, 10);
title.setGravity(Gravity.CENTER);
title.setTextColor(Color.rgb(0, 153, 204));
title.setTextSize(23);
builder.setCustomTitle(title);
LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout_spinners = inflater.inflate(R.layout.layout_spinners,null);
sp_titulos_carpetas = (Spinner) layout_spinners.findViewById(R.id.spinner_titulo_carpetas);
sp_titulos_textos = (Spinner) layout_spinners.findViewById(R.id.spinner_textos_carpetas);
builder.setView(layout_spinners);
builder.setCancelable(false);
builder.show();
//configuracion de textos en memoria sd
String path = Environment.getExternalStorageDirectory().toString()+"/Textos/";
File f = new File(path);
String[] fileStr = f.list();
ArrayList<String> lista_lista_CARPETAS = new ArrayList<String>();
for (String lista_texto : fileStr) {
lista_lista_CARPETAS.add(lista_texto);
}
Collections.sort(lista_lista_CARPETAS, new AlphanumComparator());
String[] lista_k = f.list(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
File f = new File(dir, name);
return f.isDirectory();
}
});
FileFilter fileFilter = new FileFilter() {
public boolean accept(File file) {
return file.isDirectory();
}
};
File[] files = f.listFiles(fileFilter);
ArrayAdapter<String> carpetas = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, lista_k);
carpetas.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
sp_titulos_carpetas.setAdapter(carpetas);
//ARRAY CON TITULOS DE ARCHIVOS TXT
String camino = Environment.getExternalStorageDirectory().toString()+"/Textos/" + "Naxos"+ "/";
File t = new File(camino);
String[] lista_textos = t.list();
ArrayList<String> lista_lista_textos = new ArrayList<String>();
for (String lista_texto : lista_textos) {
if (lista_texto.toLowerCase().endsWith(".txt")) {
lista_lista_textos.add(lista_texto);
}
}
for (int index =0; index < lista_lista_textos.size(); index++){
lista_lista_textos.set(index, WordUtils.capitalizeFully(lista_textos[index].toLowerCase().replace(".txt", "")));
}
Collections.sort(lista_lista_textos, new AlphanumComparator());
ArrayAdapter<String> adaptador_textos = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, lista_lista_textos);
adaptador_textos.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
sp_titulos_textos.setAdapter(adaptador_textos);
sp_titulos_textos.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String nombre_texto = parent.getSelectedItem().toString();
File sdcard = new File( Environment.getExternalStorageDirectory().toString()+"/Textos/" + "Naxos/");
//Get the text file
File file = new File(sdcard, nombre_texto);
//Read text from file
StringBuilder text = new StringBuilder();
int BUFFER_SIZE = 8192;
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "Cp1252"),BUFFER_SIZE);
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
}
catch (IOException e) {
//You'll need to add proper error handling here
}
String nuevoTexto = text.toString().replaceAll("\t", " ");
String nuevoTextoA = nuevoTexto.replaceAll("\n", " ");
Holmes1 = nuevoTextoA;
delimitadores = " ";
tokenHolmes1 = new StringTokenizer(Holmes1, " ");
arrayHolmes1 = Holmes1.split(delimitadores);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
And the xml for the spinners:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:weightSum="100"
style="#style/spinner_rojo">
<Spinner
android:id="#+id/spinner_titulo_carpetas"
android:layout_width="0dp"
style="#style/spinner_rojo"
android:background="#drawable/spinner_background_holo_light"
android:layout_height="wrap_content"
android:layout_weight="50"></Spinner>
<Spinner
android:id="#+id/spinner_textos_carpetas"
android:layout_width="0dp"
style="#style/spinner_rojo"
android:background="#drawable/spinner_background_holo_light"
android:layout_height="wrap_content"
android:layout_weight="50"></Spinner>
</LinearLayout>
And an image:
Anyone know any possible sulucion to show the drop down list?
I just copied your code and edit ArrayList. It totally worked for me.
private void mostrar_alertdialog_spinners() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
TextView title = new TextView(this);
title.setText("Selecciona un archivo:");
title.setPadding(10, 10, 10, 10);
title.setGravity(Gravity.CENTER);
title.setTextColor(Color.rgb(0, 153, 204));
title.setTextSize(23);
builder.setCustomTitle(title);
LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout_spinners = inflater.inflate(R.layout.spinner_layout,null);
Spinner sp_titulos_carpetas = (Spinner) layout_spinners.findViewById(R.id.spinner_titulo_carpetas);
Spinner sp_titulos_textos = (Spinner) layout_spinners.findViewById(R.id.spinner_textos_carpetas);
builder.setView(layout_spinners);
builder.setCancelable(false);
builder.show();
ArrayList<String> lista_k = new ArrayList<String>();
lista_k.add("Path A");
lista_k.add("Path B");
ArrayAdapter<String> carpetas = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, lista_k);
carpetas.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
sp_titulos_carpetas.setAdapter(carpetas);
ArrayList<String> lista_lista_textos = new ArrayList<String>();
lista_lista_textos.add("Path C");
lista_lista_textos.add("Path D");
ArrayAdapter<String> adaptador_textos = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, lista_lista_textos);
adaptador_textos.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
sp_titulos_textos.setAdapter(adaptador_textos);
sp_titulos_textos.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
Move this to the end of the code, so you are doing it after setting everything up:
builder.show();
Create custom alert dialog for same. Try this
Dialog new_dialog = new Dialog(getParent());
// new_dialog.setTitle("Book your appointment");
new_dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
new_dialog.setContentView(R.layout.customize_dialog_list_view);
new_dialog.setCancelable(false);
cuc = new CommanUtilityClass();
SharedPreferences sp = getSharedPreferences("provider",0);
String services = sp.getString("services", "");
TextView service = (TextView) new_dialog
.findViewById(R.id.cdlv_service_provider);
TextView hour = (TextView) new_dialog.findViewById(R.id.cdlv_working_hours);
TextView appointment_time = (TextView) new_dialog.findViewById(R.id.cdlv_appoint_time);
TextView appointment_date = (TextView) new_dialog.findViewById(R.id.cdlv_appoint_date);
//String[] ampm = myTiming[which].split(":");
/*String[] range = myTiming[which].split(":");
int startTimeInt = Integer.parseInt(range[0])
* 60 + Integer.parseInt(range[1]);
String finalvalue = "";
if(startTimeInt >= 720){
if(startTimeInt >= 780){
}else{
}
}else{
finalvalue = String.valueOf(range[0] + ":" + range[1] + " AM");
}
for (int i = 0; i < range.length; i++) {
String startTimeString = range[i].split("-")[0];
String endTimeString = range[i].split("-")[1];
Log.d("Minutes", "startTimeString = " + startTimeString);
Log.d("Minutes", "endTimeString = " + endTimeString);
int startTimeInt = Integer.parseInt(startTimeString.split(":")[0])
* 60 + Integer.parseInt(startTimeString.split(":")[1]);
int endTimeInt = Integer.parseInt(endTimeString.split(":")[0]) * 60
+ Integer.parseInt(endTimeString.split(":")[1]);
}*/
appointment_time.setText(Html.fromHtml("<b>Appointment time :</b>" + myTimingToShow[which].split("/")[0]));
appointment_date.setText(Html.fromHtml("<b>Appointment date :</b>" + selected));
service.setText(Html
.fromHtml("<b>Service provider :</b>"
+ cuc.toTheUpperCase(bsp_name)));
hour.setText(Html
.fromHtml("<b>Working hours :</b>"
+ cuc.toTheUpperCase(bsp_availability)));
try {
lv = (ListView) new_dialog
.findViewById(R.id.cdlv_list);
CustomDialogArrayAdapter cdaa = new CustomDialogArrayAdapter(
getApplicationContext(),
m_ArrayList);
lv.setAdapter(cdaa);
} catch (Exception e) {
e.printStackTrace();
}
new_dialog.show();
Here I have just inflated xml layout to alert dialog. Make sure you fetch each spinner with context to dialog. See above code for same.
Hope it helps. Cheers!
Due to memory leak, happening so, When you are opening the one spinner it is able to get the valid context, but second time when you are trying to retrieve the another spinner it's actually getting null as a context and not populating anything. But When you are using both the spinner in Activity out of Alert-Dialog, its' actually getting a valid context always. Thus for that time you are not getting any error and it populates correctly.
So, to avoid memory leak, use getApplicationContext() to retrieve the context for spinner ArrayAdapter
ArrayAdapter<String> carpetas = new ArrayAdapter<String>
(getApplicationContext(),android.R.layout.simple_spinner_item, lista_k);
ArrayAdapter<String> adaptador_textos = new ArrayAdapter<String>
(getApplicationContext(),android.R.layout.simple_spinner_item, lista_lista_textos);
public class FareActivity extends Activity {
int fareid;
String Source;
String Dest;
AutoCompleteTextView source;
AutoCompleteTextView dest;
static final String[] SOURCE = new String[] {
"Delhi", "Mumbai", "Agra", "Jaipur};
static final String[] DEST = new String[] {
"Delhi", "Mumbai", "Agra", "Jaipur};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fare);
dest = (AutoCompleteTextView) findViewById(R.id.acdest);
ArrayAdapter<String> dadapter = new ArrayAdapter<String>(this, R.layout.list_item, DEST);
dest.setAdapter(dadapter);
source = (AutoCompleteTextView) findViewById(R.id.acsource);
ArrayAdapter<String> sadapter = new ArrayAdapter<String>(this, R.layout.list_item, SOURCE);
dest.setAdapter(sadapter);
// Fare id calculation
if(Source=="Delhi" && Dest=="Jaipur")
{
fareid=1;
}
else if(Source=="Delhi" && Dest=="Agra")
{
fareid=2;
}
else if(Source=="Delhi" && Dest=="Mumbai")
{
fareid=3;
}
}
I just want to store autocompletetextview 'source' and autocompletetextview 'dest' values to String variable 'Source' and String Variable 'Dest'. I will use both string variables for further processing in my project, so please help me out.
Just use the AutoCompleteTextView method getText() and call toString() on it.
// Fare id calculation
Source = source.getText().toString();
Dest = dest.getText().toString();
if (Source.equals("Delhi") && Dest.equals("Jaipur")) {
fareid=1;
}
else if (Source.equals("Delhi") && Dest.equals("Agra")) {
fareid=2;
}
else if (Source.equals("Delhi") && Dest.equals("Mumbai")) {
fareid=3;
}
You should keep in mind that users can enter everything they want into your AutoCompleteTextView. If you want to perform an action when the user chooses one of the suggested items, add an OnItemSelectedListener with dest.setOnItemSelectedListener().
There is also an error in your code you call dest.setAdapter(sadapter) instead of source.setAdapter(sadapter).
AutoCompleteTextView source = (AutoCompleteTextView) findViewById(R.id.acsource);
String Source = source.getText().toString();