2017-02-11 1 views
0

내 코드에 두 가지 오류가 있습니다. 해결 방법을 모르겠습니다.통화가 들어있는 문자열을 추가 할 수 없습니다.

표시하고 해결 방법을 알려주십시오. 내가하지만, 다른 오류가 표시 될 수 있습니다로를 해결하기 위해 노력

public class Food { 

String price = null; 
String name = null; 
boolean selected = false; 

public Food(String price, String name, boolean selected) { 
    super(); 
    this.price = price; 
    this.name = name; 
    this.selected = selected; 
} 

public String getPrice() { 
    return price; 
} 
public void setPrice(String price) { 
    this.price = price; 
} 
public String getName() { 
    return name; 
} 
public void setName(String name) { 
    this.name = name; 
} 

public boolean isSelected() { 
    return selected; 
} 
public void setSelected(boolean selected) { 
    this.selected = selected; 
} 

}

public class MainActivity extends Activity { 

    MyCustomAdapter dataAdapter = null; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     //Generate list View from ArrayList 
     displayListView(); 
     checkButtonClick(); 
    } 

    private void displayListView() { 

     //Array list of foods 
     ArrayList<Food> foodList = new ArrayList<Food>(); 
     Food food = new Food("15 SAR", "Chicken Meal", false); 
     foodList.add(food); 
     food = new Food("10 SAR", "Sliced Chicken", false); 
     foodList.add(food); 
     food = new Food("20 SAR", "Sandwich Chicken", false); 
     foodList.add(food); 
     food = new Food("10 SAR", "Hot Chicken", false); 
     foodList.add(food); 
     food = new Food("6 SAR", "Grilled potatoes", false); 
     foodList.add(food); 
     food = new Food("2 SAR", "Pepsi", false); 
     foodList.add(food); 
     food = new Food("17 SAR", "Fish Meal", false); 
     foodList.add(food); 

     //create an ArrayAdaptar from the String Array 
     dataAdapter = new MyCustomAdapter(this, 
       R.layout.food_info, foodList); 
     ListView listView = (ListView) findViewById(R.id.listView1); 
     // Assign adapter to ListView 
     listView.setAdapter(dataAdapter); 

    } 

    private class MyCustomAdapter extends ArrayAdapter<Food> { 

     private ArrayList<Food> foodList; 

     public MyCustomAdapter(Context context, int textViewResourceId, 
           ArrayList<Food> foodList) { 
      super(context, textViewResourceId, foodList); 
      this.foodList = new ArrayList<Food>(); 
      this.foodList.addAll(foodList); 

     } 

     private class ViewHolder { 
      TextView price; 
      CheckBox name; 
     } 

     @Override 
     public View getView(int position, View convertView, ViewGroup parent) { 

      ViewHolder holder = null; 
      Log.v("ConvertView", String.valueOf(position)); 

      if (convertView == null) { 
       LayoutInflater vi = (LayoutInflater) getSystemService(
         Context.LAYOUT_INFLATER_SERVICE); 
       convertView = vi.inflate(R.layout.food_info, null); 

       holder = new ViewHolder(); 
       holder.price = (TextView) convertView.findViewById(R.id.price); 
       holder.name = (CheckBox) convertView.findViewById(R.id.checkBox); 
       convertView.setTag(holder); 

      } else { 
       holder = (ViewHolder) convertView.getTag(); 
      } 

      Food food = foodList.get(position); 
      holder.price.setText(" (" + food.getPrice() + ")"); 
      holder.name.setText(food.getName()); 
      holder.name.setChecked(food.isSelected()); 

      holder.name.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 
       @Override 
       public void onCheckedChanged(CompoundButton compoundButton, boolean b) { 
        food.setSelected(b); 
       } 
      }); 
      holder.name.setTag(food); 

      return convertView; 

     } 

    } 

    private void checkButtonClick() { 

     Button myButton = (Button) findViewById(R.id.findSelected); 
     myButton.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 

       setContentView(R.layout.invoic_page); 
       int totalPrice = 0; 
       for (Food f : foodList) { 
        if (f.isSelected) { 
         totalPrice += f.getPrice(); 
        } 

        //totalPrice variable now has the total of all selected items 
       } 
      } 

     }); 
    } 
} 

: 여기

는 내 응용 프로그램의 코드입니다 코드의 다른 장소 그래서 나는 최고의 솔루션을 원한다.

+0

만들 변수 최종 초에 사용 정수 .parseInt (yourstring); –

+0

깜박이는 텍스트 커서를 오류 위에 놓고 ALT + ENTER를 누르십시오 -> ENTER – Linxy

+1

이것은 다중 통화 시스템입니까? 그렇지 않은 경우 가격에 문자열을 사용하고 각 문자열에서 통화를 반복 할 필요가 없습니다. – weston

답변

-1

totalPriceint하고 Food 모델 클래스에 priceString입니다. 당신이 필요로하는, 두 번째 오류의 경우

// Make this final. 
final Food food = foodList.get(position); 
holder.name.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 
     @Override 
     public void onCheckedChanged(CompoundButton compoundButton, boolean b) { 
      food.setSelected(b); 
     } 
}); 

: 그래서 당신은 당신이 food 변수 마지막을해야 필요가

for (Food f : foodList) { 
      if (f.isSelected) { 
       totalPrice += Integer.parseInt(f.getPrice()); 
      } 

      //totalPrice variable now has the total of all selected items 
     } 

final Food food = foodList.get(position); 첫 번째 오류의 경우 최종

+1

가격에 무엇이 있었는지 보셨습니까? – weston

-1

를 정의 할 필요가 convet 필요 문자열 값을 정수로 변환 :

for (Food f : foodList) { 
    if (f.isSelected) { 
    totalPrice += Integer.valueOf(f.getPrice()); 
    } 
} 

그러나 음식 클래스 또는 BigDecimal의 가격으로 price을 정수 또는 BigInteger 변수로 변경하는 것이 좋습니다.


UPDATE

결코 당신의 가격 값에 통화를 저장합니다. 대신 통화 이름과 같은 새 변수를 추가 할 수 있습니다. 이식성과 미래의 버그없는 코드를 위해 저장하지 마십시오.

+0

현재 가격에 무엇이 있었는지 보셨습니까? – weston

+0

놀라운 오류가 발생했습니다 :) ...하지만 여전히 기호를 해결할 수 없습니다. foodList 및 isSelected : for (Food f : foodList) {if (f.isSelected) { – Sahora

+0

실행 해 보셨습니까? – weston

0

두 번째 돈은 String입니다. "1 SAR""2 SAR"을 단순히 추가하고 "3 SAR"을 얻을 수는 없습니다. 이 단일 통화 시스템 인 경우

, 사방 " SAR"를 추가하지 않고 값을 저장하기 위해 문자열을 사용하지 않는, 하나 int s 또는 long의와 예를 들어, 통화의 가장 낮은 부문을 저장 할랄.개인적으로

나는 것 : 이것은 다중 통화 시스템이 통화에 대한 클래스를 만드는 것입니다, 특히, 또는

String forDisplay = String.format("%.2f SAR", totalHalas/100); 

:

new Food("15 SAR", "Chicken Meal", false);은 사용자에게 가격을 표시하기 위해 다음

new Food(1500, "Chicken Meal", false);된다 이를 위해 라이브러리를 사용하십시오 : Joda Money.

하지만 당신은 또한 자신의 롤 수 있습니다

public class Money { 
    private final String currency; 
    private final long value; 
    private final int dp; 

    public Money(long value, int dp, String currency){ 
     this.value = value; 
     this.dp = dp; 
     this.currency = currency; 
    } 

    //optional helper factory method 
    public static Money sar(long halas){ 
     return new Money(halas, 2, "SAR"); 
    } 

    public Money add(Money other){ 
     if(!other.currency.equals(currency)) 
      throw new RuntimeException("Can't add different currencies"); 
     if(!other.dp.equals(dp)) 
      throw new RuntimeException("The decimal places do not match"); 
     return new Money(value + other.value, dp, currency); 
    } 

    public String toString(){ 
     return String.format("%."+dp+"f %s", value/Math.pow(10,dp), currency); 
    } 
} 

사용 예제 :

System.out.println(new Money(1500,2,"SAR").add(new Money(623,2,"SAR"))); 
//or: 
System.out.println(Money.sar(1500).add(Money.sar(623))); 

Outputs : 첫 번째 이미지에서

21.23 SAR 
관련 문제