Programación y Desarrollo para Android Subforo exclusivo para temas de programación de software para PDAs y desarrollo de aplicaciones, interfaces, etc bajo Android


 
Herramientas
  #1  
Viejo 01/04/16, 13:51:56
Avatar de wasous
wasous wasous no está en línea
Usuario poco activo
Mensajes: 18
 
Fecha de registro: ene 2013
Mensajes: 18
Modelo de smartphone: samsung galaxy s2
Tu operador: Movistar
Mencionado: 0 comentarios
Tagged: 0 hilos
Problema con spinners. Ayuda porfavor.

Buenas, estoy creando una app para un trabajo de clase en la universidad y tengo un problema con una actividad, el problema es el siguiente, los spinners se me cargan leyendo de los archivos .txt tal y como yo quiero pero al añadirle un onClickListener o un simple textView.setText("hola"); me explota, da igual donde lo ponga, os pego aquí el código de la activity muchas gracias. Sin la fila que esta en rojo funciona, si la pongo ya no. AYUDA porfavooor.

public class Vendido extends AppCompatActivity {
Spinner categoriesSpinner;
String fich;
String fichObj,total,disponible;
TextView resto;
EditText unidades;
boolean valido;
int cantInicial,cantFinal,posicion;
List<String> categories,objetos,cantidadesList;
Spinner objetoSpinner;
Button vendido;
int totalEntradas;
ArrayAdapter<String> adaptador;
String[] categories2,cantidades,pocoStock;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
vendido = (Button)findViewById(R.id.vendido);
unidades = (EditText)findViewById(R.id.unidades);
resto = (TextView)findViewById(R.id.resto);
categories = new ArrayList<String>();

setContentView(R.layout.activity_vendido);
categoriesSpinner = (Spinner) findViewById(R.id.categoria);
objetoSpinner = (Spinner)findViewById(R.id.objeto);
fich="Categorias";
leerFichero(fich);
Log.d("Hector", "Fichero leido");
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, categories);
Log.d("Hector", "Creado adapter");
categoriesSpinner.setAdapter(adapter);
Log.d("Hector", "setAdapter hecho");




categoriesSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.d("Hector", "Dentro del 1 Spinner");
fichObj = categories.get(position);
leerFichero2(fichObj);
Log.d("Hector", "Fuera de leerFichero2");
objetoSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.d("Hector", "dentro de 2 spinner");
disponible = cantidadesList.get(position);
resto.setText("Disponible: "+disponible);
cantInicial = Integer.parseInt(cantidadesList.get(position));
posicion = position;

Log.d("Hector", "antes del listener");
}
@override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
@override
public void onNothingSelected(AdapterView<?> parent) {

}
});

}


protected boolean vender(int unidInicial,int posicion){
cantFinal = unidInicial - Integer.parseInt(unidades.getText().toString());
if (cantFinal<0){
Toast.makeText(this, "No tienes suficientes unidades", Toast.LENGTH_SHORT).show();
return false;
}
else{
total = Integer.toString(cantFinal);
Toast.makeText(this, "Te quedan "+total+" unidades", Toast.LENGTH_SHORT).show();
cantidadesList.set(posicion,total);
return true;
}
}

private void leerFichero(String fichero) {
String nomFichero = fichero +".txt";
Log.d("Hector", nomFichero);
categories.clear();
try {
String s;
int linea = 0;
InputStreamReader is = new InputStreamReader(openFileInput(nomFichero));
BufferedReader fich = new BufferedReader(is);
while ((s = fich.readLine()) != null) {// Leer hasta fin de fichero
categories.add(s);
linea++;
}
is.close(); // Cerrar el fichero
} catch (IOException ex) {
ex.printStackTrace();
Toast.makeText(this, "Error leyendo fichero", Toast.LENGTH_SHORT).show();
}
}
protected int leerFichero2 (String fichero)
{
String nomFichero=fichero+".txt";
totalEntradas= contarLineasFichero(nomFichero);
if (totalEntradas>0) {
categories2 = new String[totalEntradas/3];
cantidades = new String[totalEntradas/3];
pocoStock= new String[totalEntradas/3];
try {
String s;
int linea = 0;
Log.d("Hector", "al principio de leer fichero");
InputStreamReader is = new InputStreamReader(openFileInput(nomFichero));
BufferedReader fich = new BufferedReader(is);
while ((s = fich.readLine()) != null) {// Leer hasta fin de fichero
categories2[linea] = s;
cantidades[linea] = fich.readLine();
pocoStock[linea]=fich.readLine();

linea++;
}
Log.d("Hector", "al final de leer fichero");
is.close(); // Cerrar el fichero
} catch (IOException ex){
ex.printStackTrace();
Toast.makeText(this, "Error leyendo fichero", Toast.LENGTH_SHORT).show();
}
objetos = new ArrayList<String>();
cantidadesList = new ArrayList<String>();
objetos = Arrays.asList(categories2);
cantidadesList = Arrays.asList(cantidades);
adaptador = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, objetos);
objetoSpinner.setAdapter(adaptador);
}

return totalEntradas;
}
protected int contarLineasFichero (String nomFichero)
{
int lineas = 0;

try {
InputStreamReader is = new InputStreamReader(openFileInput(nomFichero));
BufferedReader fich = new BufferedReader(is);
String s;
// Leer hasta fin de fichero
while ((s = fich.readLine()) != null)
lineas++;
// Cerrar el fichero
is.close();
} catch (IOException ex){
ex.printStackTrace();
Toast.makeText(this, "Error contando líneas de "+nomFichero, Toast.LENGTH_SHORT).show();
}
return lineas;
}
protected void guardarFichero(String nomFichero) {
try {
File file = new File(getFilesDir(), nomFichero + ".txt");
BufferedWriter output = new BufferedWriter(new FileWriter(file));
Log.d("Hector", "al principio de guardar fichero");
boolean first = true;
int i = 0;
for (String category : categories2) {

if (category != null) {
if (first) {
first = false;
} else {
output.newLine();
Log.d("Hector", "new line");
}
output.write(category);
output.newLine();
output.write(cantidadesList.get(i));
output.newLine();
output.write(pocoStock[i]);

}
i++;
}
output.close();
} catch (Exception ex) {
Toast.makeText(this, "Error añadiendo categoría", Toast.LENGTH_SHORT).show();
}

}
Responder Con Cita


  #2  
Viejo 01/04/16, 13:53:54
Avatar de wasous
wasous wasous no está en línea
Usuario poco activo
Mensajes: 18
 
Fecha de registro: ene 2013
Mensajes: 18
Modelo de smartphone: samsung galaxy s2
Tu operador: Movistar
Mencionado: 0 comentarios
Tagged: 0 hilos
Lo siento por el tocho, lo de el final son funciones que he utilizado el onCreate es relativamente pequeño.
Responder Con Cita
  #3  
Viejo 01/04/16, 14:11:45
Avatar de mocelet
mocelet mocelet no está en línea
Desarrollador
Mensajes: 2,203
 
Fecha de registro: may 2011
Localización: Madrid
Mensajes: 2,203
Tu operador: -
Mencionado: 17 comentarios
Tagged: 2 hilos
El setContentView(R.layout.activity_vendido) lo tienes que poner antes de llamar a los findViewById o todas esas vistas estarán a null (de ahí la NullPointerException que te salta en la línea resto.setText)
Responder Con Cita
Gracias de parte de:
Respuesta

Estás aquí
Regresar   HTCMania > Todo sobre Android > Programación y Desarrollo para Android

Herramientas

Reglas de Mensajes
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Las caritas están On
Código [IMG] está On
Código HTML está Off

Saltar a Foro



Hora actual: 11:49:07 (GMT +1)

Cookies settings
Powered by vBulletin™
Copyright © vBulletin Solutions, Inc. All rights reserved.
 
HTCMania: líderes desde el 2007