Using Context with Appcompatactivity

Using Context with Appcompatactivity

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?

1

1 Answer

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

context = BookView.this;
setUpScreen(book);
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling
Author

James H. Sterling

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.