Home > front end >  My ListView is not appearing when I transition to the next page
My ListView is not appearing when I transition to the next page

Time:02-11

I am currently using the default layout on in my program. The first page is good, it goes to the next page with no issues. The second page where I have the listview, it doesnt show

.java file

package com.example.alimkutchhi_comp304_001_assign2;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;

public class SelectPhoneBrandActivity extends AppCompatActivity {

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

        ListView listview = findViewById(R.id.lstvPhones);

        ArrayList<String> phones = new ArrayList<>();
        phones.add("iPhone");
        phones.add("Samsung");
        phones.add("Google Pixel");
        phones.add("Huawei");

        ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_2, phones);

    }
}

I followed a tutorial so I know this should be the correct format This is what I wrote in my .xml file

<?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=".SelectPhoneBrandActivity">

    <ListView
        android:id="@ id/lstvPhones"
        android:layout_width="379dp"
        android:layout_height="699dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Again, this should be correct, so maybe it has something to do with Android Studio? Hopefully I can get an answer to this issue.

CodePudding user response:

I was able to figure this one out thankfully. What I forgot to do was add listview.setAdapter(adapter); to it

The bottom line of the java file is now this

 ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, phones);
        listview.setAdapter(adapter);

I also made the mistake of my layout being wrong, its simple list item 1 that should be used

Thank you for the help. I will use this place better next time

  • Related