I'm fairly new to Android development so I ran into a problem with the onResume() method.
My code crashes when I try to write Name.setText() from within the onResume() method. Writing the TextView from within the onPause() method works surprisingly without any problem.
How can I access this TextView from within the onResume() method?
public class Main extends Activity {
private ViewPager awesomePager;
private static int NUM_AWESOME_VIEWS = 2;
private Context cxt;
private AwesomePagerAdapter awesomeAdapter;
View v;
TextView Name;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
cxt = this;
awesomeAdapter = new AwesomePagerAdapter();
awesomePager = (ViewPager) findViewById(R.id.awesomepager);
awesomePager.setAdapter(awesomeAdapter);
}
@Override
protected void onResume() {
super.onResume();
Name.setText("1");
}
@Override
protected void onPause() {
super.onPause();
}
private class AwesomePagerAdapter extends PagerAdapter{
@Override
public int getCount() {
return NUM_AWESOME_VIEWS;
}
@Override
public Object instantiateItem(View collection, int position) {
View v = new View(cxt.getApplicationContext());
final LayoutInflater inflater = (LayoutInflater) cxt
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
switch (position) {
case 0:
v = inflater.inflate(R.layout.subpage1, null, false);
Name = (TextView) v.findViewById(R.id.name);
break;
case 1:
v = inflater.inflate(R.layout.subpage2, null, false);
break;
default:
break;
}
((ViewPager) collection).addView(v, 0);
return v;
}
@Override
public void destroyItem(View collection, int position, Object view) {
((ViewPager) collection).removeView(v);
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public void finishUpdate(View arg0) {}
@Override
public void restoreState(Parcelable arg0, ClassLoader arg1) {}
@Override
public Parcelable saveState() {
return null;
}
@Override
public void startUpdate(View arg0) {}
}
}
Name
must be set to null...Your app must have paused before it ever got initialized. Just check to make sure it's initialized before trying to do anything with it. You're onResume()
should look like this then:
@Override
protected void onResume() {
super.onResume();
if(Name != null){
Name.setText("1");
}
}
P.S. Standard java convention is to have all variable names begin with a lower case letter. You should probably rename Name
to name
.