我的textView
中有一个MainActivity
。 textview
的值取决于用户的输入。当我导航到下一个Activity
然后返回我的MainActivity
时,textView为空。我已经看过不同的例子并尝试了所有这些例子,但似乎没有任何工作。我的代码出了什么问题?
这是我的MainActivity
。
public class MainActivity extends AppCompatActivity {
TextView cart_items_tv;
static Integer cartnum=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button2 = (Button) findViewById(R.id.b2);
final ListView lv = (ListView) findViewById(R.id.lv);
cart_items_tv = (TextView) findViewById(R.id.tv_items);
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Downloader(MainActivity.this,url1,lv).execute();
tv.setText("Category: Snacks and Drinks");
v.setSelected(true);
v.setPressed(true);
}
});
public void cart_items(Integer num){
cartnum = num +cartnum;
if(cartnum == 0 || cartnum == 1 ) {
cart_items_tv.setText("(" +String.valueOf(cartnum) + "item)");
} else
cart_items_tv.setText("(" +String.valueOf(cartnum) + " items)");
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("save",cartnum.toString());
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
cart_items_tv.setText(savedInstanceState.getString("save"));
}
}
修改
按下后退按钮时,此功能正常。但是当使用第二个活动的按钮时,通过Intent,它不起作用。还有另一种方式吗?