Spinner converter android - android

I am having some confusion with the spinner class in android. What I want to is make a converter, where the user picks a unit they want to convert, then in the second spinner pick the output unit. Ex Spinner 1: Yard² to Spinner 2: Feet². Im not sure how to set it up, so If yard² and feet² is selected then do this calculation. Here is the code I have so far:
private void UnitBegin_ItemSelected (object sender, AdapterView.ItemSelectedEventArgs e)
{
Spinner UnitBegin = (Spinner)sender;
string ubget = UnitBegin.SelectedItem.ToString();
if (ubget == "Yard²")
{
}
}

You can accomplish that by declaring private globar Spinners, like this:
private Spinner spinner1;
private Spinner spinner2;
// your code
// now just use the globally declared spinners (spinner1 and spinner2) in your code
private void UnitBegin_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e)
{
string selected1 = spinner1.SelectedItem.ToString();
string selected2 = spinner2.SelectedItem.ToString();
if(selected1.Equals("Yard²"))
{
if (selected2.Equals("m²"))
{
//do calculation
}
else if (selected2.Equals("unit²"))
{
//do calculation
}
else if (selected2.Equals("otherunit²"))
{
//do calculation
}
else
{
//ERROR
}
}
if (selected1.Equals("m²"))
{
if (selected2.Equals("Yard²"))
{
//do calculation
}
else if (selected2.Equals("unit²"))
{
//do calculation
}
else if (selected2.Equals("otherunit²"))
{
//do calculation
}
else
{
//ERROR
}
}
//repeat for all the possible units
}
But I would advise you to do something like this:
private Spinner spinner1;
private Spinner spinner2;
private float unit1;
private float unit2;
// your code
// now just use the globally declared spinners (spinner1 and spinner2) in your code
private void UnitBegin_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e)
{
string selected1 = spinner1.SelectedItem.ToString();
if(selected1.Equals("Yard²"))
{
unit1 = 0.5 //let's say this is the multiplier from Yard² to m² :)
}
//repeat for all the possible units
}
private void UnitEnd_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e)
{
string selected2 = spinner2.SelectedItem.ToString();
if(selected2.Equals("UNIT²"))
{
unit2 = 0.7 //let's say this is the multiplier from UNIT² to m² :)
}
//repeat for all the possible units
}
And in the method that calculates the result to display:
float result = value*unit1; //and you get the value in the "default" unit
float finalResult = result*unit2; //and you get the value converted to the final unit
return finalResult; //return the final converted value

Related

Sorting ArrayList of JSONObjects by a double doesn't work

I'm currently creating an Android app for school but still want to give my best.
I'm pretty new to Android development and coding in general. The app is supposed to be a stock market game. (Btw, I'm German, so there might be some German variables)
So I want to sort my RecyclerView containing shares. It works alphabetically but not by worth.
I can guarantee that the name "worth" of the double in the JSONObject is correct. What am I doing wrong?
public class CompanyAdapter extends RecyclerView.Adapter<CompanyAdapter.viewHolder> implements Filterable {
private CustomFilter filter;
private ArrayList<JSONObject> jObjList;
private final String keyName;
private final String keyWorth;
private final String keyChange;
public final static int SORT_ALPHABETICALLY = 0;
public final static int SORT_ALPHABETICALLY_REVERSE = 1;
public final static int SORT_BY_WORTH = 2;
public final static int SORT_BY_WORTH_REVERSE = 3;
public CompanyAdapter(Context context, ArrayList<JSONObject> jObjList) {
this.jObjList = jObjList;
Context c = context;
keyName = c.getResources().getString(R.string.nameCompany);
keyWorth = c.getResources().getString(R.string.worthCompany);
keyChange = c.getResources().getString(R.string.changeCompany);
sort(SORT_ALPHABETICALLY);
}
//left out some unnecessary code
public void sort (int sorting) {
if (jObjList.size()>1) {
switch (sorting) {
case SORT_ALPHABETICALLY:
sortAlphabetically();
break;
case SORT_ALPHABETICALLY_REVERSE:
sortAlphabeticallyReverse();
break;
case SORT_BY_WORTH:
sortByWorth();
break;
case SORT_BY_WORTH_REVERSE:
sortByWorthReverse();
break;
}
}
}
private void sortAlphabetically () {
Collections.sort(jObjList, new Comparator<JSONObject>() {
#Override
public int compare(JSONObject j1, JSONObject j2) {
try {
return j1.getString(keyName).compareToIgnoreCase(j2.getString(keyName));
} catch (JSONException e) {
return 0;
}
}
});
}
private void sortAlphabeticallyReverse () {
sortAlphabetically();
Collections.reverse(jObjList);
}
private void sortByWorth () {
Collections.sort(jObjList, new Comparator<JSONObject>() {
#Override
public int compare(JSONObject j1, JSONObject j2) {
try {
return Double.compare(j1.getDouble(keyWorth), j2.getDouble(keyWorth));
} catch (JSONException e) {
Log.e("JSONException", e.getMessage());
return 0;
}
}
});
}
private void sortByWorthReverse () {
sortByWorth();
Collections.reverse(jObjList);
}
}
try to replace
return Double.compare(j1.getDouble(keyWorth), j2.getDouble(keyWorth));
with
System.out.print("VALUE1: "+j1.getDouble(keyWorth));
System.out.print("VALUE2: "+j2.getDouble(keyWorth));
return (int)(j1.getDouble(keyWorth)-j2.getDouble(keyWorth));
as well to make sure and debug the value print it.
and after sortByWorth();
add notifyDataSetChanged();
Have you checked the values of the objects you are comparing within the console?
Since you are reading in the values as a string, perhaps they will not be giving the result you expect.
Furthermore, what operation is the compare function performing?
Replace:
return Double.compare(j1.getDouble(keyWorth), j2.getDouble(keyWorth));
In sortByWorth method, to:
return j1.getDouble(keyWorth).compareTo(j2.getDouble(keyWorth))
Try it..
I forgot the notifyDataSetChanged(). Sorry, that's a stupid error.

How to initialize an edittext with a empty string if i am using a two way databinding and a double as attribute?

I am using the binding in edittext like this
android:text='#={autuacao.equipamento.limite + ""}'
limite is a primitive double.
But when the activity starts, the edittext is initialized as 0.0, and i need it to be empty, how can i do this?
Tynn The answer was almost there but the parameters should be like below, and i didn't need the inverse binder.
#BindingAdapter("android:text")
public static void setText(EditText editText, String value) {
if (value == null) {
return;
}
if (value.equals("0.0")) {
editText.setText("");
} else {
editText.setText(value);
}
}
You could get around it by defining your own binding adapter:
#BindingAdapter("android:text")
public static void setDoubleToText(TextView view, double value) {
String text = "";
if (value != 0) {
text = String.valueOf(value);
}
view.setText(text);
}
Additionally you might also need to define the inverse behavior:
#InverseBindingAdapter(attribute = "android:text")
public static double getDoubleFromText(TextView view) {
try {
return Double.parseDouble(view.getText().toString());
} catch (Exception e) {
return 0.0;
}
}
Kotlin Version:
object DataBindingUtil {
#BindingAdapter("android:text")
#JvmStatic
fun setExtraBehaviorForEditText(editText: EditText, text: String?) {
if (text == "0" || text == "0.0") editText.setText("") else editText.setText(text)
}
}

Display the ArrayList values into TextVitew

Am working on one android project. i stored the getting response in the ArrayList while parsing from the JsonArray. now i want just display the values to required text views.
Here am doing.
public void updateRedemptionRequestDetails(){
//Dismiss dialog
dlgProgress.dismiss();
// Get the status
String status=redemptionRequestDetailsResponse.getStatus();
if(status.equals("success")){
List<RedemptionRequestDetailsResource> redemptionRequestDetailsResource = redemptionRequestDetailsResponse.getData();
if(!redemptionRequestDetailsResource.isEmpty() && redemptionRequestDetailsResource.size()==0 ){
redemptionRequestDetailsResources.addAll(redemptionRequestDetailsResource);
populateRedemptionDetails(redemptionRequestDetailsResources);
}
}else if ( status.equals("failed")) {
//Show toast based on error code
generalMethods.showToastMessage(context,redemptionRequestDetailsResponse.getErrorcode());
}
}
Can anyone please shed some lights on this.how can i get the values in specified string and display them.
Here my model class
public class RedemptionRequestDetailsResource {
private String rdmId;
private String rdmUniqueBatchTrackingId;
private String rdmLoyaltyId;
private String rdmStatus;
private String rdmCashPaymentStatus;
private String rdmProductCode;
public String getRdmId() {
return rdmId;
}
public void setRdmId(String rdmId) {
this.rdmId = rdmId;
}
public String getRdmUniqueBatchTrackingId() {
return rdmUniqueBatchTrackingId;
}
public void setRdmUniqueBatchTrackingId(String rdmUniqueBatchTrackingId) {
this.rdmUniqueBatchTrackingId = rdmUniqueBatchTrackingId;
}
public String getRdmLoyaltyId() {
return rdmLoyaltyId;
}
public void setRdmLoyaltyId(String rdmLoyaltyId) {
this.rdmLoyaltyId = rdmLoyaltyId;
}
public String getRdmStatus() {
return rdmStatus;
}
public void setRdmStatus(String rdmStatus) {
this.rdmStatus = rdmStatus;
}
public String getRdmCashPaymentStatus() {
return rdmCashPaymentStatus;
}
public void setRdmCashPaymentStatus(String rdmCashPaymentStatus) {
this.rdmCashPaymentStatus = rdmCashPaymentStatus;
}
public String getRdmProductCode() {
return rdmProductCode;
}
public void setRdmProductCode(String rdmProductCode) {
this.rdmProductCode = rdmProductCode;
}
}
here my populateRedemptionDetails method
public void populateRedemptionDetails(List<RedemptionRequestDetailsResource> requestDetailsResource) {
List<RedemptionRequestDetailsResource> redemptionRequestDetailsResource = requestDetailsResource;
TextView txtLoyaltyId = (TextView)rootView.findViewById(R.id.txtLoyaltyId);
txtLoyaltyId.setText(redemptionRequestDetailsResource.getRdmLoylatyId());
}
i tried like this but it throwing error.
The if condition is wrong, it will never enter:
if (!redemptionRequestDetailsResource.isEmpty() && redemptionRequestDetailsResource.size()==0) {
}
it should be:
if (!redemptionRequestDetailsResource.isEmpty()) {}
also, small tip, when using equals, you should put the constant on the left side of the call, like this:
"success".equals(status)
this is to prevent NullPointerExceptions

How to make checkboxes work in a live wallpaper Android app?

I have three check boxes in my live wallpaper's settings that I need to figure out how to make them work, I want for example checkbox1 to execute code1, checkbox2 to execute code 2 and the last checkbox to execute code3:
code1:
private void incrementCounter() {
if (mImagesArrayIndex >= mImagesArray.length-10) {
mImagesArrayIndex = mImagesArray.length-10;}
if (mImagesArrayIndex <10) {
mImagesArrayIndex = 10;
code2:
private void incrementCounter() {
if (mImagesArrayIndex >= mImagesArray.length-20) {
mImagesArrayIndex = 0;}
if (mImagesArrayIndex <0) {
mImagesArrayIndex = mImagesArray.length-20;
}
}
code3:
mImagesArrayIndex++;
code3 (goes into code1 and code2), codes1,2,3 are all in CustomWallpaper.java That's all, I have already set my settings layout and it looks like this:
solution:
public void run() {
SharedPreferences myPref = PreferenceManager.getDefaultSharedPreferences( CustomWallpaper.this);
try {
while (true) {
drawFrame();
if (myPref.getBoolean("lwp_o_scroll_lock_key",true))
incrementCounter1();
else
incrementCounter2();
if (myPref.getBoolean("lwp_auto_animation_key",true))
mImagesArrayIndex++;
else
//
// if (myPref.getBoolean("lwp_auto_animation_key",true))
//incrementCounter2();
Thread.sleep(SeekBarPreference.mCurrentValue);
}
} catch (Exception e) {
//
}
}

ConcurrentModificationException when iterating keys of a HashMap

I have a HashMap of Sound objects
private HashMap<Integer, Sound> sounds;
over which I'm trying to iterate to turn off all the sounds. I used
this answer to create an Iterator, but I'm still getting ConcurrentModificationException, though I'm sure there's no other code calling this at the same time.
public synchronized final void stopAll() {
Iterator<Entry<Integer, Sound>> soundEntries = sounds.entrySet().iterator();
while(soundEntries.hasNext())
{
Entry<Integer, Sound> s = soundEntries.next();
s.getValue().myOnCompletionListener = null;
s.getValue().fadeYourself();
}
sounds.clear();
}
In what way should I rewrite this to keep the ConcurrentModificationException from happening?
This is inside my Sound class:
private class soundFader extends AsyncTask<Sound, Void, Void>
{
#Override
protected Void doInBackground(Sound... arg0) {
arg0[0].fadeOut();
return null;
}
}
private void fadeOut()
{
float STEP_DOWN = (float) 0.10;
float currentVol = myVolume;
float targetVol = 0;
if(isSoundEnabled())
{
while(currentVol > targetVol)
{
currentVol -= STEP_DOWN;
mp.setVolume(currentVol, currentVol);
try {
Thread.sleep(70);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
mp.setVolume(0, 0);
onCompletion(mp);
sounds.remove(resource); // THIS LINE WAS MY ERROR
mp.seekTo(0);
nowPlaying = false;
}
public void fadeYourself()
{
soundFader fader = new soundFader();
fader.execute(this);
}
It is not permissible for one thread to modify a Collection while another thread is iterating over it.
If you want to modify only values (not keys) there is no need to use iterators here.
public synchronized final void stopAll() {
for(Sound s: sounds.values())
{
s.myOnCompletionListener = null;
s.fadeYourself();
}
sounds.clear();
}
Ninja edit:
You are removing items from the Collection while iterating. Hence the CoMo exception.
Since you are doing sounds.clear(); towards the end, you can remove the sounds.remove(resource); line.

Categories

Resources