How to give user option to choose currency format - android

I want to give users option to select Currency display format like in this example:
Couple of challenges I face. First I do not know how to pass the values of
Currency.getAvailableCurrencies();
to the ListPreference entries and values set. Below is my attempt.
First the xml
<ListPreference
android:key="currency"
android:title="Currency"
android:defaultValue="$"
android:negativeButtonText="#null"
android:positiveButtonText="#null" />
Then this is how I try to populate the listPreference from code
public static class SettingsFragment extends PreferenceFragment {
#TargetApi(Build.VERSION_CODES.KITKAT)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Add preference xml
addPreferencesFromResource(R.xml.pref_general);
//Get root PreferenceScreen
PreferenceScreen mPreferenceScreen = getPreferenceManager().createPreferenceScreen(getActivity());
//Get the currency list preference
ListPreference listPref = (ListPreference) mPreferenceScreen.findPreference("currency");
//Get available currency set
Set<Currency> currencySet = Currency.getAvailableCurrencies();
//Convert the currency Set<E> to String[] so I can get Array contents
String[] currencyArray = currencySet.toArray(new String[currencySet.size()]);
CharSequence[] entries = new CharSequence[currencyArray.length];
CharSequence[] values = new CharSequence[currencyArray.length];
for (int i = 0; i < entries.length; i++){
entries[i] = currencyArray[i].toString();
values[i] = currencyArray[i].toString();
}
listPref.setEntries(entries);
listPref.setEntryValues(values);
}
}
The above failed with the following exceptions
Caused by: java.lang.ArrayStoreException: source[0] of type java.util.Currency cannot be stored in destination array of type java.lang.String[]
So how can I present a human readable list of available currencies in a ListPreference>
UPDATE - WORKING CODE
For anyone reading, here is the updated working code per the answer below, not sure what I will do with Pre KitKat devices at this time
public static class SettingsFragment extends PreferenceFragment {
#TargetApi(Build.VERSION_CODES.KITKAT)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Add preference xml
addPreferencesFromResource(R.xml.pref_general);
//Get root PreferenceScreen
PreferenceScreen mPreferenceScreen = (PreferenceScreen)getPreferenceScreen();
//Get the currency list preference
ListPreference listPref = (ListPreference) mPreferenceScreen.findPreference("currency");
if (listPref != null) {
//Get available currency set
Set<Currency> currencies = Currency.getAvailableCurrencies();
CharSequence[] entries = new CharSequence[currencies.size()];
CharSequence[] values = new CharSequence[currencies.size()];
int i = 0;
for (Currency currency: currencies){
String tempCurrency = String.format("%s\t%s\t%s",currency.getDisplayName(), currency.getSymbol(), currency.toString());
if (!tempCurrency.trim().isEmpty()){
entries[i] = tempCurrency;
values[i] = currency.getSymbol();
}
i++;
}
listPref.setEntries(entries);
listPref.setDefaultValue("$");
listPref.setEntryValues(values);
} else {
Toast.makeText(getActivity(), "ListPreference is null", Toast.LENGTH_SHORT).show();
}
}
}

This line seems like the problem, I dont know why you think it would automatically cast the Currency object to a string
//Convert the currency Set<E> to String[] so I can get Array contents
String[] currencyArray = currencySet.toArray(new String[currencySet.size()]);
You want to replace that with something like:
Set<Currency> currencies = Currency.getAvailableCurrencies();
for (Currency currency: currencies) {
System.out.printf("%s\t%s\t%s\n",currency.getDisplayName(), currency.getSymbol(), currency.toString());
// your code to check whether the symbol is not empty here
// add it to your String array or just directly use the
// CharSequences arrays for entries and values here.
}

Related

Storing String array from other string array

I create on Setting page With Spinner in spinner have a hospital name to select
and when selected hospital in hospital have a phone number to save setting to button clicked call to that hospital
This my String-Array
I have two string - array first is a phone number of hospital
and second is hospital name I need to storing number to hospital name same as line when I selected in spinner
<string-array name ="number">
<item>055270300</item>
<item>055909000</item>
<item>055212222</item>
</string-array>
<string-array name="hospital">
<item>hospital 1</item>
<item>hospital 2</item>
<item>hospital 3</item>
</string-array>
And Here is my Activity:
TextView title = (TextView) findViewById(R.id.toolbar_title);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
title.setText(toolbar.getTitle());
title.setText("การแจ้งเหตุฉุกเฉิน");
phonenum = (EditText)findViewById(R.id.input_phonenum);
message = (EditText)findViewById(R.id.put_message);
preferences = getSharedPreferences(shared_preferences,Context.MODE_PRIVATE);
editor = preferences.edit();
spinner = (Spinner)findViewById(R.id.sos_spinner);
String[] hospital = getResources().getStringArray(R.array.hospital);
ArrayAdapter<String> adapterhospital = new ArrayAdapter<String>(this ,android.R.layout.simple_list_item_1, hospital);
spinner.setAdapter(adapterhospital);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
editor.putInt(String.valueOf(getResources().getStringArray(R.array.number)), R.array.hospital);
editor.commit();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
button = (Button)findViewById(R.id.save_btn);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String getMessage = message.getText().toString();
int getPhonenum = Integer.parseInt(phonenum.toString());
editor.putInt(stored_phonenum, getPhonenum);
editor.putString(stored_message , getMessage);
editor.commit();
Toast.makeText(HowtoActivity.this, "Data Saved.",
Toast.LENGTH_SHORT).show();
}
});
}
I would recommend creating the array using java as opposed to xml.
Its quite simple,
ArrayList<String> hospitals= new ArrayList<>();
then add the hospitals to this array list this way :
hospitals.add("Hospital 1");
hospitals.add("Hospital 2");
hospitals.add("Hospital 3");
Note that this(hospitals array) is the array you will be storing in your spinner.
For the task you want to achieve, this is how i would proceed to do it :
You can have one more arraylist to store both hospital and its respective number seperated by a comma(,):
So create another arrayist, lets call it numbers.
ArrayList<String> numbers = new ArrayList<>();
numbers.add("Hospital 1,71955555");
numbers.add("Hospital 2,71955556");
numbers.add("Hospital 3,71955557");
Now once the user selects an item on the spinner, use the onItemSelected to get the value and store it in shared preferences.
Now just loop through the number arrayList and collect the number if your selected value is equal to the hospital name. You can split the value where the comma is. This way :
for(int i=0;i<numbers.size();i++){
String value = numbers.get(i);
String names[]= value.split(",");
String name = names[0];
if(name.equalsIgnoreCase("Value stored from spinner"){
String number = names[1];
//Store this number in shared preferences as the value for the hospital //selected
}
}
From here you can call the hospital number from your shared preferences in any activity where it is needed.
You can use xml pull Parser for this purpose.
Create an xml like this
<?xml version="1.0" encoding="utf-8"?>
<resources>
<hospital>
<hospital>
<a_name>hospital 1</a_name>
<a_number>71955555</a_number>
</hospital>
<hospital>
<a_name>hospital 1</a_name>
<a_number>71955555</a_number>
</hospital>
<hospital>
<a_name>hospital 1</a_name>
<a_number>71955555</a_number>
</hospital>
<hospital>
<a_name>hospital 1</a_name>
<a_number>71955555</a_number>
</hospital>
</hospitalprovider>

SharedPreferences not saving all the data after restart

I am new to Android App Development and I am supposed to make a TodoList App for a course. But the SharedPreference in my code is not working. I dont know if I'm supposed to use it in a specific way in a specific method like onCreate or onStop.
It is saving the first input the user is entering permanently, but in the same position:
(The "task0" is what I used to track the different variable names I used as argument for "putString" in addStuff method, to avoid replacing values)
It is saving the inputs after that in the same session, but if the user ends that session, all those values after "t" are gone. If the user restarts the app and inputs something else (like "g"), it is saving "g" in that same 3rd position.
I have basic Java knowledge and I tried to understand what is going on using it, but failed. Please let me know where is the mistake and how to use SharedPreferences properly.
public class TodoActivity extends AppCompatActivity {
public ArrayList<String> items;
public ArrayAdapter<String> itemsAdapter;
public ListView list;
public String s;
public EditText taskBox;
public static final String filename = "itemsList";
public TextView text;
public static int counter = 0;//counter starting at 0 no matter what, everytime the app starts
public String newtask= "task";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_todo);
list = (ListView) findViewById(R.id.list1);text = (TextView) findViewById(R.id.text1);
taskBox = (EditText) findViewById(R.id.box);
s = taskBox.getText().toString();
items = new ArrayList<String>();
itemsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
list.setAdapter(itemsAdapter);
//add items to list
items.add("First Item");
items.add("Second Item");
//restore
SharedPreferences sp = this.getSharedPreferences("itemsList", 0);
//checking if it stores the previous values, this gives the last input but not the previous ones after restarting the app
String dummyname = "task";
text.setText(String.valueOf(counter));//since counter is again at
for(int c=0; c<=50; c++){
String num = String.valueOf(c);
dummyname = dummyname + num;
String x = sp.getString(dummyname, "not found");
if (x.equalsIgnoreCase("not found")){
counter=c-1;
break;
} else {
items.add(x);
text.setText(dummyname);
}
}
}
public void addItem(View v){
s = taskBox.getText().toString();
itemsAdapter.add(s);//adding the new task as string
String temp = String.valueOf(counter);
newtask = "task" + temp;
//trying to store the new tasks with different variable names to avoid being replaced
text.setText(newtask);
SharedPreferences sp = this.getSharedPreferences("itemsList", 0);
SharedPreferences.Editor e = sp.edit();
e.putString(newtask,s);
e.apply();
counter++;
}
}
If you have relatively small collection of key-values that you would like to save,
You should use Shared preference API
Read from the shared preference:
Pass the key and value you want to write,create a SharedPreferences.Editor by calling edit() on your SharedPreferences.
Pass key and values you want to save by using this method putInt() ,putString() ,Then call commit() to save the changes. For example:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("KeyName", newHighScore);
editor.commit();
Write from the shared preference:
To retrieve values from a shared preferences file, call methods such as getInt() and getString(),
providing the key for the value you want, and optionally a default value to return if the key isn't present. For example:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt("KeyName", defaultValue);
Two things :
1) To initialize SharedPreferences use :
sharedPreferences = getSharedPreferences("itemsList", Context.MODE_PRIVATE);
2) Where are you calling addItem() method??
The problem is about the Tag you use to save items. See this Line :
dummyname = dummyname + num;
You add item by this format :
task0
task1
task2
but you are getting values in this format
task0
task01
task012
Just change these two line of code :
//dummyname = dummyname + num;
//String x = sp.getString(dummyname, "not found");
String newDummy= dummyname + num;
String x = sp.getString(newDummy, "not found");

Using a variable to switch to a certain spinner item

I have:
a String array with an unknown length that's populated with unknown items (let's say fish, bird, cat)
an ArrayAdapter and a Spinner that displays the items
a variable that contains one unknown item from the string array (let's say cat)
I want to set the Spinner to the value from the variable (cat). What's the most elegant solution? I thought about running the string through a loop and comparing the items with the variable (until I hit cat in this example), then use that iteration's # to set the selection of the Spinner, but that seems very convoluted.
Or should I just ditch the Spinner? I looked around and found a solution that uses a button and dialog field: https://stackoverflow.com/a/5790662/1928813
//EDIT: My current code. I want to use "cow" without having to go through the loop, if possible!
final Spinner bSpinner = (Spinner) findViewById(R.id.spinner1);
String[] animals = new String[] { "cat", "bird", "cow", "dog" };
String animal = "cow";
int spinnerpos;
final ArrayAdapter<String> animaladapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, animals);
animaladapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
bSpinner.setAdapter(animaladapter);
for (Integer j = 0; j < animals.length; j++) {
if (animals[j].equals(animal)) {
spinnerpos = j;
bSpinner.setSelection(spinnerpos);
} else {
};
}
(Temporarily) convert your String array to a List so you can use indexOf.
int position = Arrays.asList(array).indexOf(randomVariable);
spinner.setSelection(position);
EDIT:
I understand your problem now. If your String array contains all unique values, you can put them in a HashMap for O(1) retrieval:
HashMap<String, Integer> map = new HashMap<String, Integer>();
for (int i = 0; i < animals.length; i++) {
map.put(animals[i], i);
}
String randomAnimal = "cow";
Integer position = map.get(randomAnimal);
if (position != null) bSpinner.setSelection(position);

how to show Selected Value In Spinner using array Adapter?

As i am newbie in android i want to show my saved spinner value at the time of view of saved form
how can i show database saved value at the time of view for spinner
here is my code
Java activity file
Spinner spnAECust;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ae_view_edit_sales);
spnAECust = (Spinner) findViewById(R.id.spnAECust);
/* Get Customer List and Add Select Default */
cust = con.getAllCustomers();// from database getting list
List<Customer> custList = new ArrayList<Customer>();
Customer c = new Customer();
c.setId(Constants.Common.ZERO);
c.setNm("Select Customer");
custList.add(c);
custList.addAll(cust);
// Create and fill an ArrayAdapter with a bunch of "Customer" objects
ArrayAdapter<Customer> custArrayAdapter = new ArrayAdapter<Customer>(this, android.R.layout.simple_spinner_item,
custList.toArray(new Customer[custList.size()]));
// Tell the spinner about our adapter
spnAECust.setAdapter(custArrayAdapter);
sa = con.getAirSalesActivityDetails(Integer.parseInt(saId));// get details from Sqlite
Customer cust = new Customer();
cust.setId(sa.getCustomerId());
spnAECust.setSelection(custArrayAdapter.getPosition(cust));// to set value saved in db
}
at tried setSelection but it maches index value rather than id value so i get abstract value to b selected please show me correct way to implement ...Thnks in advance
Here i got answer by my own
/* Get Customer List and Add Select Default */
cust = con.getAllCustomers();
List<Customer> custList = new ArrayList<Customer>();
Customer cst = new Customer();
cst.setId(Constants.Common.ZERO);
cst.setNm(Constants.Common.CUSTOMER_HINT);
custList.add(cst);
custList.addAll(cust);
/* Get Commodity List and Add Select Default */
comm = con.getAllCommodities();
List<Commodity> commList = new ArrayList<Commodity>();
Commodity cm = new Commodity();
cm.setId(Constants.Common.ZERO);
cm.setNm(Constants.Common.COMMODITY_HINT);
commList.add(cm);
commList.addAll(comm);
// Create and fill an ArrayAdapter with a bunch of "Customer" objects
ArrayAdapter<Customer> custArrayAdapter = new ArrayAdapter<Customer>(this, android.R.layout.simple_spinner_item,
custList.toArray(new Customer[custList.size()]));
int custIndex = 0;
// to set selected item
for (int r = 0; r < custArrayAdapter.getCount(); r++) {
if (sa.getCustomerId() == custArrayAdapter.getItem(r).getId()) {
custIndex = r;
break;
}
}
// Tell the spinner about our adapter
spnAECust.setAdapter(custArrayAdapter);
spnAECust.setSelection(custIndex);
// Create and fill an ArrayAdapter with a bunch of "Commodities" objects
ArrayAdapter<Commodity> commArrayAdapter = new ArrayAdapter<Commodity>(this, android.R.layout.simple_spinner_item,
commList.toArray(new Commodity[commList.size()]));
int commIndex = 0;
// to set selected item
for (int r = 0; r < commArrayAdapter.getCount(); r++) {
if (sa.getCommodityId() == commArrayAdapter.getItem(r).getId()) {
commIndex = r;
break;
}
}
// Tell the spinner about our adapter
spnAEComodity.setAdapter(commArrayAdapter);
spnAEComodity.setSelection(commIndex);
used for loop to get index for saved value
int commIndex = 0;
// to set selected item
for (int r = 0; r < commArrayAdapter.getCount(); r++) {
if (sa.getCommodityId() == commArrayAdapter.getItem(r).getId()) {
commIndex = r;
break;
}
}
and add index to
spnAEComodity.setSelection(commIndex);

Retrieve android parse column and set it to array

I have a table in Parse which is named Customer_Information. And there is a column named username. I want to retrieve all the values in the username column and store it to array. After storing, i want to set it to a single textview. Is this possible? I've tried this code but it has an error ArrayIndexOutOfBounds.
public class Users extends Activity{
private static final String tbname = "Customer_Information";
private static final String uname = "username";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.users);
TextView text = (TextView)findViewById(R.id.text);
ParseQuery query = new ParseQuery(tbname);{
try{
List<ParseObject> test = query.find();
for(int x=0;x<test.size();x++){
String[] str = {test.get(x).getString(uname)};
text.setText("Username: "+str[x]+"\n");
}
}
catch (com.parse.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
The problem is most likely with this line:
text.setText("Username: "+str[x]+"\n");
You are trying to access an index, but you are accessing it with x. If all the ParseObjects return an array of the same length, after a while, as x increases, it will become greater than that array's greatest index, resulting in an IndexOutOfBoundsException.
I suggest you first do some testing: print out the values of str, figure out what index you need, then change the line so it uses the constant index. Based on the fact that you only have 1 element in the array since you do
String[] str = {test.get(x).getString(uname)};//one element array
the index is most likely 0:
text.setText("Username: "+str[0]+"\n");
If you are not going to make str any larger than 1 element, discard it and use just a single String.

Categories

Resources