public class MainActivity extends ActionBarActivity {
Button b1;
TextView tv2;
Integer count ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
count++;
b1= (Button)findViewById(R.id.b1);
tv2=(TextView)findViewById(R.id.tv2);
tv2.setText(count);
if(count == 5) {
Intent ii = new Intent(this,Activity2.class );
Bundle bb = new Bundle();
bb.putInt("Count",count);
ii.putExtras(bb);
startActivity(ii);
finish();
}
else
{
Intent iii = new Intent(this,activity3.class);
// Bundle bb1 = new Bundle();
startActivity(iii);
}
}
public void onStart()
{
Bundle b33 = getIntent().getExtras();
count=b33.getInt("count");
tv2.setText(count);
}
在这段代码中,我想计算一个活动被打开的次数。在这种情况下,activity 1将只打开5次,之后activity 3将打开我正在尝试的是在杀死activity 1之前杀死它,我将计数值发送到activity 2,之后我将再次调用activity 1,并再次发送计数值到activity 1。因此,代码将从一开始执行本身,所以值将再次为1,但我希望activity 1在oncreate((或onstart((中捕获count的新值
错误是应用程序没有打开其强制关闭,并且在logcat中显示Null异常错误,尽管我完成了所有绑定。
在onStart((方法中尝试此代码
public void onStart()
{
Bundle b33 = getIntent().getExtras();
if(b33 != null)
{
count=b33.getInt("count");
tv2.setText(count);
}
}
更改:
整数计数;
至
int count=0;
还有变化:
tv2.setText(计数(;
到(位于Create和Start上(:
tv2.setText(String.valueOf(count));
更新代码:
public class MainActivity extends ActionBarActivity {
Button b1;
TextView tv2;
int count = 0 ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
count++;
b1= (Button)findViewById(R.id.b1);
tv2=(TextView)findViewById(R.id.tv2);
tv2.setText(String.ValueOf(count));
if(count == 5) {
Intent ii = new Intent(this,Activity2.class );
Bundle bb = new Bundle();
bb.putInt("Count",count);
ii.putExtras(bb);
startActivity(ii);
finish();
}
else
{
Intent iii = new Intent(this,activity3.class);
// Bundle bb1 = new Bundle();
startActivity(iii);
}
}
public void onStart()
{
super.onStart();
Bundle b33 = getIntent().getExtras();
if(b33 != null)
{
count=b33.getInt("count");
tv2.setText(String.valueOf(count));
}
}
我试过这个代码,它能正常工作。