Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android Build a Blog Reader Android App Rebuilding from Scratch Adding Data for the List

Why can I not declare my ArrayAdapter as private?

The error I get is "Illegal start of expression". If I remove the 'private' keyword, then my code passes the test.

com/example/MainListActivity.java
package com.example;

import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;

public class MainListActivity extends ListActivity {
  public String mSongTitles[] = {"Wah","tjg","kfg"};
    @Override
    public void onCreate(Bundle savedInstanceState) {
      private ArrayAdapter <String> adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,mSongTitles);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_list);
    }
}
Ragnar Sinikas
Ragnar Sinikas
11,573 Points

This ArrayAdapter is in the method, you can declare it as member variable as a private field....

What is the difference and how do I make the distinction?

Ragnar Sinikas
Ragnar Sinikas
11,573 Points

Any variable set up inside of a method can't be accessed outside of that method. It's known as a local variable - it's local to the method. But when you declare it outside of the method as public String mSongTitles[] = {"Wah","tjg","kfg"}; then you can make it public, private or protected

Thank you very much. That's just the reminder I needed.

1 Answer

Joseph Greene
PLUS
Joseph Greene
Courses Plus Student 7,638 Points

It's all about scope. If you want a variable of any kind to be seen outside it's parent method then it can't be private. This is a good thing. You should always strive for a degree of seperation. To make private variables talk you would use what's called getters and setters. But I think that's out of the scope of the lesson. Once you've got some more android under your belt I recommend taking a full fledged Java course or getting a good book or two. It will make you a better android developer. Keep up the awesome work. You're asking the right kinds of questions to becoming a good programmer.