0

Les pongo un ejemplo de mi profesor el cual usa un SimpleAdapter en el ListView y funciona perfectamente. Aqui el MainActivity:

public class MyListActivity extends MainMenu {

private String[] names={"Jaume Cabre","John Grishman","Santiago Postegui"};
private int[] photosWriters={R.drawable.jaumecabre,R.drawable.johngrishman,R.drawable.santiagoposteguillo};
private int[] photosBook={R.drawable.senyoria,R.drawable.theguardians,R.drawable.lalegionperdida};
private String[] books={"Senyoria", "The Guardians", "La Legion Perdida"};


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my_list);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    ListView myWriters;

    List<Map<String,Object>> data=new ArrayList<>();
    for (int i=0;i<names.length;i++){
        Map<String,Object> datum=new HashMap<>(2);
        datum.put("photo",photosWriters[i]);
        datum.put("name",names[i]);
        data.add(datum);
    }
    myWriters = findViewById(R.id.listWriters);
    SimpleAdapter simpleAdapter = new SimpleAdapter(
            this,data,R.layout.item_list, new String[] {"photo","name"}, new int[]{R.id.photo,R.id.name}
            );
    myWriters.setAdapter(simpleAdapter);

    myWriters.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            buildDialog(names[position], "Book" + ": " + books[position], position);
        }

    });

}

Aqui el layout item_list.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto">

<ImageView
    android:id="@+id/photo"
    app:srcCompat="@mipmap/ic_launcher"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:layout_weight="1"
    android:contentDescription="@string/image_icon" />

<TextView
    android:id="@+id/name"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:fontFamily="@font/trocchi"
    android:gravity="center"
    android:text=""
    android:textSize="24sp" />

</LinearLayout>

Y aqui el layout del MyListActivity content_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context=".MyListActivity"
tools:showIn="@layout/activity_my_list">

<TextView
    android:id="@+id/textWriters"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:fontFamily="casual"
    android:text="@string/textWriters"
    android:textAlignment="center"
    android:textSize="24sp"
    android:textStyle="bold|italic"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<ListView
    android:id="@+id/listWriters"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="56dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Todo ello, funciona bien. Pero en mi proyecto no funciona nada.

Ahora les pondre mi proyecto, el cual dentro de un SimpleAdapter como hizo mi profesor, yo debo colocar otro SimpleAdapter dentro del ListView del primer SimpleAdapter.

public class MainActivity extends AppCompatActivity {
ListView listViewShops, listViewProducts;
ArrayList<tendes> tendesDAO= new ArrayList<>();
ArrayList<tendes> tendesAfegides= new ArrayList<>();

int[] tmpimgshops={R.drawable.tenda_t1,R.drawable.tenda_t2,R.drawable.tenda_t3, R.drawable.tenda_t3, R.drawable.tenda_t4, R.drawable.tenda_t5, R.drawable.tenda_t6, R.drawable.tenda_t7, R.drawable.tenda_t8, R.drawable.tenda_t9, R.drawable.tenda_t10,  R.drawable.tenda_t11, R.drawable.tenda_t12, R.drawable.tenda_t13, R.drawable.tenda_t14, R.drawable.tenda_t15, R.drawable.tenda_t16};
int[] tmpimgproductes={R.drawable.producte_p1,R.drawable.producte_p2,R.drawable.producte_p3, R.drawable.producte_p4, R.drawable.producte_p5, R.drawable.producte_p6, R.drawable.producte_p7, R.drawable.producte_p8};
listViewShops=(ListView) findViewById(R.id.listView_shops);
listViewProducts=(ListView) findViewById(R.id.listView_products);

 @Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_shops);
    stringCopy(alimentacion);

    spinnerCategoria=(Spinner) findViewById(R.id.spinner_categoria);
    spinnerSubCategoria=(Spinner) findViewById(R.id.spinner_subcategoria);
    listViewShops=(ListView) findViewById(R.id.listView_shops);
    listViewProducts=(ListView) findViewById(R.id.listView_products);
    ProductesDAO productesDAO=new ProductesDAO(this);
    productesDB=productesDAO.getProductes();

    ArrayAdapter<String> itemsCategoria= new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, categories);
    itemsCategoria.setNotifyOnChange(true);
    spinnerCategoria.setAdapter(itemsCategoria);

    ArrayAdapter<String> itemsSubCategoria= new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, subcategories);
    itemsSubCategoria.setNotifyOnChange(true);
    spinnerSubCategoria.setAdapter(itemsSubCategoria);

try{
        tendesDAO=new TendesDAO(this);
        tendesAfegides=tendesDAO.getTendesAfegides();
        Log.d("ShopsActivity","onCreate");
        Log.d("ShopsActivity","shops.size(): "+tendesAfegides.size());
    }catch(IOException ex){
        ex.printStackTrace();
    }

    List<Map<String,Object>> data=new ArrayList<>();
for(int i=0;i<tendesAfegides.size();i++) {
        Log.d("ShopsActivity", "tendesAfegides(" + i + ")=" + tendesAfegides.get(i).getNom());
        productes = new ArrayList<>();
        productes = productesDAO.getProductesTenda(tendesAfegides.get(i).getCodi());
        try{
            List<Map<String,Object>> data2=new ArrayList<>();
            Map<String,Object> datum=new HashMap<>(2);
            datum.put("imgshop", tmpimgshops[i]);
            for(int j=0;j<productes.size();j++){
                Map<String,Object> datum2=new HashMap<>(2);
                datum2.put("imgproducte",tmpimgproductes[(j+(i*3))]);
                datum2.put("desproducte",productes.get(j).getDescripcio());
                data2.add(datum2);
            }
            SimpleAdapter simpleAdapterProductes=new SimpleAdapter(
                    this,data2,R.layout.products_list, new String[] {"imgproducte", "desproducte"}, new int[] {R.id.image_product,R.id.txt_description_product}
            );
            listViewProducts.setAdapter(simpleAdapterProductes);
            datum.put("productes",listViewProducts);
            data.add(datum);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    SimpleAdapter simpleAdapterShops=new SimpleAdapter(
            this,data,R.layout.shops_products,new String[] {"imgshop","productes"}, new int[] {R.id.imageViewShop, R.id.listView_products}
    );
    listViewShops.setAdapter(simpleAdapterShops);
}
}

Ahora los layouts del primer SimpleAdapter y del segundo: shops_products.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<ImageView
    android:id="@+id/imageViewShop"
    android:layout_width="150dp"
    android:layout_height="150dp"
    app:srcCompat="@android:drawable/sym_def_app_icon" />

<ListView
    android:id="@+id/listView_products"
    android:layout_width="150dp"
    android:layout_height="match_parent"
    android:orientation="vertical" />

</LinearLayout>

products_list.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="150dp"
android:layout_height="150dp"
android:gravity="center|top"
android:orientation="vertical">

<ImageView
    android:id="@+id/image_product"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:scaleType="fitCenter"
    app:srcCompat="@android:drawable/sym_def_app_icon" />

<TextView
    android:id="@+id/txt_description_product"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="TextView"
    android:textAlignment="center" />

</LinearLayout>

Y el layout del MyListActivity:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MyListActivity">

<LinearLayout
    android:id="@+id/linearLayout2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="20dp"
    android:orientation="horizontal"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/spinner_subcategoria">

    <ListView
        android:id="@+id/listView_shops"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </ListView>
</LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

Y el error que obtengo...:

W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
    at es.tiendaslocales.ShopsActivity.onCreate(MyListActivity.java:184)
    at android.app.Activity.performCreate(Activity.java:6320)
W/System.err:     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1113)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2530)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2665)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1499)
    at android.os.Handler.dispatchMessage(Handler.java:111)
    at android.os.Looper.loop(Looper.java:207)
    at android.app.ActivityThread.main(ActivityThread.java:5765)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:806)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)

La linea del error 'MyListActivity.java:184' es la linea dentro del for donde...: listViewProducts.setAdapter(simpleAdapterProductes);

Nose donde podra estar el error, porque la estructura, es exactamente la mismta que la del profesor, solo que cambiando el string de los titulos de los libros por un ListView donde coloco el otro SimpleAdapter....

1 respuesta 1

0

Si llamas a findViewById antes de llamar a setContentView te va a devolver null Prueba con esto:

public class MainActivity extends AppCompatActivity {

ListView listViewShops, listViewProducts;
ArrayList<tendes> tendesDAO;
ArrayList<tendes> tendesAfegides;

    @override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_my_list);
        listViewShops=(ListView) findViewById(R.id.listView_shops);
        listViewProducts=(ListView) findViewById(R.id.listView_products);
        //aqui va el resto de tu codigo
    }
}
2
  • Lo siento, si lo tenia en el onCreate, lo que pasa es que el codigo era muy extenso y se me olvido ponerlo.
    – Alejandro
    Commented el 23 jun. 2020 a las 17:24
  • Gracias por aclararlo. En ese caso debes inicializar tus listView despues de llamar a setContentView dentro del metodo onCreate
    – danms07
    Commented el 23 jun. 2020 a las 19:54

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.