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);
}
在这段代码中我想计算一个活动被打开的次数,在这种情况下,activity1将只打开5次,之后activity3将打开我尝试杀死activity1然后杀死我将计数值发送到activity2然后我再次调用activity1并再次将计数值发送到activity1,所以代码将从开始本身执行,所以再次值为1但我希望activity1在oncreate()或in中捕获count的新值onstart()
并且错误是应用程序未打开其强制关闭并且在logcat中显示Null-exception错误但是我执行了所有绑定。
答案 0 :(得分:1)
在onStart()方法
上尝试此代码public void onStart()
{
Bundle b33 = getIntent().getExtras();
if(b33 != null)
{
count=b33.getInt("count");
tv2.setText(count);
}
}
变化:
整数计数;
到
int count=0;
也改变了:
tv2.setText(计数);
to(在onCreate和onStart上):
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));
}
}
我尝试了这段代码及其工作原理。