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.
Related
I have a main fragment and two fragments in view pager (About/Reviews).
I call api to load data when navigation bar selected. I want to data model I have called api can be used between three fragments. I don't want to call api three times when the fragments load.
ok you want to call the api only once , that is when the activity is created right ?
ok for that initialize a int variable and set the value to 0;
int a=0;
then use condition to call your api
if(a==0)
{
//Your code To call Api
a=1;
}
So Here After U call Your Api Once "a is set to 1" which does not satisfy the condition and it does not call the api for the second time ...
but "a=0" when the your class or activity is created or called ..the api is also called
This Solution Is Given , Keeping That The Activity Is Not Recalled Or Recreated Unnecessarily ( Or The Activity Is Not Recalled/Recreated On Changing The Fragment )
when you create the fragment just pass the data.
Fragment fragment = new DemoFragment();
Bundle args = new Bundle();
args.putString("TERM", "FINEL TERM");
fragment.setArguments(args);
You can receive data from the fragment
Bundle args = getArguments();
String termStatus = args.getString("TERM")
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.
Make an AdapterArray become an IntArray because I can't send to another activity an adapter array.
I'm creating a racing timer in Android Studio Java and I have saved my data about the race (example: time of all turns) in an Array Adapter. But when I try to send it to another Activity the function doesn't accept ArrayAdapter so I created a function to turn ArrayAdapter into an IntArray the problem is that whenever I run that function the program crashes.
I'm looking for an answer to this problem by correcting my code or doing a completely different one if I had to.
public int[] AdapterToInt(ArrayAdapter adapter)
{
int[] a = new int[adapter.getCount()];
for (int i = 0; i < adapter.getCount(); i++)
{
a[i] = Integer.valueOf(adapter.getItem(i));
}
return a;
}
public void onButtonClickSaveTimes(View view) {
int[] array;
array = AdapterToInt(adapter1);
TextView textoexemplo = (TextView) findViewById(R.id.textViewhorario);
Intent myIntent = new Intent(getBaseContext(), Main5Activity.class);
myIntent.putExtra("car1", AdapterToInt(adapter1));
myIntent.putExtra("car2", AdapterToInt(adapter2));
myIntent.putExtra("car3", AdapterToInt(adapter3));
myIntent.putExtra("car4", AdapterToInt(adapter4));
myIntent.putExtra("car5", AdapterToInt(adapter5));
startActivity(myIntent);
}
I expect it to send the ArrayAdapter to another activity or at least making my function work and turn ArrayAdapter into ArrayInt so i can send it through myIntent.putExtra, but the actual output is a app crash.
The problem is likely here:
a[i] = Integer.valueOf(adapter.getItem(i));
Since adapater.getItem(i) returns an object that you likely will not be able to convert into an integer, you are probably going to have issues here.
You could instead use adapter.getItemId(i) which would return a long as opposed to an object.
However, that idea also doesn't seem to great so I would try to see if anything from here works for you.
And if none of that works it probably makes more sense to just send over all the data you need to reconstruct your ArrayAdapter to the other activity.
This link may also help:
How do I pass custom ArrayAdapter Object between Intents with serialization
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
}
I wish to store several instances of a simple class as part of saving my apps state when the activity is not in focus.
public class Player
{
int score1;
int score2;
int total;
}
I've been told parceling is the way to go. What advantages does this hold over saving the variables individually using the method below?
savedInstanceState.putInt(player.getScore1);
Edit:
I will likely store up to 50 instances of each of these classes and eventually increase the number of variables in them to 12.
Serialization springs to mind but everywhere I turn I'm told it is a slow inefficient method of storage and even that the android documentation advises to avoid it.
My first advice will be using SharedPreference instead of savedInstanceState.
savedInstanceState Has its own pro's and con's.
If app is closed by user interaction like Back or home button then savedInstanceState will not be called.It is called only when app is disturbed by android o.s. itself like you are using app and call occured and app goes in background.
In sharedpreference u will have control in you hand writing your own logic the way you want.
Whenever a activity is killed, either by system or use, onPause() method is always called.
You can use SharedPreferences to store your values and, thus, can retrieve it when activity is again created.
According to your code, you can make changes like this:
public class Player extends Activity {
private SharedPreferences mPrefs;
int score1;
int score2;
int total;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences mPrefs = getSharedPreferences();
score1 = mPrefs.getInt(String key1, int defaultValue);
score2 = mPrefs.getInt(String key2, int defaultValue);
total = mPrefs.getInt(String key3, int defaultValue);
}
protected void onPause() {
super.onPause();
SharedPreferences.Editor ed = mPrefs.edit();
ed.putInt(key1, score1);
ed.putInt(key2, score2);
ed.putInt(key3, total);
ed.commit();
}
}
String key is the name of the preference.
int defaultValue is the default value returned when nothing is stored. It is generally returned when the activity is first created
I used the following method to store my players instances.
public Object onRetainNonConfigurationInstance()
{
if (table != null) // Check that the object exists
return(table);
return super.onRetainNonConfigurationInstance();
}
The table instance stored contains an array holding all my player instances. When reloading my app the table object was loaded within the onCreate method using this code:
if (getLastNonConfigurationInstance() != null)
{
table = (Table)getLastNonConfigurationInstance();
}
*This method is depreciated yet none of my beta testers phones have had any issues with it.
*This only works when your app has been shutdown by your phones OS and not when closed manually. Many users will press the back button not knowing it closes the app whilst home minimizes. The article below has many good approaches for ways to circumvent this.
http://www.androiduipatterns.com/2011/03/back-button-behavior.html