Android 将变量从onCreate()传递到onPause()
我有一个变量Android 将变量从onCreate()传递到onPause(),android,scoping,Android,Scoping,我有一个变量storyID,我已经在onCreate中成功设置了该变量。但是当我试图在onPause中访问它时,它返回0 我认为这是一个范围问题,但看不出我错在哪里 public class StoryBodyActivity extends AppCompatActivity { private TextView storyBodyTextView; private ScrollView storyBodyScrollView; public int storyID;
storyID
,我已经在onCreate
中成功设置了该变量。但是当我试图在onPause
中访问它时,它返回0
我认为这是一个范围问题,但看不出我错在哪里
public class StoryBodyActivity extends AppCompatActivity {
private TextView storyBodyTextView;
private ScrollView storyBodyScrollView;
public int storyID;
Parcelable state;
int scrollY;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_story_body, menu);
return true;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_story_body);
Bundle extras = getIntent().getExtras();
String story = extras.getString("story");
int storyID = extras.getInt("story_id");
Log.i("stories", Integer.toString(storyID));
// show back arrow
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setTitle(story);
storyBodyTextView = (TextView) findViewById(R.id.story_body_text_view);
storyBodyScrollView = (ScrollView) findViewById(R.id.story_body_scroll_view);
DatabaseHelper db = new DatabaseHelper(this);
String storyBody = db.getStoryBody(storyID);
storyBodyTextView.setText(Html.fromHtml(storyBody));
if(state != null) {
Log.d("pause", "trying to restore textview state..");
storyBodyTextView.onRestoreInstanceState(state);
}
int scroll = storyBodyScrollView.getScrollY();
Log.i("scroll", Integer.toString(scroll));
}
@Override
public void onPause() {
// Log.d("pause", "saving listview state @ onPause");
// state = storyBodyTextView.onSaveInstanceState();
scrollY = storyBodyScrollView.getScrollY();
// Log.i("scroll", Integer.toString(scrollY));
Log.i("insert", Integer.toString(storyID));
DatabaseHelper db = new DatabaseHelper(this);
db.saveScrollPosition(scrollY, storyID);
super.onPause();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
从
onCreate
方法中的intstoryid
中删除int
,谢谢。这就解决了问题。请您解释一下问题的原因好吗?您正在“OnCreate()”内创建一个局部变量,这意味着您正在为局部变量赋值,而全局变量则没有更新。在“OnPause()”中,您使用的是全局变量,该变量仍然未被触及。