我目前正在开发一款Android应用,并使用序列化文件。我有一个方法将Java对象序列化为一个带有Context参数的文件。我在另一个类中工作时可以检索一个有效的Context对象,但是当我在这个扩展AppCompatActivity的类时,我不太清楚该怎么做。我尝试使用getApplicationContext()但仍然为Context提供了一个空值。
这是我到目前为止的基础:
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);
}
});
}
}
如何获取可以传递给序列化的上下文的非null值?
答案 0 :(得分:3)
您先调用该方法,然后初始化context
。改变它:
context = BookView.this;
setUpScreen(book);