Cómo comprobar NULL en etiquetas XML XML analizadas
Actualmente estoy construyendo esta aplicación android y lo único que me ha stumped es la manija ListView
elementos que muestran en el orden que los necesito, pero si una etiqueta tiene un valor en blanco que se muestra como un solo objeto de línea que ocupan nada, pero el espacio y el espaciado el diseño.
- Cambiar del diseño main.xml a otro diseño
- Android ImageButton - no se puede obtener la imagen en el centro
- Cómo generar simple-xml java objeto anotado desde el esquema xsd
- La generación de Gradle falla debido a la entrada duplicada en strings.xml
- Símbolo de escape de Android XML "@"
Todo el espacio en estas imágenes ListView items es una cadena Null que se está enviando y lo analizo. Simplemente me gustaría saber la mejor manera de manejar este error?
Mi XML para los elementos ListView:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:id="@+id/ContactTitle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:textAppearance="?android:attr/textAppearanceMedium" android:textColor="@color/White" /> <TextView android:id="@+id/Name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignRight="@+id/ContactTitle" android:layout_below="@+id/ContactTitle" android:layout_marginRight="17dp" android:textColor="@color/White" /> <TextView android:id="@+id/MainPhone" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignRight="@+id/Name" android:layout_below="@+id/Name" android:textColor="@color/White"/> <TextView android:id="@+id/Cell" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignRight="@+id/MainPhone" android:layout_below="@+id/MainPhone" android:textColor="@color/White" /> <TextView android:id="@+id/Fax" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/Cell" android:layout_below="@+id/Cell" android:textColor="@color/White" /> <TextView android:id="@+id/Email" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/Fax" android:layout_below="@+id/Fax" android:ellipsize="marquee" android:textColor="@color/EmailColor" /> </RelativeLayout>
Tengo que comprobar si las TextViews
vacías y ocultarlas. Mi código está aquí:
protected void onPostExecute(String result) { String xml = result; String KEY_ITEM = "Contact"; String KEY_CONTACTTITLE = "ContactTitle"; String KEY_NAME = "Name"; String KEY_MAINPHONE = "Phone"; String KEY_CELLPHONE = "Cell"; String KEY_FAX = "Fax"; String KEY_EMAIL = "Email"; ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>(); Document doc = getDomElement(xml); if (xml != null) { { NodeList nl = doc.getElementsByTagName(KEY_ITEM); for (int i = 0; i < nl.getLength(); i++) { HashMap<String, String> map = new HashMap<String, String>(); Element e = (Element) nl.item(i); if (getValue(e, KEY_CONTACTTITLE) != null) { map.put(KEY_CONTACTTITLE, getValue(e, KEY_CONTACTTITLE)); } else { TextView contactTitle = (TextView) findViewById(R.id.ContactTitle); } if (getValue(e, KEY_NAME) != null) { map.put(KEY_NAME, getValue(e, KEY_NAME)); } if (getValue(e, KEY_MAINPHONE) != null) { map.put(KEY_MAINPHONE, getValue(e, KEY_MAINPHONE)); } if (getValue(e, KEY_CELLPHONE) != null) { map.put(KEY_CELLPHONE, getValue(e, KEY_CELLPHONE)); } if (getValue(e, KEY_FAX) != null) { map.put(KEY_FAX, getValue(e, KEY_FAX)); } if (getValue(e, KEY_EMAIL) != null) { map.put(KEY_EMAIL, getValue(e, KEY_EMAIL)); } menuItems.add(map); menuItems = simple; } String[] hashMapObjects = { KEY_CONTACTTITLE, KEY_NAME, KEY_MAINPHONE, KEY_CELLPHONE, KEY_FAX, KEY_EMAIL }; int[] listItemObjects = { R.id.ContactTitle, R.id.Name, R.id.MainPhone, R.id.Cell, R.id.Fax, R.id.Email }; ListAdapter adapter = new SimpleAdapter( MoveContactsActivity.this, menuItems, R.layout.listed_contacts, hashMapObjects, listItemObjects); setListAdapter(adapter);
Estoy tratando de comprobar si el valor es nulo para agregar el objeto a la HashMap
. Esto, por supuesto, no funciona y me pregunto cómo comprobar para esos null
TextViews
y TextViews
.
- Android: Utilizar matriz de color en XML
- Almacenar datos estáticos en Android - recurso personalizado?
- Hacer una forma triangular con definiciones xml?
- EditText oculto por el teclado cuando android: gravity = "center" - Android
- Android: Uso de StreetViewPanoramaView en XML
- Conflicto strings.xml en el manifiesto de Android
- El azulejo estirable a veces estira
- Disposición del botón de Android: consigue dos botones lado a lado en toda la pantalla
Sólo necesita llamar View.setVisibility(View.GONE)
si no hay nada que mostrar en TextView
. Dado que está utilizando SimpleAdapter
y no tiene ningún método getView
personalizado, la forma más sencilla de hacerlo es utilizar SimpleAdapter.ViewBinder
:
String[] hashMapObjects = { KEY_CONTACTTITLE, KEY_NAME, KEY_MAINPHONE, KEY_CELLPHONE, KEY_FAX, KEY_EMAIL }; int[] listItemObjects = { R.id.ContactTitle, R.id.Name, R.id.MainPhone, R.id.Cell, R.id.Fax, R.id.Email }; SimpleAdapter adapter = new SimpleAdapter(MoveContactsActivity.this, menuItems, R.layout.listed_contacts, hashMapObjects, listItemObjects); SimpleAdapter.ViewBinder binder = new SimpleAdapter.ViewBinder() { @Override public boolean setViewValue(View view, Object object, String value) { if (!(view instanceof TextView)) { return false; } final TextView text = (TextView) view; text.setVisibility(TextUtils.isEmpty(value) ? View.GONE : View.VISIBLE); text.setText(value); return true; } }; adapter.setViewBinder(binder); setListAdapter(adapter);
No conozco su estructura de elementos de vista de lista.
Mi sugerencia es:
comprobar si la etiqueta es nula y hacer algo para resolver este problema como el conjunto TextView visibilidad = GONE.
Como dijo William, se puede extender el adaptador simple para agregar la visibilidad a la vista si el texto es nulo o vacío:
public class MyAdapter extends SimpleAdapter { public MyAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) { super(context, data, resource, from, to); } @Override public View getView(int position, View convertView, ViewGroup parent) { if(convertView!=null) //reset the visibility if a convert view is used convertView.setVisibility(View.VISIBLE); View v = super.getView(position, convertView, parent); //text recovering from data source. here I check the name field //you can add any test and hide any views using views id and setVisibility method String displayedText = ((HashMap<String, String>) this.getItem(position)).get("Name"); if( displayedText == null || displayedText.isEmpty()) v.setVisibility(View.GONE); return v; } }
use esta clase en lugar de SimpleAdapter, entonces puede chage el método getView para agregar condiciones en cualquier campo de cualquier vista de su ListView.
para obtener información: getView devuelve la vista que se mostrará en una posición determinada en el ListView, puede cambiar cualquier cosa en esas vistas según la fuente de datos recuperando el elemento en la posición dada.
Simplemente evite agregar valores nulos a su colección que se pasa al adaptador para rellenar la vista de lista
boolean elementFound = false; for (int i = 0; i < nl.getLength(); i++) { HashMap<String, String> map = new HashMap<String, String>(); Element e = (Element) nl.item(i); elementFound = false; if (getValue(e, KEY_CONTACTTITLE) != null) { map.put(KEY_CONTACTTITLE, getValue(e, KEY_CONTACTTITLE)); elementFound = true; } else { TextView contactTitle = (TextView) findViewById(R.id.ContactTitle); } if (getValue(e, KEY_NAME) != null) { map.put(KEY_NAME, getValue(e, KEY_NAME)); elementFound = true; } if (getValue(e, KEY_MAINPHONE) != null) { map.put(KEY_MAINPHONE, getValue(e, KEY_MAINPHONE)); elementFound = true; } if (getValue(e, KEY_CELLPHONE) != null) { map.put(KEY_CELLPHONE, getValue(e, KEY_CELLPHONE)); elementFound = true; } if (getValue(e, KEY_FAX) != null) { map.put(KEY_FAX, getValue(e, KEY_FAX)); elementFound = true; } if (getValue(e, KEY_EMAIL) != null) { map.put(KEY_EMAIL, getValue(e, KEY_EMAIL)); elementFound = true; } if(elementFound){ menuItems.add(map); } //I don't understand whay are you doing this //menuItems = simple; }
compruebe su valor con String
no vacía también como:
if (getValue(e, KEY_NAME) != null && !getValue(e,KEY_NAME).toString().equalsIgnoreCase("")) { map.put(KEY_NAME, getValue(e, KEY_NAME)); }
Está utilizando SimpleAdapter
. Es bueno, pero creo que la gestión del cambio es la clave del software. Debe extender BaseAdapter
y debe manejar el método getView
.
Sé SimpleAdapter
es bastante rápido para implementar, pero cuando los cambios vienen, le acosarán. Si usted escribe un archivo más ahora mismo para el adaptador personalizado que se relajará cuando los cambios vienen.
ArrayList<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>(); @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = infalter.inflate(R.layout.list_row, null); holder = new ViewHolder(); holder.tvRawName = (TextView) convertView .findViewById(R.id.tvRawName ); holder.tvRawEmail= (TextView) convertView .findViewById(R.id.tvRawEmail); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } try { if(data.get(position).get("Email")!=null && data.get(position).get("Email").length()>0) { holder.tvRawEmail.setVisibility(View.VISIBLE); holder.tvRawEmail.setText(data.get(position).get("Email")); }else { holder.tvRawEmail.setVisibility(View.GONE); } } catch (Exception e) { e.printStackTrace(); } //do like for all return convertView; } public class ViewHolder { TextView tvRawName; TextView tvRawEmail; }
- Estilo sherlock ActionMode fondo
- Cómo cambiar el color de las líneas de TimePicker en el tema Appcompat?