将变量从onCreate()传递给onPause()

时间:2017-11-10 20:57:51

标签: android scoping

我有一个变量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);
    }
}

1 个答案:

答案 0 :(得分:1)

int方法

中的int storyID移除onCreate