I am very new to Android development and Java. Have read around but I’m not getting anywhere on this issue.
I have a button which when clicked should set a variable A’s Value to “Item Purchased”.
However, I am only get the value used when the variable is first defined in the class.
For those learning like me on this – this topic will hopefully make an excellent reference to those just starting.
Code is:
public class shopView extends Activity
{
String temp = "temp";
@Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.shopview);
Button btnRef1 = (Button) findViewById(R.id.btnbtnRef11);
final TextView ConfirmPurchasetest = (TextView) findViewById(R.id.tvMigName);
btnRef1.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
temp = "passed value";
ConfirmPurchasetest.setText("item Purchased");
buyFromShop();
Log.v("after button push", "temp");
};
});
}
public String buyFromShop(){
Log.v("button push", "after buy from shop");
Log.v("temp variable",temp);
return temp;
}
}
and is called using the following:
shopcheckout = shop.buyFromShop();
Log.v("Value in myView",shopcheckout);
Expected: shopcheckout = “item purchased”
Actual: shopcheckout = “temp”
Thanks again for any answers. Will actively monitor this post.
Unless you click on your Button
btnRef1, buyFromShop() will always return “temp”.If you add this code in your onCreate():
Now buyFromShop() will return “Changing the string.”.
If you want buyFromShop() to return the value of
ConfirmPurchasedtest, change your code to this:Also according to naming convention, class names like
shopViewshould have the first letter of each word capitalized; soShopView. Variables likeConfirmPurchasetestshould start with lower case and then capitalize each word (after the first), soconfirmPurchaseTest.Hope that helps!