How can i use a variable from an Activity to another Activty? - java

In my MainActivity i have a score variable,
int score = 0;
however i have another activity which is the DisplayScore activity (which displays the score) txtFinalScore.setText("Score: " + score);
how can i use that same variable form my MainActivity to my DisplayScore activity so that i can display the score?

If I've understood well, here's how you should do it.
public class Main {
public static void main(String[] args) {
int score = 0; // the main activity thing
int displayScore = score; // the thing to use the same value as score
System.out.println("Score : " + displayScore); // to simulate the setText
}
}

This question explains perfectly how to use putExtra() and getExtra() methods for the Intent in Android, because I think that's what you need.
Also, if you find this difficult, you can store the score value into a sharedPreference and retrieve it from another activity. You can see the docs here.

Related

Syncing the data in arrays between activities [duplicate]

This question already has answers here:
What's the best way to share data between activities?
(14 answers)
Closed 5 years ago.
I am making a food order app. There is a full page ListView on my main page called MenuActivity and there is a Button when I press it, it will intent to the CartActivity page.
I have arrays food for food name, imgID for food images, butPlus butMinus to adjust the amount of food and amount to keep the amount of each food with an initial value of 0.
I have a method called addAmount , minusAmount in MenuAcitivity that will increase, decrease the amount. It is called by an Adapter of this class.
public static void addAmount(int position) {
amount[position] += 1;
}
Going to CartActivity, I used this to pass all my values.
public void goToCart(MenuItem menuItem) {
Intent in = new Intent(MenuActivity.this, CartActivity.class);
in.putExtra("list", amount);
in.putExtra("imgID", imgID);
in.putExtra("nameList", food);
startActivity(in);
}
to receive the values I created new ArrayList in CartActivity to get the data of the food that the amount in not zero.
// add components to array lists
// addList, removeList are methods to add,remove in my new ArrayList created in this class
for (int i = 0; i < amountList.length; i++) {
if (amountList[i] != 0) {
if (!foodListFinal.contains(foodList[i]))
addList(amountList[i], foodList[i], imgID[i]);
} else if (amountList[i] == 0 && !foodListFinal.isEmpty()) {
if (foodListFinal.contains(foodList[i])) {
index = foodListFinal.indexOf(foodList[i]);
removeList(amountList[index], foodList[index], imgID[index]);
}
}
}
Also, I have a method called addAmount , minusAmount in CartAcitivity that will increase, decrease the amount just like in the MenuActivity. It is called by an Adapter of this class which is not the same one with MenuActivity.
public static void addAmount(int position) {
int newAmount = (amountListFinal.get(position)) + 1;
amountListFinal.set(position, newAmount);
}
public static void minusAmount(int position) {
int newAmount = (amountListFinal.get(position)) - 1;
amountListFinal.set(position, newAmount);
}
Here is my problem..
When I decrease amount in the CartActivity to 0 and I went back to MenuActivity it correctly says 0, but if I switch to CartActivity again the app crashes with an error saying index out of bound.
Please help me with this, or is there any better way to do this please enlighten me. Thank you
for which array caused this error : " saying index out of bound." , foodList or amountList array ? It's gonna help you
I would suggest to use secondary storage to store your changes. Also passing whole array to another activity is not recommended.Use any database to insert change in it and then in cart activity retrieve all data.
This way ,you can achieve same state of amount in various objects.

How can I use variables through different classes?

in the class GameScreen I wrote this code for a score:
if (Gdx.input.justTouched()&& executed==true) {
MyGdxGame.camera.unproject(touchPoint.set(Gdx.input.getX(), Gdx.input.getY(), 0));
for (int i=0;i<4;i++) {
if (sprite[zahl[i]].getBoundingRectangle().contains(touchPoint.x, touchPoint.y) && zahl[4] == zahl[i]) {
int scoreValue = Integer.parseInt(score);
scoreValue++;
score = String.valueOf(scoreValue);
executed= false;
}
if (sprite[zahl[i]].getBoundingRectangle().contains(touchPoint.x, touchPoint.y) && zahl[4] != zahl[i]){
this.dispose();
game.setScreen(new GameOverScreen(game));
return;
}
}
}
The second if refers to the class GameOverScreen. So if a user loses the game, the GameOverScreen would be shown. Now I want to show the reached score on the GameOverScreen. Therefore I have to use the changing variable score from the GameScreen class in the GameOverScreen class.
My question is: How can I use variables through different classes?
You could create a constructor that takes the score as the parameter in your GameOverScreen.
e.g:
game.setScreen(new GameOverScreen(game, TheScore));
You can save the variable on Android sharedpreferences. See the example here

finding the number of a variable in Object arrays in different classes (java)

Presume we have a class Student and a class Activity.
class Student {
private Activity[] myActivites;
public Activity[] getAct() {
return this.myActivites
}
}
class Activity {
private String name;
public String getName(){
return this.name;
}
private Student[] members;
}
the members array represents all the students that go to this particular activity, while the myActivites array in Student represents all the different activites the particular student is visiting.
How would I go about writing an INT method in the activity class that returns the number of differently named activites that all of the students in this particular activity are visiting (so, two different Activity objects can have the same name!)
EDIT:
Thanks for your concerns guys. It's actually not homework, I'm preparing for a test next week.
Hope you will forgive me for not translating the code into english, as it takes quite some time.
It's a part of a larger program I have to write. So far, I've done something like this:
public int steviloRazlicnihDejavnosti() {
int najboljPriden = this.clani[0].getSteviloKrozkov();
for (int i=1; i<this.clani.length; i++) {
int trenutnaPridnost = this.clani[i].getSteviloKrozkov();
if (trenutnaPridnost > najboljPriden) {
najboljPriden = trenutnaPridnost;
}
}
String[][] krozkiClanov = new String[this.clani.length][najboljPriden];
for (int i=0; i<this.clani.length; i++) {
Ucenec trenutni = this.clani[i];
Krozek[] krozkiTrenutnega = trenutni.getKrozki();
for (int j=0; j<krozkiTrenutnega.length; j++) {
krozkiClanov[i][j] = krozkiTrenutnega[j].getDejavnost();
}
}
int stevec = 0;
return;
"Krozek" is the class Activity.
"Ucenec" is the class Student.
at first, I figure out, which student has the most activites and then set a 2d string array of this length (and the length of all students), which I fill with the names of the activites. Then, I was thinking of checking the 2D array (haven't written that up yet), but believe that this will take too much time - I basically just prolonged the same problem I was facing before.
Hope this shows that I've actually put some work into this.
I've also tried solving it with adding an extra boolean attribute "HasBeenChecked", and would not count any object that "HasBeenChecked", but figured that this did not help with recodnising the duplicates of the names.

How do I use the values of variables that are calculated inside a method, in a class?

I'm very new to programming, and don't understand much. I've been trying to build a simple game where a user and computer compete by rolling dice to earn points. My method is posted below. The computer is only allowed to earn 20 points per turn.
My issue is that I need the value of variable computerTotal to be remembered after the method has been called and completed. I want to ensure that whenever the computerTurn method is finished, I can use that calculated variable computerTotal outside of that method.
I tried establishing a new int in the .java file class (but outside of the method), and then using that int within the method to hold the value, however I receive errors about the integer needing to be static?
This is all very confusing to me. Can anyone help me out?
public static void computerTurn()
{
System.out.println("Passed to Computer.");
Die computerDie1, computerDie2;
int computerRound, computerTotal;
computerRound = 0;
computerTotal = 0;
while (computerTotal < 21){
computerDie1 = new Die();
computerDie2 = new Die();
computerDie1.roll();
computerDie2.roll();
System.out.println("\n" + "CPU Die One: " + computerDie1 + ", CPU Die Two: " + computerDie2 + "\n");
computerRound = computerDie1.getFaceValue() + computerDie2.getFaceValue();
int cpuDie1Value;
int cpuDie2Value;
cpuDie1Value = computerDie1.getFaceValue();
cpuDie2Value = computerDie2.getFaceValue();
System.out.println ("Points rolled this round for the Computer: " + computerRound);
computerTotal = computerTotal + computerRound;
System.out.println ("Total points for the Computer: " + computerTotal + "\n");
}
Any variables created inside a method are "local variables" meaning they cannot be used outside the method. Put a static variable outside of a method to create "global variables" which can be used anywhere.
Add a method to your class
public static int getComputerTotal() { return ComputerTotal;}
Then you can get the value outside of the class by doing something like:
ComputerTurn();
ComputerTurn.getComputerTotal();
Putting the variable outside of the method is on the right track, but since this method is static (meaning it cannot access variables that depend on object instances), it can only access static variables. Declare computerTotal in the class, outside of methods, using the following:
private static int computerTotal;
You should probably do some research on object-oriented programming and what static means in Java.
Declare computerTotal as a member variable of your class, so that its value is available even outside the function.
class MyClass{
private int computerTotal ;
public void function myFunction()
{
........
......... // your calculations
computerTotal = computerTotal + computerRound;
}
public int getComputerTotal(){return computerTotal ;}
}
You have to declare the computertotal outside any methods to keep them. so like this:
public class name {
int computertotal = 0; //v=can just uuse int computertotal;
public void method() {
while(computertotal < 20) {
computertotal += 1;
}
}
}
And now he variable gets saved!
You may need to add some setters and getters to get that int from another class.
class NewClass {
private int yourInt = 1;
}
It is telling you to make it a static variable because you may be calling it in a statement like
NewClass.yourInt;
, a static variable is one that’s associated with a class, not objects of that class.
Setters and getters are methods which allows you to retrieve or set the value which is private from another class. You might want to add them in the NewClass, where your int is declared. Setters and getters looks like this.
Setter:
public void setYourInt(int newInt) {
this.yourInt = newInt;
}
Getter:
public int getYourInt() {
return this.yourInt;
}

Assigning song's into database slot, simple music database

I'm trying to write a method which will look at a datbase(of 4 'slots') find the next empty one and store a song object(artis, name, duration, filesize). Whenever I input data in the program my current method seems to assign the incoming song object to all database 'slots' any help would be great thanks
All 4 java class's are here if anyone could have a look -----> http://www.fast-files.com/getfile.aspx?file=62228
public void addSong()
{
Song S = new Song();
do{
if (a.fileSize==0) {
setData(a.artist, a.name, a.duration, a.fileSize);
break;
} else if (b.fileSize==0) {
setData(b.artist, b.name, b.duration, b.fileSize);
break;
} else if (c.fileSize==0) {
setData(c.artist, c.name, c.duration, c.fileSize);
break;
} else if (d.fileSize==0) {
setData(c.artist, c.name, c.duration, c.fileSize);
break;
}
}while(true);
}
public void setData( String artist, String name, double duration, int fileSize)
{
S.setArtist(artist);
S.setName(name);
S.setDuration(duration);
S.setFileSize(fileSize);
}
EDIT - 4 database java class's http://www.fast-files.com/getfile.aspx?file=62228
First of all, get rid of the loop.
Second, I think your issue is with hiding S variable. In setData you set S properties (here its a global field) when in addSong you declare and instantiate a new S variable, which you never use.
You can do the following:
Make sure you use the correct variable.
Pass S to setData so it will set the fields of a parameter instead of global field.

Categories