I am trying to make an item list view with titles, prices and category of gasoline, to be seen in this item list view.
I am new to android and I am not sure that I could have failed in my code. My project manages to compile and execute but when entering that section of the code, both the emulator and the phone will crash the app.
Here the code.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class ListadoActivity extends AppCompatActivity {
ListView lista;
ArrayAdapter adaptador;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// instancia de ListView
lista = (ListView) findViewById(R.id.lista);
// inicializar el adaptador y la fuente de datos
adaptador = new ProductoArrayAdapter(this,DataSource.PRODUCTOS);
// relacionado la lista al adaptador
lista.setAdapter(adaptador);
}
}
DataSource.java
import java.util.ArrayList;
import java.util.List;
public class DataSource {
static List PRODUCTOS = new ArrayList<Producto>();
static{
PRODUCTOS.add(new Producto("Gasolina Magna" , "$10.91",
R.drawable.ic_magna));
PRODUCTOS.add(new Producto("Gasolina Premium" , "$12.10",
R.drawable.ic_premium));
PRODUCTOS.add(new Producto("Diesel" , "$14.20", R.drawable.ic_diesel));
}
}
ProductArrayAdapter.java public class ProductArrayAdapter extends ArrayAdapter {
public ProductoArrayAdapter(Context context, List<Producto> objects) {super(context,0, objects);}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
//Obteniendo una instancia de inflater
LayoutInflater inflater = (LayoutInflater)
getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//Salvando la referencia del view de la fila
View listItemView = convertView;
//Comprobando si el Viwe no existe
if(null == convertView){
//Si no existe, entonces inflarlo con image_list_view.xml
listItemView = inflater.inflate(R.layout.image_list_item, parent,
false);
}
//Obteniendo instancia de los TextViews
TextView titulo = (TextView) listItemView.findViewById(R.id.text1);
TextView subtitulo = (TextView) listItemView.findViewById(R.id.text2);
ImageView categoria = (ImageView)
listItemView.findViewById(R.id.category);
//Obteniendo instancia de la Tarea en la posicion actual
Producto item = getItem(position);
titulo.setText(item.getNombre());
subtitulo.setText(item.getPrecio());
categoria.setImageResource(item.getcategoria());
//Devolver al ListView la fila creada
return listItemView;
}
}
Product.java
public class Producto {
private String nombre;
private String precio;
private int categoria;
public Producto(String nombre, String precio, int categoria){
this.nombre = nombre;
this.precio = precio;
this.categoria = categoria;
}
public void setNombre(String nombre){
this.nombre = nombre;
}
public void setPrecio(String precio){
this.precio = precio;
}
public void setCategoria(int categoria){this.categoria = categoria;
}
public String getNombre(){ return nombre; }
public String getPrecio(){ return precio; }
public int getcategoria(){ return categoria; }
}
activity_listado.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/green"
android:orientation="vertical">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/lista"/>
</LinearLayout>
image_list_item.xml
<?xml version="1.0" encoding="utf-8"?>
Error message
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.pablo.gasolinerasbarclin, PID: 16819
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.pablo.gasolinerasbarclin/com.example.pablo.gasolinerasbarclin.ListadoActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2927)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2988)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1631)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6682)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at com.example.pablo.gasolinerasbarclin.ListadoActivity.onCreate(ListadoActivity.java:24)
at android.app.Activity.performCreate(Activity.java:6942)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2880)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2988)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1631)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6682)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
Application terminated.