I'm making a quiz app, there is main activity and it contains fragments which are questions like (Radio Button, Checkbox, Drag and drop questions) . How to collect the Score from all the fragments.
Hold the score variable in the Main Activity
private int score=0;
write public functions to get and set the score in the activity
public void setScore(int score){
this.score=score;
}
public int getScore(){
return this.score
}
Now in the fragments you can get and set score using
score=((MainActivity)getContext()).getScore()
((MainActivity)getContext()).setScore(score)
There are multiple ways to do that.
You can add Set/Get method in Your activity and fetch that from
fragment when you need them.
Create static variable in Activity class and you can access with 'ActivityClassName'.
Use Shared Preference and get access of that data anywhere. You can reset when you need and update from any class.
You can use as your app requires.
Just keep the variable static in which your are storing your score .
for eg : public static int score=0
by writing static it will have reference in memory and will be available until the
activity is running .
Create a Java class and name it as DataHolder. Define score variable as a global variable. Create getter & setter method as static. When you get score, set the values using set method. when you want to get score, use get method. Its simple java. Best thing is you can get and set score from any activity or any fragment using this method. Try below code.
DataHolder.java
public class DataHolder {
private static String Score="";
public static void set_Score(String s){
DataHolder.Score = s;
}
public static String get_Score(){
return DataHolder.Score;
}
}
To set score in DataHolder class, use below code from any fragment or activity.
String Score = ""; //get Score to this variable
DataHolder.set_Score(Score);
try using public static final key word if your value is not going to be changed through out the app else use public static before the var type that will remain accessible in all files with out instantiation and value could be initialized at any instance .
Example:
public static int score;
public static final int score=5;
Second way is by using sharedprefrences , you can get help from here .
Related
I am new to android studio but I am getting better at it as I program more and more. I have a MainActivity.java and the .xml file. And a friend provided me some code that it suppose to work with the input areas. The problem is I do not know how to access that regular java file. So that I can use it the way it is intended. He was using eclipse to build everything while I use android studio. I have the buttons all good to go and areas of input good to go but I just dont know how to implement his code. Any guidance will be greatly appreciated.
See examples to understand what I am trying to do.
"In android studio" a class is created called WaterDetails.java with a .xml file called activity_water_details.xml. There are calculations that were made for the duration that I need to be able to use or access from a java file created in eclipse called DurationCalculations.java. I have tried importing. I have tried opening the folder in explorer and putting the class in the same project. But, nothing seems to work.
Code:
public class WaterDetails extends AppCompatActivity {
Button continueWaterDetailsPart2;
EditText duration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_water_details);
duration = (EditText)findViewById(R.id.enter_duration);
duration.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String user = duration.getText().toString();
if(duration.equals(" "))// if user inputs information
//Then get calculations from other java file.
}
});
Sample Code:
Second Java fie. The file I need to access.
package ScubanauiTables;
import java.util.Arrays;
public class DurationCalculations {
private int duration;
//Constructor
DurationCalculations(int duration, int maxDepth, int avgDepth, int temp, int visibility, int pressureStart,
int pressureEnd, String[] diveConditions, String[] diveActivities) {
setDuration(duration);
setMaxDepth(maxDepth);
setAvgDepth(avgDepth);
setTemp(temp);
setVisibility(visibility);
setPressureStart(pressureStart);
setPressureEnd(pressureEnd);
setAirType(21);
setDiveConditions(diveConditions);
setDiveActivities(diveActivities);
setPressureGroup();
public int getDuration() {
int temp = duration;
return temp;
}
private void setDuration(int duration) {
this.duration = duration;
}
I hope this sample code makes sense. Thank you all for your help in advance.
You want to use methods of your DurationCalculation class, and for that, you've to create an instance of that class.
You can instantiate and use your class like this
DurationCalculations durationCalculation = new DurationCalculations(
/*enter your constructor values*/);
Now you can call all public methods of your DurationCalculations class using durationCalculation variable like this
durationCalculation.getDuration();
You cannot call any private methods from outside of the class, like your setDuration() whose scope is set to private. For it be accessed outside of DurationCalculations class. You need to set it to public
Yes I'm really new to android and I'm wokring on a very simple app.
On my mainActivity I'm creating and array, and want to access the array from a different activity.
public class Activity extends {
MyAreas[] myArea;
#Override
protected void onCreate(Bundle savedInstanceState) {
myArea= new MyAreas[2];
myArea[0] = new MyAreas(33, 44, "Location ", "active");
myArea[1] = new MyAreas(32, 434, "Location 2", "active");
Class
public class MyAreas{
public double val;
public double val2;
public String name;
public String status;
public MyAreas(double val, double val2, String name, String status) {
this.val= val;
this.val2= val2;
this.name = name;
this.status = status;
}
I'm trying to access myarea array from my activity2.java, I tried this but didn't work.
private ArrayList<MyAreas> mMyAreasList;
Using Parcelable to pass data between Activity
Here is answer which should help.
In regular Java you can use getters to obtain objects or any variable from a different class. Here is a good article on encapsulation.
In Android, there is a class called Intent that lets you start one activity from another and pass any necessary information to it. Take a look at the developer docs and this other answer which should help you.
For your begginer level, rather than using intents, just set the array object public and static, like that:
public static MyAreas[] myArea;
By that way you can access it from any activity in your app..
Then, go to the activity2.java wherever you want to access it.
MyAreas area = Activity.myArea[0];
The problem with this approach is that you do not have complete control when and in what order the activities are created or destroyed. Activities are sometimes destroyed and automatically restarted in response to some events. So it may happen that the second activity is started before the first activity, and the data is not initialized. For this reason it is not a good idea to use static variables initialized by another activity.
The best approach is to pass the data via the intent. The intents are preserved across activity restarts, so the data will be preserved as well.
Another approach is to have a static field to keep the data, and initialize the data in an Application instance.
I'm using public static strings for keeping values into my apk.
Example in my Class:
public class Login
{
public static string UserName;
}
In my activity:
Login.UserName="SomeText"
For Some reason which i dont know, all public static strings has been reseted suddenly.(All values has returned on null)
Is there possibility for injection in my code? 'Or' android applications can create a problem like this??
All static variables will be reset and equal to null when you close the application. If you want persistent data then look into android preferences.
I know there are already some questions on global methods and variables in android but I'm running into problems with static methods probably due to my less experience with objectoriented programming. So here is what I want to have:
I am writing an app which counts points which the user can earn for certain things he does. Because of that I want to call the method addPoints from different activities and services. This method should also set the points textview in the main activity and some other things.
I realized it by adding a static variable
static int sPoints;
in the MainActivity, that I use as a "global" variable in each activity.
However, with the addPoints method I have some problems. If I use a non-static method, I have to create an instance of MainActivity in the other activities, which is not very nice and changing the values of that instance does not have an effect on the actual MainActivity.
If I use a static function it works fine as long as I don't want to use non-static methods like in this example:
public static void addPoints(Context context, int points){
int levelBefore, levelAfter;
levelBefore = getLevelFromPoints(sPoints);
sPoints = sPoints + points;
levelAfter = getLevelFromPoints(sPoints);
if(levelBefore!=levelAfter){
String rank = getRankFromLevel(levelAfter);
levelTextView.setText("Lvl. " + String.valueOf(levelAfter));
Toast.makeText(context, "Congrats! You reached the next level!", Toast.LENGTH_LONG).show();
}
}
Here I can't easily use levelTextView.setText and I run into this problem in many other cases. Moreover, I've read that using static methods is not good, anyway.
So would the correct way be creating an instance of MainActivity each time and then call addPoints on it which has to return the new number of points? Or is there another way (I hope so, because both above ways seem to be not very satisfying).
a. Static methods can safely be used in case your work can not be accomplished by ShardPreferences and requires the use of same code at multiple classes like in your case.
b. First create an interface that will pass the updated rank to respective activities or classes
public interface ScoreUpdater {
void updateScore (String rank);
}
c. then implement it in all activities where required to use, MainActivity in this case
public class MainActivity extends AppCompatActivity implements ScoreUpdater{
//
//other methods and codes
//
#Override
public void updateScore(String rank) {
runOnUiThread(new Runnable() {
#Override
public void run() {
levelTextView.setText("Lvl. " + String.valueOf(levelAfter));
Toast.makeText(MainActivity.this.getApplicationContext(), "Congrats! You reached the next level!", Toast.LENGTH_LONG).show();
}
});
}
}
d. then implement your static methods. not sure where you have declared few variables. so my method below is on guess work.
public static void addPoints(Context context, int points){
//not sure where you are declaring sPoints
int levelBefore, levelAfter;
levelBefore = getLevelFromPoints(sPoints);
sPoints = sPoints + points;
levelAfter = getLevelFromPoints(sPoints);
if(levelBefore!=levelAfter){
String rank = getRankFromLevel(levelAfter);
if(context instanceof ScoreUpdater){
((ScoreUpdater)context).updateScore(rank);
}
}
}
private static int getLevelFromPoints(int points){
//your operations
return points;
}
I am writing an Android app where I need to pass a string array between two classes. The string initializes fine and I can output the contents of the string fine in the one class but as I try to pass it to another class I get a Null Pointer Exception error. The following is the stripped down version of my code:
accelerometer.java:
public class accelerometer extends Service {
public String movement[];
public void onCreate() {
movement = new String[1000000];
}
public void updatearray() {
movement[arraypos]=getCurrentTimeString();
//Toast.makeText(this, movement[arraypos] , Toast.LENGTH_SHORT).show(); //this correctly displays each position in the array every time it updates so I know the array is working correctly in this file
arraypos+=1;
}
public String[] getmovement(){
return movement;
}
}
wakeupalarm.java:
public class wakeupalarm extends Activity {
private TextView herestext_;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.wakeup);
herestext_ = (TextView) findViewById(R.id.TextView01);
accelerometer accelerometercall = new accelerometer();
String movearray[] = accelerometercall.getmovement();
herestext_.setText(movearray[2]);
}
}
I have a feeling I'm missing something very simple but any help would be greatly appreciated!
Thanks,
Scott
You're creating a new accelerometer class, which is completely uninitialized since there is no constructor, then you access its member. Of course it'll be null.
Not sure how your two classes are related, but if the activity is called by the service, then you need to pass the string through the intent (through an extra, for example).
Side note: Class names should always start with a capital letter. Method/variable names should have camel case, i.e. "updateArray". Also, you can format your code here by selecting it and pressing CTRL+K.
Your first problem, I think, is that you are creating an array with a million slots in it. Do you really mean to be doing that? It's going to take a lot of memory---quite possibly more than is available. You should instead look to having a Vector of Strings that you extend as necessary.