Pass integer between classes in Java [duplicate] - java

This question already has answers here:
Transferring int variable between activities Android
(2 answers)
Closed 9 years ago.
So I have this class where I push a button, and at the and I get the int maxpluseen which I want to pass over to ClassB.
private void populateBtn() {
foto1 = (Button) this.findViewById(R.id.button2);
foto1.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SimpleDateFormat")
#Override
public void onClick(View v) {
int maxpluseen = maxIndex + 1;
Log.d("LOG!", "Uiteindelijk resultaat " + maxpluseen);
Intent myIntent = new Intent(classA.this, classB.class);
classA.this.startActivity(myIntent);
}
});
}
I tried doing the following:
public static int Access(int maxpluseen){
return maxpluseen;
}
And In classB
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.info);
int maxpluseen = 0;
int test = classA.Access(maxpluseen);
Log.d("LOG!", "Test int tussen klassen= " + test);
}
But it gives back 0 (so my int isn't passed from classA to classB. What am I doing wrong here?

in class A:
Intent myIntent = new Intent(classA.this, classB.class);
myIntent.putExtra("number", maxpluseen)
classA.this.startActivity(myIntent);
in Class B:
int getal;
getal = getIntent().getExtras().getInt("number");
......

here you are passing ClassA.Access() a value of 0, thus returning a value of 0.
int maxpluseen = 0;
int test = classA.Access(maxpluseen);

First of all, you should mention that your Classes aren't normal classes, but Activities.
Secondly, you should really use all-English variable names (maxplusone).
You can add data to the Intent, you use to start the new Activity with, which you can read more about
Here in a different question or here in the Intent developer description

Is classA your main?
If so, create an object to classB. Write a function to set the int value, so that you can do something like classBObject.setInt(value). Then, in your foto1's onClick() method, call that function.

Related

Unable to sync up answers the questions on an Android Multiplication app

I have a problem with my simple android app. When I launch it, the questions seems to be a step ahead of the answers I enter as input. For example If the question was to be 3x3 = ?, It will only accept the correct answer for the next question. So any answer I give in the current question will always be wrong. I tested this by continuously entering the same same answer.
Any pointers would be much appreciated. I hope this make sense!
public class MainActivity extends AppCompatActivity {
int value3;
int answer;
EditText answer_field;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageView leftNumber = findViewById(R.id.left_number);
final ImageView rightNumber = findViewById(R.id.right_number);
Button myButton = findViewById(R.id.answer_button);
final int[] numberArray = new int[]{
R.drawable.number_0,
R.drawable.number1,
R.drawable.number2,
R.drawable.number3,
R.drawable.number4,
R.drawable.number5,
R.drawable.number6,
R.drawable.number7,
R.drawable.number8,
R.drawable.number9,
};
leftNumber.setImageResource(numberArray[0]);
rightNumber.setImageResource(numberArray[0]);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Create a random number generator
Random randomNumberGenerator = new Random();
int value1 = randomNumberGenerator.nextInt(10);
leftNumber.setImageResource(numberArray[value1]);
// Create a new random number
int value2 = randomNumberGenerator.nextInt(10);
// Set the right dice image using an image from the diceArray.
rightNumber.setImageResource(numberArray[value2]);
answer_field = findViewById(R.id.answer_field);
answer = valueOf(answer_field.getText().toString());
value3 = value1 * value2;
if(value3 == answer) {
showToast("Correct");
}
}
});
}
public void showToast(String text){
Toast.makeText(MainActivity.this, text, Toast.LENGTH_LONG).show();
}
}
Thank you!
You are generating the values at the onClick of your answer button wich means that the values to multiply will be set (or reset) randomly every time the user hit the answer button; put the logic to generate the values outside the onclick, so when the user clicks on it only the comparison will be made, somewhat like this:
[...]
leftNumber.setImageResource(numberArray[0]);
rightNumber.setImageResource(numberArray[0]);
// Create a random number generator
Random randomNumberGenerator = new Random();
int value1 = randomNumberGenerator.nextInt(10);
leftNumber.setImageResource(numberArray[value1]);
// Create a new random number
int value2 = randomNumberGenerator.nextInt(10);
// Set the right dice image using an image from the diceArray.
rightNumber.setImageResource(numberArray[value2]);
answer_field = findViewById(R.id.answer_field);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
answer = valueOf(answer_field.getText().toString());
value3 = value1 * value2;
if(value3 == answer) {
showToast("Correct");
}
}
});
[...]

Retrieve a random object from an ArrayList: incompatible types

I'm trying to get a random Base from an ArrayList:
Edit: full code:
public class MainActivity extends AppCompatActivity {
private Random randomGenerator;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ArrayList<Base> baseArrayList = new ArrayList<Base>();
Base baseOne = new Base("Grüner Salat");
Base baseTwo = new Base("Gemischter Salat");
Base baseThree = new Base("Rüeblisalat");
Base baseFour = new Base("Eisbergsalat");
baseArrayList.add(baseOne);
baseArrayList.add(baseTwo);
baseArrayList.add(baseThree);
baseArrayList.add(baseFour);
Button mixSaladBtn = (Button) findViewById(R.id.mixSaladBtn);
mixSaladBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView baseTextView = (TextView) findViewById(R.id.baseTextView);
String baseDisplay = getRandomBase(baseArrayList);
baseTextView.setText(baseDisplay);
}
});
ArrayList<Ingredient> ingredientArrayList = new ArrayList<Ingredient>();
}
public String getRandomBase(ArrayList<Base> baseArrayList){
int index = randomGenerator.nextInt(baseArrayList.size());
Base randomBase = baseArrayList.get(index);
System.out.println(randomBase);
return randomBase.getIngredientName();
}
}
The App crashes when I call the method getRandomBase in the onClick method. Somehow I'm not getting back a Base from baseArrayList.get(index);
Final edit: I had 2 errors. The first one was that at first I used a raw type. Many thanks for the clarifications!
The second error was that I had to move the declaration of the Random randomGenerator();
You problem is in the method you are sending raw arraylist . so it doesn't know what data type it is . There are two ways you can fix
1. Casting
Base randomBase = (Base) baseArrayList.get(index);
Sending Type in method
public String getRandomBase(List<Base> baseArrayList){
}
Try
public String getRandomBase(ArrayList<Base> baseArrayList){...

How to access a variable declared in the main activity in another activity

i don't know if this is possible or if they is a better programming practice but i'd like to know how to use a varible declared in the main activity in another activity. Source code snippet example is given like so...
public class MainActivity extends ActionBarActivity {
private int a, b;
private EditText first, second;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
first = (EditText) findViewById(R.id.first_entry);
second = (EditText) findViewById(R.id.second_entry); }
public void doMath(View view) throws Exception {
try {
if (!first.getText().toString().equals("")) {
a = Integer.parseInt(first.getText().toString());
}
else {
a = 0;
}
if (!second.getText().toString().equals("")) {
b = Integer.parseInt(gpa_credits1.getText().toString());
}
else {
b = 0;
}
int sum = a + b; }catch (Exception e) {}
now, i would like to create a new activity to use the variable "sum" to do some math like...
public class first_year_second_semester extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newActivity);
int blah = 5;
private TextView soln;
soln = (TextView) findViewById(R.id.the_soln);
soln = (blah / sum) //i.e sum from the previous activity...please i need this
}
You can pass the value from one to other activity using intent or using shared preferences.
Intent intent=new Intent(MainActivity.this,year_second_semester.class);
intent.putExtras("sum",sum);
startActivity(intent);
Then in next activity you can get this value.
Or using shared preferences:
Inside class:
SharedPreferences shared;
Inside onCreate:
shared=getSharedPreferences("app",Context.MODE_PRIVATE);
After computing the sum I.e. after doing sum=a+b;
Editor edit=shared.edit();
edit.putString("sum",sum);
edit.commit();
And in the next activity:
Inside the class:
SharedPreferences shared;
Inside oncreate:
shared=getSharedPreferences("app",Context.MODE_PRIVATE);
Wherver you want:
String yourvalue=shared.getString("sum","default value");
Here your value will be the sum from the main activity.
Create a public static variable in your main activity (where the do math method is) like so:
public static int SUM;
Then in the do math function set that value to the one calculated.
int sum = a+b;
SUM = sum;
Then you can access it via:
MainActivity.SUM

Is it possible to pass a int and a string both from one activty to another , if yes then how to achive it?

I am trying to send a string and a int type data from one activity to another but due to lack of knowledge i don't know how to do it.
With the particular coding given below now i can only send any one of the data type.
searched a lot but not found any answer appropriate for my question. If i have asked any thing wrong plzz notify me as i am new to android Dev.
Any help may be appreciated.
this is my java coding of the two activities :
First.java
public class QM extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qm);
}
public void FLG(View view) {
// Do something in response to button
EditText mEditText= (EditText)findViewById(R.id.editText1);
String str = mEditText.getText().toString();
Intent intent = new Intent(this, Q1.class);
intent.putExtra("myExtra", str);
startActivity(intent);
finish();
}
}
Second.java
public class Q1 extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_q1);
Intent intent = getIntent();
if (intent.hasExtra("myExtra")){
TextView mText = (TextView)findViewById(R.id.textView1);
mText.setText("user name "+intent.getStringExtra("myExtra")+"!"); }
}
}
You can send 2 extras or even more as long you have different keys for it, so in your problem you need 2 extras one for String and one for Integer.
sample:
pass:
Intent intent = new Intent(this, Q1.class);
intent.putExtra("myExtra", str);
intent.putExtra("myExtraInt", yourInt);
get:
Intent intent = getIntent();
if (intent.hasExtra("myExtra") && intent.hasExtra("myExtraInt")){
TextView mText = (TextView)findViewById(R.id.textView1);
mText.setText("user name "+intent.getStringExtra("myExtra")+"!");
int extraInt = intent.getIntExtra(myExtraInt);
}
I'd like to give you some information.
Imagine the Intent's extras to be a (theoretically) infinitely sized bagpack. You can put certain type of data into it in an infinite number as long as each of the data has a unique name which is a string.
Internally it's a table that maps names to values.
So: Yes you can put String and Int simultaneously into the Intent's extras like this.
String str = "Test";
int val = 2933;
Intent i = new Intent(MyActivity.this, NewActivity.class);
i.putExtra("MyStringExtraUniqueName", str);
i.putExtra("MyIntExtraUniqueName", val);
To check for it use i.hasExtra("MyStringExtraUniqueName") as you did already and to get it use i.getExtra("MyStringExtraUniqueName").
BUT if you only use getExtra you'll be returned data of type object. Remember to cast the returned value to the appropriate type or use one of the specialized getter methods for some predefined data types.
See this for the available getters: http://developer.android.com/reference/android/content/Intent.html
Bundle data = new Bundle();
data.putInt("intKey", 5);
data.putString("stringKey", "stackoverflow");
Intent i = new Intent(MyActivity.this, NewActivity.class);
i.putExtras(data);
//And in the second acitvity fetch this way
Bundle data = getIntent().putExtras(b);

Accessing variables in different classes in Android

So say a user enters a total in an EditText field in my Incomings class, I then want this to be passed to my Results class. How do I go about this in Android? I know the best way is to use Accessor methods.
My Incomings class:
public void onClick(View v) {
String userLoan = etLoan.getText().toString();
String userGrant = etGrant.getText().toString();
String userFirst = etFirst.getText().toString();
float fUserLoan = Float.parseFloat(userLoan);
float fUserGrant = Float.parseFloat(userGrant);
float fUserFirst = Float.parseFloat(userFirst);
float totalIncomings = fUserLoan + fUserGrant + fUserFirst;
Intent intent = new Intent(v.getContext(), Outgoings.class);
startActivity(intent);
}
});
My results class has a blank function and will calculate the totals
I have tried using accessor methods in my MainAcivity class:
public float getTotalOutgoings() {
return totalOutgoings;
}
public void setTotalOutgoings(float totalOutgoings) {
this.totalOutgoings = totalOutgoings;
}
public float getTotalIncomings() {
return totalIncomings;
}
public void setTotalIncomings(float totalIncomings) {
this.totalIncomings = totalIncomings;
}
public float getTotalResult() {
return totalResult;
}
public void setTotalResult(float totalResult) {
this.totalResult = totalResult;
}
Any suggestions?
Pass Intent extras:
Intent intent = new Intent(v.getContext(), Outgoings.class);
intent.putExtra ("total",totalIncomings);
startActivity(intent);
Then access in your next Activity with
Intent i = getIntent();
float totalComings = i.getFloatExtra("total",-1.0);
Now about your Results class. It depends exactly what you want to do with that class. If all you need is a simple calculation, make a static method. And data passing is usually the other way around. The Activity calls a data class, gives it data, then the data class does whatever it needs to do and returns the result to the Activity.
use
Bundle bd = new Bundle();
bd.putFloat("key",value);
intent.putExtras(bd);
startActivityForResult(intent,1);
On other class
Bundle bund= getIntent().getExtras();
float value= bd.getFloat("key");
Are you trying to call a function on your MainActivity?
MainActivity m = (MainActivity) getActivity();
m.setTotalIncomings(XXX);

Categories

Resources