Using a Spinner value in a calculation - java

Wondering if i can get some help with a problem i'm having? I have searched for the answer on here, and although i found a few relevant topics i'm still really struggling...
Below you can see that i'm using a Spinner asking the user to select either Large, Med or Small.
The selection is then issued to a TextView.
What i now want to do is assign a value to the 3 selections, Large = 6, Med = 4, Small =2.
Next there will be a EditText box for the user to add their own value.
Then i want to put the two values into a calculation (say * them in this example) putting the answer into a TextView.
Any help here would be great.
Many Thanks
Will
String[] items = { "Large", "Med", "Small" };
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.plugfan);
Factor = (TextView) findViewById(R.id.Factor);
Spinner spin = (Spinner) findViewById(R.id.spinner);
spin.setOnItemSelectedListener(this);
ArrayAdapter aa = new ArrayAdapter(
this,
android.R.layout.simple_spinner_item,
items);
aa.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(aa);
}
public void onItemSelected(AdapterView<?> parent, View v, int position,
long id) {
Factor.setText(items[position]);
}
public void onNothingSelected(AdapterView<?> parent) {
Factor.setText("");
}

A quick way to solve this (not the smartest one) is to have a paralell array:
int[] itemValues = { 6, 4, 2 };
In the method onItmeSelected you can setText using the itemValue, instead of items.
If you want a more OO-solution a new class that returns a list of Strings to use as a model for your spinner might be a beter solution (an enumeration might solve it too).

Related

How to get a value from listview with multidimensional array?

So I have a multidimensional array for my listview, it constructed like this:
String[][] listControls = {
{"Shutdown Host","10"},
{"Close Connection","1"}};
Let say the first String is the text I want to display in the list view, and the other one is a id/message to send via socket (lets say it a secret value).
I coded the Adapter like this:
ArrayAdapter adapter = new ArrayAdapter<String>(this,R.layout.layout_listview);
for(int i = 0; i < listControls.length; i++) {
adapter.add(listControls[i][0]);
}
listView = (ListView) findViewById(R.id.controls_listView);
listView.setAdapter(adapter);
listView.setClickable(true);
And I constructed the click listener of an item:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Object obj = listView.getItemAtPosition(position);
//What should I add here? to get specific value from the array?
//Integer cmdId = Integer.parseInt( ... );
}
});
From the click listener, i want to get the other value, e.g. If I clicked "Close Connection" in list view, I want to get the "1" value from it and put it into a variable.
Thanks in advance for the help.
Write custom adapter for your case. Use HashMap which is always better.
HashMap<String, Integer> map = new LinkedHashMap<>();
map.add("Shut Down Host", 0);
map.add("Close connection", 1);
And most importantly use RecyclerView.
Tutorial for RecyclerView https://developer.android.com/guide/topics/ui/layout/recyclerview
What you could do is
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String value = listControls[position][1]
}
This will, of course work only if you have access to listControls. If not, I'd opt for creating an object SomethingWithCode(String text, Int code)[or just Pair in kotlin] and creating a custom adapter.
Hope this helps!
Also, you probably don't need multidimensional array for it, if you're always passing just two values(refer to object with string and int parameters)

MPAndroid Chart - Chart not updating

Im using the Horizontal MPAndroid chart to display income/Expense and the chart works for the most. I can change the information displayed although I can only change it if I do it in OnViewCreated. Nothing at all happens if I try doing it from the activity in which the fragment is displayed and I have absolutely no idea why. Although I am not 100% sure if I am setting the data the right way.
public class BudgetFragment extends Fragment{
private HorizontalBarChart mainChart;
private BarData data;
private BarDataSet dataset1;
private BarDataSet dataset2;
private int expenseSum = 0;
private int incomeSum = 0;
public MainActivityBudgetFragment(){
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.budget_fragment, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mainChart = (HorizontalBarChart) view.findViewById(R.id.mainBudgetChart);
ArrayList<BarEntry> entries1 = new ArrayList<>();
ArrayList<BarEntry> entries2 = new ArrayList<>();
entries1.add(new BarEntry(10000, 5));
entries2.add(new BarEntry(10000, 5));
dataset1 = new BarDataSet(entries1, "income");
dataset2 = new BarDataSet(entries2, "expense");
//X-axis labels
ArrayList<String> xVals = new ArrayList<String>();
xVals.add("income"); xVals.add("expense");
ArrayList<BarDataSet> dataSets = new ArrayList<BarDataSet>();
dataSets.add(dataset1);
dataSets.add(dataset2);
//Add to chart
data = new BarData(xVals, dataSets);
mainChart.setData(data);
//Description and animation
mainChart.setDescription(""); // set the description
mainChart.setScaleYEnabled(false);
mainChart.setTouchEnabled(false);
mainChart.animateY(2000);
setDataExpense(200);//(This works fine)
setDataIncome(200); //(This works fine)
}
public void updateDataExpense(){
Log.e("updateTag", "Updated expense");
dataset2.removeEntry(1);
data.addEntry(new BarEntry(expenseSum, 1), 1);
dataset2.setColor(getResources().getColor(R.color.orange));
mainChart.notifyDataSetChanged(); // let the chart know it's data changed
mainChart.invalidate(); // refresh
}
public void updateDataIncome(){
Log.e("updateTag", "Updated Income");
dataset1.removeEntry(0);
data.addEntry(new BarEntry(newIncome, 0), 0);
dataset1.setColor(getResources().getColor(R.color.green));
mainChart.notifyDataSetChanged(); // let the chart know it's data changed
mainChart.invalidate(); // refresh
}
//(These do not work when called outside OnViewCreated)
private void setDataExpense(int sum){
expenseSum = (expenseSum + sum);
Log.d("ResumeTag", "expense set at " + expenseSum);
updateDataExpense();
}
private void setDataIncome(int sum){
incomeSum = (incomeSum + sum);
Log.d("ResumeTag", "income set at " + incomeSum);
updateDataIncome();
}
}
Let me know if I forgot anything important. I do not have much experience in asking questions on Stackoverflow.
Thank you for your help!
//Chris
Please try this :
public void updateDataIncome() {
Log.e("updateTag", "Updated Income");
dataset1.removeEntry(0);
data.addEntry(new BarEntry(newIncome, 0), 0);
dataset1.setColor(getResources().getColor(R.color.green));
data.notifyDataChanged(); // NOTIFIES THE DATA OBJECT
mainChart.notifyDataSetChanged(); // let the chart know it's data changed
mainChart.invalidate(); // refresh
}
Your question does say what action is performed for which you expect the data to be updated. On whatever action you want the data to be refreshed, you should have one of the listener and then call your functions that populates the data that you want to be refreshed.
For example in this code on selection of a value in Spinner, onItemSelected(..) gets invoked & within it we are calling the populate function that refreshes the data. This is partial code but you can find a complete example of using Adapter & OnItemSelectedListener. Hope this helps you.
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, monthList);
// Setting the array adapter containing country list to the spinner widget
spinnerMonth.setAdapter(adapter);
AdapterView.OnItemSelectedListener monthSelectedListener = new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> spinner, View container,
int position, long id) {
Log.d("Logger:MainAct"," onItemSelected:Entry::::");
tvMonth.setText("Chart for "+strMonth[position]);
populateChartByMonth(strMonth[position]);
//Toast.makeText(getApplicationContext(), "Success : " + strMonth[position], Toast.LENGTH_SHORT).show();
Log.d("Logger:MainAct"," onItemSelected:Exit::::");
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
Log.d("Logger:MainAct"," onNothingSelected:Entry/Exit");
}
};
entries1.add(new BarEntry(10000, 5));
This line x value is 1 and Y value is 10000
entries1.add(new BarEntry(5,10000));

How to make listView say one thing, but pass through different data

So this question is a little hard to explain, but basically what i want is to have an array list for a listview, but change the title on the listview. So that when the user sees the listview it says one thing, but passes through different information.
Here's my code:
//the string names
String names[] = { "item1", "item2"};
i have 2 classes called item1.java and item2.java
when one listitem is clicked it sets a class equal to the activity name and opens it like this:
protected void onListItemClick(ListView lv, View v, int position, long id){
super.onListItemClick(lv, v, position, id);
String openClass = names[position];
try{
Class selected = Class.forName("com.example.example." + openClass);
Intent selectedIntent = new Intent(this, selected);
startActivity(selectedIntent);
}catch (ClassNotFoundException e){
e.printStackTrace();
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
But in the listview i don't want it to say "item1" and "item2"....is there any way to make like an alias or something?
Sorry if my question is hard to understand i tried my best to explain what i need help with let me know if you have any questions about my question(: thanks for the help
You do this the same way you make any custom adapter, such as one that should display images instead of or in addition to some text.
For example, if your adapter is an ArrayAdapter, you create a subclass, override getView(), and do what you want in there to format your rows the way that you want.
You can override toString() to do this. See following example
public static class Alias {
String originalValue;
public Alias(String s) {
this.originalValue = s;
}
#Override
public String toString() {
return "What are you want to show";
}
}
String names[] = {"item1", "item2"};
Alias array[] = new Alias[names.length];
Alias array[0] = new Alias(names[0]);
Alias array[1] = new Alias(names[1]);
ArrayAdapter<Alias> adapter = new ArrayAdapter<Alias>(this, resId, array);
This will show "What are you want to show" in every listview whatever the value is.

Android - saving checked items of a ListView on app shutdown

I am making an application for the Android platform in Eclipse, and I need help with something. :)
What I want for one part to do is create an arraylist from items that are checked in another ListView. I figured out how to make that and here is the code:
public class MusicList extends Activity {
private ListView lvCheckBox;
private String[] arr = { "Depeche Mode", "The Prodigy", "Rammstein",
"Manilla Road", "Led Zeppelin", "AC/DC", "Massive Attack",
"Skrillex", "Deadmau5" };
ArrayList<String> arrList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.musiclist);
lvCheckBox = (ListView) findViewById(R.id.lvCheckBox);
lvCheckBox.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lvCheckBox.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_checked, arr));
arrList = new ArrayList<String>();
lvCheckBox.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
if(arrList.contains(lvCheckBox.getItemAtPosition(arg2).toString()))
{
arrList.remove(lvCheckBox.getItemAtPosition(arg2).toString());
}
else
{
arrList.add(lvCheckBox.getItemAtPosition(arg2).toString());
}
Collections.sort(arrList);
String strText = "";
for(int i=0 ; i<arrList.size(); i++)
strText += arrList.get(i) + ",";
Toast.makeText(MusicList.this, "Item Clicked: "+ strText, Toast.LENGTH_SHORT).show();
}
});
}
}
BUT!
Now I need to save that arraylist (like some "user settings" (actually the music which the user likes)) even when the app closes completely and when I come back to the list screen previously checked items need to be checked again (bear in mind I will be adding a lot more musicians to the starting list!!). So, anyone knows how to do that? :)
That's all, thanks in advance, and also I am new here so sorry if I messed something up :(
Android has a SharedPreferences class that will allow you to save information to the App's "cache".
So, you'd be able to save and retrieve the list information.
http://developer.android.com/reference/android/content/SharedPreferences.html

want a simple code for the getting the state name and city name depend on the selection

I am new to both android and java. I am developing a simple app which contain country , state and city which are selected by spinner. Now consider while am selecting the country(India) then i need to get only states of india. And then while selecting any state(Andhra pradesh) then the cities of A.P should be shown in the next spinner. Can any one suggest me with some sample code.
thanks in advance
you can add this logic(for two spinners) to your code:
public void onCreate() {
....
Country[] mCountries = ... ;
final Spinner spinner1 = ...;
final Spinner spinner2 = ...;
spinner1.setAdapter(new ArrayAdapter(mCountries);
spinner1.setOnItemSelectedListener( new OnItemSelectedListener() {
void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Country country = (Country) parent.getAdapter().getItem(position);
spinner2.setAdapter(new ArrayAdapter(country.getStates());
}
void onNothingSelected(AdapterView<?> parent) {
spinner2.setAdapter(null);
}
});
....
}

Categories