Skip to content
Advertisement

My activity_main.xml is not showing my contacts

In my Android Studio layout file for my MainActivity class, there is a layout that used to show my contacts but it doesn’t work anymore.

This is how the layout shows:

activity_main.xml

This is what shows in the emulator (note: I already have added contacts).

Outcome

I’m not sure if it has to do with the layout, the MainActivity itself or the Manifest.

The onCreate code that’s suppose to show contacts below the buttons:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler_view);

ContactModel dummy = new ContactModel();
dummy.setName("foo");
dummy.setNumber("123");
arrayList.add(dummy);

adapter = new MainAdapter(this, arrayList);
recyclerView.setAdapter(adapter);

Button add_btn = findViewById(R.id.add_btn);

add_btn.setOnClickListener(v -> startActivity(new Intent(MainActivity.this, Add_Contact.class)));

Button rem_btn = findViewById(R.id.rem_btn);

rem_btn.setOnClickListener(v -> startActivity(new Intent(MainActivity.this, Main_Remove_Contact.class)));
}

This is what my ContactModel looks like:

package com.app.wolfix;

public class ContactModel {
    String name, number;

    public String getName(){
        return name;
    }

    public void setName(String name) { this.name = name; }

    public String getNumber() { return number; }

    public void setNumber(String number) { this.number = number; }
}

Please don’t hesitate to ask for any piece of code necessary, I will edit the question if necessary.

Thanks in advance!

Advertisement

Answer

There are a few things wrong here (in the original version of the question):

  • You never actually created an instance of your adapter
  • You never assigned it to the RecyclerView
  • You never added any data to arrayList
  • You never set a layout manager for the RecyclerView.

Putting all of these together, the following onCreate works for me with your example to show dummy items in the list. You will need to add your actual code for populating arrayList somewhere in there still.

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

    RecyclerView recyclerView = findViewById(R.id.recycler_view);

    ContactModel dummy = new ContactModel();
    dummy.setName("foo");
    dummy.setNumber("123");
    arrayList.add(dummy);

    adapter = new MainAdapter(this, arrayList);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    recyclerView.setAdapter(adapter);

    // in your code, you could call something here to populate
    // arrayList with real values
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement