I'm new to android development but I give my best.
I want to create an app for scoring a card game for 2 teams playing:
Activity1: Make your bid
Activity2: Evaluate the outcome of the game
Activity3: Show a list with the score of the teams (2 columns)
Start over with Activity1 until someone has won.
So I have activity1 passing data to activity2 (using putExtra with an intent)
Activity2 evaluated the bid and calculates the score of Team1 and Team2.
That data is being passed to activity3.
Here I would like to Show a list with the scores of every round.
But where / how do I save that list data when I move on to activity1 again?
I'm already playing around with a new class which should be extending the application but I do not know how to instantiate that class and how to make it accessible form each activity?
Here is my manifest.xml => extradata as a new class:
<application
android:allowBackup="true"
android:icon="#drawable/notrump"
android:label="#string/app_name"
android:theme="#style/AppTheme"
android:name="extradata">
<activity
This class is set up like this:
public class extradata extends Application{
public static ArrayList<scoredata> scoring = new ArrayList<scoredata>();
#Override
public void onCreate()
{
super.onCreate();
}
And the scoredata class looks like that:
public class scoredata {
private int mScoreteam1;
private int mScoreteam2;
private String mBidteam1;
private String mBidteam2;
public scoredata(int pScoreteam1, int pScoreteam2, String pBidteam1, String pBidteam2){
mScoreteam1 = pScoreteam1;
mScoreteam2 = pScoreteam2;
mBidteam1 = pBidteam1;
mBidteam2 = pBidteam2;
}
public int getScoreteam1(){
return mScoreteam1;
}
public int getScoreteam2(){
return mScoreteam2;
}
public String getBidteam1(){
return mBidteam1;
}
public String getBidteam2(){
return mBidteam2;
}
public void setScoreteam1(int pScoreteam1){
mScoreteam1 = pScoreteam1;
}
public void setScoreteam2(int pScoreteam2){
mScoreteam2 = pScoreteam2;
}
public void setBidteam1(String pBidteam1){
mBidteam1 = pBidteam1;
}
public void setBidteam2(String pBidteam2){
mBidteam2 = pBidteam2;
}
So do I now have an arraylist of scoredata created when the application starts?
And if so how do I access the fields or add an item from my activities?
If you just want to pass the new added values from activity2 to activity1 you can use intents.
Call second activity using startactivityforesult(intent,requestcode). After getting the new values pass the result from activity 2 using setresult().
use this link
Update your arraylist(i.e. add new item) in onActivityResult() function inside activity1.
Use adapter.setnotifychanged to make the updates reflect in listview.
You may want to implement a class as a datastore, and make it a singleton so each of your 3 activities can access the data and modify it.
I don't know if it's the best solution for your problem but it's a simple one.
Related
So I'm having 4 Activities. Let's call them Activity1, Activity2, Activity3 and Activity 4.
Now what i want to do is:
I enter data as an array in Activity2 and want to use it in Activity4. Now the solution that i found says, that i can just use intent.putExtra, and then startActivity(intent).
But my problem is: I don't want to start Activity 4 after Activity2. For Example: i want to be able to enter the data in Activity2 then go to Activity3 or 1 and afterwards go to activity4 and be able to use the data from Activity2. So is there another way i can pass the data to activity4 without being forced to start it? Im talking about something like for example "sessionStorage.set("",)" in Javascript/JQuery.
I hope my question isn't too confusing and thank you in advance.
If you don't want to start the Activity4. then you have 2 options to get the data in Activity4 without start to it. Saved the data into shared preferences or into the database, where you enter the data in Activity.
For saving the array data into shared preference, check this link.
Save ArrayList to SharedPreferences
Another option might be this. You can create a singleton class. You can access this class from any activities.
public class Globals {
private static Globals instance;
private String [] strings = null;
private Globals() {
}
public static synchronized Globals getInstance() {
if (instance == null) {
instance = new Globals();
}
return instance;
}
public void clear(){
strings = null;
}
public String[] getStrings() {
return strings;
}
public void setStrings(String[] strings) {
this.strings = strings;
}
}
Activity:
String [] strings = new String[]{"item1","item2"};
Globals.getInstance().setStrings(strings);
Other Activity:
String [] strings = Globals.getInstance().getStrings();
All data is delete when the application closed.
You can store the data entered into SharedPreferences in Activity2 and retrieve it in Activity4.
Alternatively, you can send the data to Activity3 or Activity1 and then afterwards send the data to Activity4.
public void PrintRecordToResultTA() {
int i = 0;
Log.d("data","\nCodec: " + avlRecordCollection.getCodecID());
Log.d("data","\nRecord Count: " + avlRecordCollection.getRecordCount());
I have used log to see if my program woks, but now I need to display this data on UI thread in MainActivity, this method was used to display data in java program, I was thinking should I recreate this class as Activity to reach data from another Activity to Main?
EDIT:
I have created ArrayList of AVL Records
public List<AVLRecord> avlRecords = new ArrayList<>();
public AVLRecordCollection CreateCollection() { // private
return new AVLRecordCollection(codec, recordC, avlRecords);
}
And method to Create Records, which get all data I need to display... And I use avlRecord.add(AVLRecord) to pass all data.
public void CreateRecord() {
AVLRecord AVLRecord;
RecordHeader recordHeader = GetRecord_Data();
RecordGPS_Element recordGPS_element = GetRecord_GPS();
RecordIO_Element recordIOElement = GetRecord_IO();
AVLRecord = new AVLRecord(recordHeader, recordGPS_element, recordIOElement);
avlRecords.add(AVLRecord);
}
Can someone give me an example how can I display data in MainActivity
If you are calling this method from MainActivity then you can use return to send back data to Activity class or can call a method to display with your data arrayList in Activity class.
To use return change your method return type from void to arraList of your data type.
public ArrayList<DataType> PrintRecordToResultTA() {
ArrayList<DataType> avlRecordCollectionArray = new ArrayList<DataType>;
// add data into avlRecordCollectionArray arraylist
return avlRecordCollectionArray;
}
And in Activity class change method calling,
ArrayList<DataType> avlRecordCollectionArray = ClassName.PrintRecordToResultTA();
Then you will have arraylist of data in Activity class. Display data.
I made an application "Quiz", which has 4 activities. Main activity sends a String with your name from EditText to activity with first question. I have a problem here, because I don't know how to send this string immediately to final activity from main activity, but without going to final activity. I want to go to Activity with first question from main activity, then to activity with second question, and in the end I want to go to final activity.
Thanks for your help!
You could use static fields to pass data.
Inside your FinalActivity class you could add the following variable:
private static String NAME = "";
And with the following getters and setters:
public static String getName(){
return NAME;
}
public static void setName(String name){
NAME = name;
}
You can use the getter setter here at Application class so you can get the string data from anywhere were you want to. This is not the only way but i think it is also the easy way.
public class MyApplication extends Application {
private String someVariable;
public String getSomeVariable() {
return someVariable;
}
public void setSomeVariable(String someVariable) {
this.someVariable = someVariable;
}
}
add this in your manifest
<application
android:name=".MyApplication"
android:icon="#drawable/icon"
android:label="#string/app_name">
hen in your activities you can get and set the variable like so:
/ set
((MyApplication) this.getApplication()).setSomeVariable("foo");
// get
String s = ((MyApplication) this.getApplication()).getSomeVariable();
Some Url which may help you Android global variable
You can use shared preference also but as per our requirement i don't recommend that to you
Android Shared preferences example
You can use Broadcast Receiver for your requirement. In your activity from which you want to send data, do this way:
Intent intent = new Intent();
intent.setAction("fourthactivity");
sendBroadcast(intent);
And In your fourth activity, make a broadcast receiver which receive your intent :
public class IncomingReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("fourthactivity")) {
System.out.println("GOT THE INTENT");
}
}
}
Tell me if this doesn't work or click right if it works for you.
You can use SharedPreference to store the answers as you go from one activity to other and later compare all the answers in the FinalActivity in that way less complex coding and you will achieve your desired result.
public boolean getFavourite(Winkel winkel){
boolean isFavourite = false;
MyDBHandler dbHandler = new MyDBHandler(context,null,null,1);
User user = dbHandler.loggedIn(); //This method isn't usable anymore
isFavourite = dbHandler.isFavourite(user,winkel);
return isFavourite;
}
I want to change this code to:
public boolean getFavourite(Winkel winkel){
boolean isFavourite = false;
MyDBHandler dbHandler = new MyDBHandler(context,null,null,1);
isFavourite = dbHandler.isFavourite(user,winkel);
return isFavourite;
}
I was using my database to keep track of which user was logged in at first, but it was really easy to change this by simply sending the data from my first activity to my second.
#Override
public void login(User user){
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("Username",user.getUserName());
startActivity(intent);
}
Then, in my second activity, I could call all the database functions by using this:
user.setUserName(intent.getStringExtra("Username"));
(Because I need the username as a key for my database.
However, my activity has three fragments, two of which use my adaptor for a recyclerview. These fragments implement the interface that is provided in my adaptor class, which is this one (just showing this to be complete, what the interface is is irrelevant, fact is that my fragments have to implement this interface).
public interface ItemCLickCallback {
void onItemClick(int p);
void onSecItemClick(int p);
}
Now, I need the username in my adaptor class. It has to come from my activity (because thats where its stored), and I can't use an interface because I'm already using one and I would have to override the methods in every fragment.
I could pass the data from my activity to all the fragments using a Bundle, then pass that along to the adaptor when creating it in my fragments. But that seems like a lot of excessive code. Any simpler way to do this? Thank you
EDIT:
In Adaptor class:
private CheckFavourite checkFavourite;
public void setCheckFavourite(final CheckFavourite checkFavourite){
this.checkFavourite = checkFavourite;
}
boolean isFavourite = checkFavourite.getFavourite(winkel);
public interface CheckFavourite{
boolean getFavourite(Winkel winkel);
}
Fragment:
public class Overview extends Fragment implements Adaptor.ItemCLickCallback
Activity:
public class SecondActivity extends AppCompatActivity implements Adaptor.CheckFavourite
Activity has to implement the seconde interface, fragment implements the second. But both of them are on the same adaptor instance.
What I need to do (in my activity basically):
adaptor.setCheckFavourite(this);
But I can't because I don't have the adaptor there, it gets created in my fragment.
I tried:
adaptor.setCheckFavourite(this.getActivity());
in my fragment, but that gives me an an error:
Error:(60, 51) error: incompatible types: FragmentActivity cannot be converted to CheckFavourite.
However
adaptor.setItemCLickCallback(this);
is working perfectly fine in my fragment (the other interface). How do I fix this?
:) You can use multiple inheritance. To be able to make a class implement multiple interfaces we need can have something like this:
public class MyClass extends MyOtherClass implements MyInterface1, MyInterface2, ... , MyInterfaceN {
// Need to implement all interface methods here
}
Say I am making something like a quiz, and I have a counter to show the number of questions that have been answered correctly. When one question is correctly answered, and a new screen(Activity) is shown, how do I carry over the number to the next screen?
When you say screens do you mean Activities? Then you probably want to pass them via extras in your intents.
Activity 1:
int score;
...
Intent Intent = new Intent(...);
intent.putExtra("score_key", score);
startActivity(intent);
Activity 2's onCreate():
int score;
...
Bundle extras = getIntent().getExtras();
// Read the extras data if it's available.
if (extras != null)
{
score = extras.getInt("score_key");
}
You can send numbers, strings, etc in a bundle with your intent.
Bundle b = new Bundle();
b.putInt("testScore", numCorrect);
Intent i = new Intent(this, MyClass.class);
i.putExtras(b);
startActivity(intent)
you can also put StringArrays and a few other simple vars
One of this way you can share your data among whole project,
public class mainClass
{
private static int sharedVariable = 0;
public static int getSharedVariable()
{
return sharedVariable;
}
}
From the other class/activity , you can access it directly using classname and . (dot) operator. e.g. mainClass.getSharedVariable();
A good practice for storing variables across Activitiys is using a own implementation of the Application Class.
public class MyApp extends android.app.Application {
private String myVariable;
public String getMyVariable() {
return myVariable;
}
public void setMyVariable(String var) {
this.myVariable = var;
}
Add the new Class in the Manifest.xml inside the application tag:
<application android:name="MyApp" android:icon="#drawable/icon" android:label="#string/app_name">
Now you can manipulate the variable in every Activity as follows:
MyApp ctx = (MyApp)getApplicationContext();
String var = ctx.getMyVariable();