마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

Hashmap ArrayList 등록 및 제거 질문 좀 드릴게요..

+1 추천

서버에서 받아온 값을 food1세팅하고 JOrder라는 객체를 만들어 오브젝트 형테로 저장하고 만들어나가다가 저번에 좋은 힌트를 얻어 값이 중복되는 것을 방지하고자 Hashmap 형태로 바꿔볼려고 하는데 너무 헷갈리네요..오브젝트로 하니까..

food1_ListAdapter에서 체크박스에 체크가 되면 hashmap에 담아두고 메뉴를 키값으로 두면 해제시에는 그키를 제거 하고, food1에 있는 arrayList에 가져와서 인텐트에 담아서 Pay로 보내고 싶습니다.. 

어떤방식으로 담고 불러와야하는지 좀 알려주시면 감사하겠습니다...힌트나 아님 좋은 예제 라도 있으면 알려주심 감사할게요...

지금 몇일 째 꼬박 이부분 해결에 매달리고 있습니다.. 도와주십시요 ㅠ 

public class JOrder implements Serializable{

	String menu;
	int amount;
	int price;
	
	boolean choice = false;
	
	public String getMenu() {
		return menu; 
	}
	public void setMenu(String menu) {
		this.menu = menu;
	}
	
	public int getAmount() {
		return amount;
	}
	public void setAmount(int amount) {
		this.amount = amount;
	}
	public int getPrice() {
		return price;
	}
	public void setPrice(int price) {
		this.price = price;
	}
	
	public boolean isChoice() {
		return choice;
	}
	public void setChoice(boolean choice) {
		this.choice = choice;
	}

}
----------------------------------------------------food1_ListAdapter-------------------

public class Food1_ListAdapter extends BaseAdapter {

	Activity context;
	ArrayList<JOrder> arrList;
	ArrayList<HashMap<JOrder,JOrder>> arrList2;
	HashMap<JOrder,JOrder> map;
	JOrder jOrder;
	int layout;

	public Food1_ListAdapter(Activity context, ArrayList<JOrder> arrList,
			int layout) {
		this.context = context;
		this.arrList = arrList;
		this.layout = layout;
	}

	public int getCount() {
		// TODO Auto-generated method stub
		return arrList.size();
	}

	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return arrList.get(position);
	}

	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	public View getView(final int position, View convertView, ViewGroup parent) {
		View v = null;
		if (convertView == null) {
			v = context.getLayoutInflater().inflate(layout, null);
		} else {
			v = convertView;
		}

		TextView food1_list_menu = (TextView) v
				.findViewById(R.id.food1_list_menu);
		final EditText food1_list_amount = (EditText) v
				.findViewById(R.id.food1_list_amount);
		TextView food1_list_price = (TextView) v
				.findViewById(R.id.food1_list_price);
		final CheckBox food1_list_choice = (CheckBox) v
				.findViewById(R.id.food1_list_choice);

		jOrder = arrList.get(position);
		
		food1_list_choice
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {

					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						
						if (food1_list_choice.isChecked()) {

							jOrder.setChoice(true);

							map.put(jOrder);
							arrList.add(jOrder);
							
							Toast.makeText(context, "체크되었습니다",
									Toast.LENGTH_SHORT).show();
						} else {					
							jOrder.setChoice(false);
							
							map.remove(jOrder.getMenu());
							
							Toast.makeText(context, "체크가 해제되었습니다.",
									Toast.LENGTH_SHORT).show();
						}

					}
				});
		
		food1_list_amount.addTextChangedListener(new TextWatcher() {
			
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				jOrder.setAmount(Integer.parseInt(food1_list_amount.getText().toString()));
				
				arrList.add(jOrder); 
				
			}
			
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				
				
			}
			
			public void afterTextChanged(Editable s) {
				 
								
			}
		});
		
		jOrder = arrList.get(position); 
		
		food1_list_menu.setText(jOrder.getMenu());
//		food1_list_amount.setText("");
		food1_list_price.setText("" + jOrder.getPrice());

		return v;
	}

}
--------------------------------------------------------Food1----------------------------

public class Food1 extends Activity implements OnClickListener {

	Button order_btn;
	ArrayList<JOrder> jOrder_lit;
//	ArrayList<HashMap<String, JOrder>> jOrder_lit2;
	ListView food1_list;
	JOrder jorder = new JOrder();
	String test = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.food1);

		food1_list = (ListView) findViewById(R.id.food1_list);

		onFood1List();

		order_btn = (Button) findViewById(R.id.order_food1_btn);

		order_btn.setOnClickListener(this);

	}

	public void onClick(View v) {

		if (v.getId() == R.id.order_food1_btn) {

//			HashMap<String, JOrder> map = new HashMap<String, JOrder>();
			
			Food1_ListAdapter food1 = new Food1_ListAdapter(getParent(),
					jOrder_lit, R.id.food1_list);
			ArrayList<JOrder> jOrder_lit = new ArrayList<JOrder>();
			JOrder jorder = new JOrder();
			for (int i = 0; i < food1.arrList.size(); i++) {
				jorder = food1.arrList.get(i);
				
				if (jorder.isChoice() == true) {
					
//					jOrder_lit2.add(map);
					jOrder_lit.add(jorder);
				}
			}

				Intent order_intent = new Intent(this, Pay.class);
				order_intent.putExtra("order_list", jOrder_lit);
				startActivity(order_intent);
			}
		}

	private void onFood1List() {
		ServerRequest request = new ServerRequest();

		Map<String, String> map = new HashMap<String, String>();
		request.Order_List(map, handler, 100);
	}

	Handler handler = new Handler() {

		public void handleMessage(Message msg) {
			super.handleMessage(msg);

			if (msg.what == 100) {
				jOrder_lit = (ArrayList<JOrder>) msg.obj;

				food1_list.setAdapter(new Food1_ListAdapter(Food1.this,
						jOrder_lit, R.layout.food1_layout));

				food1_list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

			} else {
				Toast.makeText(getApplicationContext(), "fail",
						Toast.LENGTH_SHORT).show();
			}
		}
	};

}

 

 

 

 

익명사용자 님이 2015년 11월 27일 질문

1개의 답변

0 추천
 
채택된 답변
또 제가 답변을 ㅋㅋ 정리 합시다.

arraylist 는 리스트에서 보여지는 용도로만 사용

hashmap 은 체크가 된 아이템만 저장하는데 사용

이상태에서 check 리스너에서 해당 상품의 키값에 따라 계속적으로 put 을 합니다.

물론 EditText 에도 리스너를 달아서 check 가 true 인 경우에 계속적으로 해당 키에 put 을 해주면 되겠죠

그리고 체크가 해제 되거나 EditText 에 0 이라는 숫자를 입력하면 hash 맵의 키를 제거합니다.

자 이러면 순수하게 0이 아니거나 체크가 된 상품들만 hashmap 에 저장이 되겠죠?

intent 로 전달할 arraylist 를  hashmap 을 루프 돌리면서 값을 채워줍니다.

map.put("key", value); 요런식으로 값들이 들어가 있다고 가정했을때

Object keys = map.keySet().toArray();

for(int cnt = 0; cnt < map.keySet().size(); cnt++) {
    Log.e("", keys[cnt] + "/" + map.get(keys[cnt]));  

    // 키/밸류 값을 새로운 arraylist 에 채워주면 되겠죠
}
쉽죵? hashmap 의 데이터를 serializable 가능한 데이터로 다시 변환해서 intent 로 보내는게 핵심입니다.
라쎄린드 (25,460 포인트) 님이 2015년 11월 27일 답변
여러번 감사합니다. 미니알리미님 덕에 많이 알아 가는거 같습니다.
이해는 대충 가는데 제가 put을 잘못했는지.. 이런식으로 put하면 앱이죽네요ㅠ
map.put(jOrder.getMenu(),jOrder);
혹시 put 해줄 때 다른방법으로 해줘야하나요??
아니요..맞는데요...제가 해보니 잘되는데..
음; 이상하네요 다시한번 시도 해볼게요 ㅎㅎ.. 감사해요
...