Moving return varibles between Classes [duplicate] - java

This question already has answers here:
How do I pass data between Activities in Android application?
(53 answers)
Closed 7 years ago.
I have a method in a Fragment that takes a value from a quantity Spinner and returns it. Where can I retrieve the value of this variable? If I want to move it to a new Activity altogether, how can I retrieve it there?
public String SetupQuantitySpinner(String[] quantity) {
Spinner spnr2;
spnr2 = (Spinner)view.findViewById(R.id.spinner_quantity);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getActivity(),
R.layout.custom_spinner,
R.id.text_main_seen,
quantity);
spnr2.setAdapter(adapter);
return quantity[spnr2.getSelectedItemPosition()];
}
Basically the Spinner represents the quantity of the item that a user has decided to purchase, i.e. 1 to 20 shirts. I now have to multiply this value by its cost, but the cost is retrieved in another Activity altogether:
String cost = currentProduct.getCost();
I need to send quantity[spnr2.getSelectedItemPosition()] to this new Activity so that I can multiply it by currentProduct.getCost();
How can I accomplish this?
Edit: This is different and hence not a duplicate because I only want to send and retrieve data associated with the selected Spinner item.

If you want to retrieve only selected item in another activity then you can simply put this code inside onItemSelected method. And retrieve the value of extra in that activity.
String item = mSpinner.getSelectedItem().toString();
Intent intent = new Intent(this,NextActivity.class);
intent.putExtra("item",item);
startActivity(intent);

This is another way to do it. Write a global variable:
public final static String PRODUCT_SIZE_MESSAGE = "com.elgami.customizer.PRODUCT_SIZE";
Start your Intent where you want to in your code:
Intent intent;
intent.putExtra(MainActivity.PRODUCT_QUANTITY_MESSAGE, productQuantity);
startActivity(intent);
You put the variable you want to send along with your Intent in the Extra, and then retrieve it in the new Class as follows:
private int getIntentMessageProductQuantity() {
return getIntent().getIntExtra(MainActivity.PRODUCT_QUANTITY_MESSAGE, 0);
}
Now you have that variable and you can use it as a parameter in any method in the new Class, like so:
public void LaunchPurchaseIntent(MainActivity.ProductType productType, int productSize, int productQuantity, String uuid) throws ParseException {
// Do what you want here
}

Related

Adding translation support to spinner

I have a spinner of strings. I want to add support to multi langues so I move the strings into strings.xml file and now I have the following method in consts class:
public static String[] getCars(Activity activity) {
if (activity == null) {
return null;
}
return new String[] {
activity.getString(R.string.car1),
activity.getString(R.string.car2)
// more
};
}
Now I display the cars in the spinner as follows:
Spinner spinner = findViewById(spinnerId);
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<>(this,
android.R.layout.simple_spinner_item, spinnerValues);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerAdapter);
Other code to handle changes:
String car = shift.getCar(); // from DB
int carPosition = Arrays.asList(ShiftUtils.getCars(this)).indexOf(car);
Spinner carsSpinner = findViewById(R.id.add_car_spinner);
carsSpinner.setSelection(carPosition);
I keep the car names in English in the DB so getCar() will return the chosen car name in English. But then if my application is currently in other language, carPosition will be -1 because it will not find the string (because car is in English). I want to display the spinner values to be in the locale language but in the background (fetch and push) to be in English. What would be the best way to do it? I prefer not to touch the DB (keep it in English).
Instead of getting the car name from your DB, create a unique ID for each car, and make your spinner item list hold both the ids and the text values.
This way, you'll be able to get the id of the selected car from the DB, and set it as the selected car in your spinner, regardless of the display language

I have an arrayList outside of an onClick method that refers to the arrayList, but it is giving me errors

I have an arrayList outside of an onClick() method. I am referring to some elements in the arrayList in my onClick() class. But when I type the name of the ArrayList and the list, it highlights in red. Both of the classes are public though.
I have tried putting the code of the arryalist and the list randomization process, but the it re randomizes every time I click something.
The part that is giving me errors is in the first case in the switch case statement, where I try to get the first position in the allImages arraylist, and the first position in the imageList List. They are in the onclick class. The arrayList and List are outside of that class.
I cannot put the arrayList and List inside of the class, because that will re randomize every time I click something. (I am trying to make a matching game)
Here is the code:
public void Random() {
Integer[] allImages = { R.drawable.cheetah, R.drawable.cheetah, R.drawable.chick, R.drawable.chick, R.drawable.fox,
R.drawable.fox, R.drawable.giraffe, R.drawable.giraffe, R.drawable.owl,
R.drawable.owl, R.drawable.panda, R.drawable.panda, R.drawable.sheep, R.drawable.sheep, R.drawable.tiger,
R.drawable.tiger};
List<Integer> imageList = Arrays.asList(allImages);
Collections.shuffle(imageList);
imageList.toArray(allImages);
}
public void onClick(View v) {
final int id = v.getId();
if (maxCounter < 2) {
switch (id) {
case R.id.one:
one.setBackgroundResource(allImages[0]); THE ALL IMAGES PART HIGHLIGHTS IN RED
unmatchedImages[maxCounter] = R.id.one;
unmatchedImages[maxCounter++] = imageList.get(0); ALSO IMAGE LIST HIGHLIGHTS IN RED
break;
//After this, i have cases for each button
}
}
else {
one.setBackgroundResource(R.drawable.qmarks);
//After this, i have a setBackgroundResource for each button
}
}
Please help. Any help is greatly appreciated.
Is your Random() should be method or class?
Base on name, which starts from uppercase (Random) it look like class.
But you added public void before name, so it's method.
I think you can move your Random() method (!) content to your Activity. Are you planning to set in Fragment or Activity?
Steps to do:
1) Move your list as field in your Activity (or fragment - I don't know what you have)
2) Shuffle list in onCreate() (or in different place but before first usage)
// 0 - Use it in your class.
// This "MainActivity" is only for example - use your name!
public class MainActivity extends AppCompatActivity {
// 1 - List of items
List<Integer> allImages = {R.drawable.cheetah, R.drawable.cheetah, R.drawable.chick,
R.drawable.chick, R.drawable.fox, R.drawable.fox, R.drawable.giraffe,
R.drawable.giraffe, R.drawable.owl, R.drawable.owl, R.drawable.panda,
R.drawable.panda, R.drawable.sheep, R.drawable.sheep, R.drawable.tiger,
R.drawable.tiger};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 2 - Shuffle them
Collections.shuffle(imageList);
}
.
.
.
}
The problem I see is that yes Random is public but in the OnClick() method your are trying to access a property of Random without telling who is the parent.
So instead of just using allImages and imageList.get() use Random().allImages and Random().imageList.get() Hope this helps.

How to use Shared Preferences to save data selected on Spinner and from checked Radio Button

I am trying to save into shared preference object what the user selects from Spinner and also save which radio button was checked (positive or negative value). THEN display or retrieve data from shared preference object.
Here is how my onCreate method looks like:
public class ShoulderActivity extends Activity implements OnItemSelectedListener {
 
 
// The attribute used to store the value of the special test id <= used in sharedPreferences
 
int selectedPosition;
 
// The attribute used to store the value (positive or negative) that correspond to the special test id <= used in sharedPreferences
EditText STValue;
 
TextView STNameTextView, STValueTextView;
 
public static final String DEFAULT = "N/A";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.shoulder_layout);
 
Spinner shoulderSpinner = (Spinner) findViewById(R.id.shoulder_spinner);
 
//Create an ArrayAdapter using the string array and a default spinner
ArrayAdapter<CharSequence> shoulderAdapter = ArrayAdapter
 .createFromResource(this, R.array.shoulder_tests,
 android.R.layout.simple_spinner_item);
 
//Specify the layout to use when the list of choices appears
shoulderAdapter
 .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
 
//Apply the adapter to the spinner
shoulderSpinner.setAdapter(shoulderAdapter);
 
shoulderSpinner.setOnItemSelectedListener(this);
 
 
}//END onCreate
And below I wrote add() method to save into shared preference object:
public void add(View view)
{
 
//User SharedPreferences to save the value per special test
SharedPreferences sharedPref = getSharedPreferences("STData", Context.MODE_PRIVATE);
 
//to edit the data or add data inside my file "STData"
SharedPreferences.Editor editor = sharedPref.edit();
 
//Store the values in my file "STData"
// ******** pull up the name of the test from ONITEM selected on SPINNER **********
 
//editor.putString("specialTestName", STName.getText().toString() );
int selectedPosition = shoulderSpinner.getSelectedItemPosition()
editor.putInt("specialTestName", selectedPosition);
editor.commit();
 
//**************************************
// get this value from the Radio Button *****************
 
RadioButton posValuerb1 = (RadioButton) findViewById(R.id.positiveId);
 
// Save the test value; if positive test radio button is checked means test is positive and vice-versa
editor.putBoolean("STValue", posValuerb1.isChecked());
 
 
//To confirm the changes or to save them
editor.commit();
 }
And below my display() method to retrieve and display data from the shared preference object:
// Method to Display special tests performed in the STData file
public void display(View view)
{
 
 
// User SharedPreferences to save the value per special name
SharedPreferences sharedPref = getSharedPreferences("STData", Context.MODE_PRIVATE);
 
shoulderSpinner.setSelection(sharedPref.getInt("spinnerSelection",0));
//save special test Value in String 'testValue' <= entered by the PT
String testValue = sharedPref.getString("STValue", DEFAULT);
 
 
// DISPlAY THE VALUES ON THE SCREEN OF ACTIVITY !!!!

 // Test Name
STNameTextView = (TextView) findViewById(R.id.STView3);
STNameTextView.setText(testName);
 
 // Name of the Special Test
STValueTextView = (TextView) findViewById(R.id.STView4);
STValueTextView.setText(testValue);
 }
}
You're clearly misunderstanding the way SharedPreference class works.
Since you decided to persist a int value with the key "specialTestName"
you should retrieve it as follows, to obtain the saved int:
int selectedPosition = sharedPrefObj.getInt("specialTestName", DEFAULTINT);
Also, what you are saving from the checkbox is a boolean value, so you cannot try to retrieve as String.
boolean checkValue = sharedPrefObj.getBoolean("STValue", DEFAULTBOOLEAN);
Btw I highly recommend you to create a class that interacts directly with the SharedPreference instead of use it directly from the Activity/Fragment.
Hope this helps you.

Object of main activity in result activity not properly accessing boolean variable?

I have a main class that holds two array lists of class objects. Long story short, I'm calling an activity via startActivityForResult to get a return of the position of a spinner item selection. I have two boolean variables in the main activity that basically tell the application which list is being worked with: booleans listASelected and listBSelected. If listASelected = true, then listBSelected = false and visa-versa. In the result activity I basically generate the spinner this way:
MainActivity mainAct = new MainAtivity();
Spinner dropdown = (Spinner)findViewById(R.id.mainMenu);
for(int i = 0;i<mainAct.pickThreeNumbers.size(); i++){
optionsPickThree.add(mainAct.pickThreeNumbers.get(i).getNumbers(1)+mainAct.pickThreeNumbers.get(i).getNumbers(2)+mainAct.pickThreeNumbers.get(i).getNumbers(3));
}
for(int r = 0; r<mainAct.pickFourNumbers.size();r++){
optionsPickFour.add(mainAct.pickFourNumbers.get(r).getNumbers(1)+mainAct.pickFourNumbers.get(r).getNumbers(2)+mainAct.pickFourNumbers.get(r).getNumbers(3)+mainAct.pickFourNumbers.get(r).getNumbers(4));
}
if(mainAct.pickThreeSelected){
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, optionsPickThree);
}else{
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, optionsPickFour);
}
dropdown.setAdapter(adapter);
Then, I use this to do my setResult.
Intent output = new Intent();
if(mainAct.pickThreeSelected){
output.putExtra("slot", position);
output.putExtra("list", "PickThree");
}else{
output.putExtra("slot", position);
output.putExtra("list", "PickFour");
}
setResult(1,output);
finish();
}
The issue is that nomatter what it always works as if mainAct.pickThreeSelected = true, even if I know it is false because other sections of the app are functioning properly. What I assume is happening is that the class object is accessing the variable's initialized values instead of their current values at the time of execution. That, or I'm an idiot and there's a different way to accomplish this.
Any help, fellas? Thanks in advance!
Make pickThreeSelected as static. That way you will update the same instance everytime.
What is the default value that you have set to the mainAct.pickThreeSelected??If its true,make it as false.Then if user selects the listA change the value to true.

Getting a value from a class extending activity in a plugin

When jumping from Activity to activity via Cordova, plugin, i want to be able to put additional information into a bundle and pass it along with the intent. I seem to have issues getting the current activity and then getting a value via
public int getCounter(){return counter;}
I have a Activity Definition which, onCreate will set counter to a value from the passed in bundle.
I have a Cordova plugin then which i am working with, which will carry out the intent to next activity.
Echo Class is a mediary which will jump between acticities based on html clicks.
//In the Class: public class Echo extends CordovaPlugin
private void launchSecondActivity(String data, CallbackContext cc){
Bundle b = new Bundle();
int tmp = ((SecondaryActivity)cordova.getActivity()).getCounter();
tmp++;
b.putInt("id", tmp);
Intent i = new Intent(cordova.getActivity().getApplicationContext(), SecondaryActivity.class);
i.putExtras(b);
cordova.getActivity().startActivity(i);
cc.success();
}
It seems that it causes a seg fault of sorts, when i am trying to assign counter to tmp, in the line:
int tmp = ((SecondaryActivity)cordova.getActivity()).getCounter();
Is there something i am doing wrong? I am trying to get the currently active activity, and then call a public function in that activity.
End Goal: I am trying to take an int, and keep passing it into intents, incremented. So that way, it will know how deep into the activity chain it is. I am working on nested state saving and curious as to the depth i am at, at any given time. The tmp being passed into the activity will be incremented each time, so it will maintain a depth.
Instead of creating a class with get counter, storing the int in the Bundle and passing it to the next activity would be far easier.
Example:
//send item to plugin.
int item = 0; // or whatever it is
Bundle b = new Bundle();
b.put("ident", item);
Intent i = new Intent();
i.putExtras();
//...
And then on the next activity.
public void onCreate(Bundle savedInstanceState)
{
int item = getIntent().getExtras().getInt("ident");
}
Then you can do with it what you will. The answer overall while the previous activity as the old number. What does that mean? It means that you can increment and do whatever you want with it when passing it to the next activity. It is copied, so you can incrememnet and store it recursively. Allowing you to even say something like:
if (item ==0){/*set new source for Activity*/}
else if(item == 1){/*set source 2*/}
//etc.

Categories

Resources