Using Context with AppCompatActivity

Ed Wu picture Ed Wu · Apr 24, 2016 · Viewed 13.7k times · Source

I'm currently working on an Android app, and working with serializing files. I have a method that serializes a Java object into a file that takes a Context parameter. I can retrieve a valid Context object when working in another class, but when I'm on this class that extends AppCompatActivity, I'm not too sure what to do. I tried using getApplicationContext() but that still gives me a null value for the Context.

Here's the base of what I have so far:

public class BookView extends AppCompatActivity {

private static Context context;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_book);
    Book book = Browse.books.get(getIntent().getIntExtra("index", 0));
    Browse.book = book;
    setUpScreen(book);
    context = getApplicationContext();
}

private void setUpChapters(Book book){

    ListView chapters = (ListView) findViewById(R.id.chapters);
    ChapterAdapter adapter = new ChapterAdapter(this, R.layout.row, book.getChapters());
    chapters.setAdapter(adapter);

    if (context != null) {
        book.serialize(context);
    }
    else {
        System.out.println("Null bookview context");
    }

    chapters.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent myIntent = new Intent(getApplicationContext(), Reader.class);
            myIntent.putExtra("index", position);
            startActivity(myIntent);
        }
    });
}
}

How do I get a non-null value for context that I can pass into serialize?

Answer

Rohit Arya picture Rohit Arya · Apr 24, 2016

You are calling the method first and then you are initializing the context. Change it like this:

context = BookView.this;
setUpScreen(book);