2017-11-10 96 views
0

我有一个变量storyID,我已经在onCreate中成功设置了变量。但是,当我尝试访问时,它将返回0将变量从onCreate()传递给onPause()

我认为这是一个范围界定问题,但无法看到我要出错的地方?

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); 
    } 
} 

回答

1

int storyIDonCreate方法

+0

谢谢删除int。这解决了它。你介意解释为什么这是问题吗? – Sebastian

+0

您正在'OnCreate()'内创建一个局部变量,这意味着您正在为本地变量赋值新值,而全局变量不会更新。在'OnPause()'内,你正在使用全局变量,它仍然没有变化。 –