I'm trying to build a simple cookie clicker- you press a button a variable grows by 1. Now, I'm trying to build a shop, so you can buy upgrades-the variable grows more, auto clicks... So, I'm trying to pass my variables (number of cookies, cookies for click) using intent, but every time I try to get to the activity, my app crash. here is my MainActivity code:
public static int NumOfCookies=0;
public static int CookieForClick=1;
public final static String EXTRA_MESSAGE = "com.example.cookieclicker01";
public final static String EXTRA_INTENT = "com.example.cookieclicker01";
public void GetToShop(View v){
Intent intent = new Intent(this, ShopActivity.class);
Bundle extras = new Bundle();
intent.putExtra(EXTRA_MESSAGE, NumOfCookies);
intent.putExtra(EXTRA_INTENT, CookieForClick);
intent.putExtras(extras);
startActivity(intent);
}
here is my code for the second activity:
Intent intent = getIntent();
var1= intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
var2 = intent.getStringExtra(MainActivity.EXTRA_INTENT);
NumOfCookies= Integer.parseInt(var1);
CookiesForClick= Integer.parseInt(var2);
TextView t1= (TextView) findViewById(R.id.Cookies);
t1.setText(Integer.toString(NumOfCookies));
You are trying to get a String, but your var1 , and var2 are int values.
var1= intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
var2 = intent.getStringExtra(MainActivity.EXTRA_INTENT);
The correct is :
var1= intent.getInt(MainActivity.EXTRA_MESSAGE);
var2 = intent.getInt(MainActivity.EXTRA_INTENT);
Or your will change the type of var1, var2 to String:
public static String NumOfCookies=0;
public static String CookieForClick=1;
either this -
//Bundle extras = new Bundle();
intent.putExtra(EXTRA_MESSAGE, NumOfCookies);
intent.putExtra(EXTRA_INTENT, CookieForClick);
//intent.putExtras(extras);
Comment out those two lines. Basically you were putting a empty Bundle in your intent in the last line and thus replacing your previously stored values.
or that-
Bundle extras = new Bundle();
extras.putString(EXTRA_MESSAGE, NumOfCookies);
extras.putString(EXTRA_INTENT, CookieForClick);
intent.putExtras(extras);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.