ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • DB SQLite (update)
    안드로이드/학습&강좌 2011. 8. 2. 17:45

    이전 강좌에더 insert 와 select에 대해 설명했고 이번에는 update에 대해서 화면을 구성해 보았다.

    프로젝트 별로 이어 간다 했으니 전 프로젝트를 참고해서 봐주길 바란다.

    이번에 수정한 내용은 목록을 뿌릴때의 ListView Custom Adapter 부분과

    select 방식 , update 쿼리, update UI화면 ActivityResult를 이용한 refresh 처리 등이다.

    먼저 기존 소스의 수정 부분부터 보도록 하자.



    MainApp.java
    package epong.dbsample;
    
    import java.util.ArrayList;
    
    import android.app.Activity;
    import android.content.Context;
    import android.content.Intent;
    import android.database.Cursor;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.view.View.OnClickListener;
    import android.widget.AdapterView;
    import android.widget.ArrayAdapter;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.ListView;
    import android.widget.TextView;
    import android.widget.Toast;
    import android.widget.AdapterView.OnItemClickListener;
    import epong.dto.ScoreDto;
    
    public class MainApp extends Activity implements OnClickListener, OnItemClickListener{
    	
    	private final int ORDER_CODE    = 1124;	// 리퀘스트코드
    	
        DBHandler dbHandler;
        EditText edtName, edtScore;
        ListView list;
        Cursor cursor = null;
        ArrayList arr_list = null;
        String[] arr = null;
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            
            Button btnIns 	 = (Button)findViewById(R.id.btnIns);
            Button btnResult = (Button)findViewById(R.id.btnResult);
            btnIns.setOnClickListener(this);
            btnResult.setOnClickListener(this);
            
            edtName 	= (EditText)findViewById(R.id.edtSang);
            edtScore 	= (EditText)findViewById(R.id.edtScore);
            list 		= (ListView)findViewById(R.id.list);
            list.setOnItemClickListener(this);
        }
        
        @Override
        public void onClick(View v) {
        	dbHandler = DBHandler.open(this);
        	try {
    			if(v.getId() == R.id.btnIns){  //추가
    				if(edtName.getText().toString().equals("")){
    					Toast.makeText(this, "이름 입력", 2000).show();
    					return;
    				}else if(edtScore.getText().toString().equals("")){
    					Toast.makeText(this, "점수 입력", 2000).show();
    					return;
    				}
    				
    				long re = dbHandler.insert(
    						edtName.getText().toString(), 
    						edtScore.getText().toString());
    				if(re == 0){
    					Toast.makeText(this, "추가 실패", 2000).show();
    				}else{
    					Toast.makeText(this, "추가 성공", 2000).show();
    					cursor = dbHandler.selectAll();
    //					arr = new String[cursor.getCount()]; // DTO 클래스형식으로 변경
    					arr_list = new ArrayList();
    //					int count = 0;
    					while(cursor.moveToNext()){
    						String code = cursor.getString(0);
    						String name = cursor.getString(1);
    						String score = cursor.getString(2);
    						ScoreDto dto = new ScoreDto(code, name, score);
    						arr_list.add(dto);
    //						arr[count] = code + " " + sang + " " + price;
    //						count++;
    					}
    					cursor.close();
    					
    					invalidate();				}
    			}else if(v.getId() == R.id.btnResult){ //목록보기
    				cursor = dbHandler.selectAll();
    //				arr = new String[cursor.getCount()];
    				arr_list = new ArrayList();
    //				int count = 0;
    				if(cursor.moveToFirst()){
    					int n_code = cursor.getColumnIndex("code");
    					int n_name = cursor.getColumnIndex("name");
    					int n_score = cursor.getColumnIndex("score");
    					do{
    						String code  = cursor.getString(n_code);
    						String name  = cursor.getString(n_name);
    						String score = cursor.getString(n_score);
    						ScoreDto dto = new ScoreDto(code, name, score);
    						arr_list.add(dto);						
    					}while(cursor.moveToNext());
    					
    					cursor.close();
    					invalidate();
    				}			}
    		} catch (Exception e) {
    			Log.i("disp", "err:" + e);
    		}
        }
        
        private void invalidate(){
    //    	ListAdapter adapter = new ArrayAdapter(this,
    //				android.R.layout.simple_list_item_1, arr_list);
    //		setListAdapter(adapter);
        	EpongAdapter adapter = new EpongAdapter(this, R.layout.list_item, arr_list);
        	list.setAdapter(adapter);
        }
    	@Override
    	public void onItemClick(AdapterView arg0, View arg1, int position, long arg3) {
    		Intent intent = new Intent(this, UpdateApp.class);
    		intent.putExtra("code", arr_list.get(position).getCode());
    		intent.putExtra("name", arr_list.get(position).getName());
    		intent.putExtra("score", arr_list.get(position).getScore());
    		startActivityForResult(intent, ORDER_CODE);
    	}
    	
    	public class EpongAdapter extends ArrayAdapter {
    
    		private ArrayList items;
    
    		public EpongAdapter(Context context, int textViewResourceId,
    				ArrayList items) {
    			super(context, textViewResourceId, items);
    			this.items = items;
    		}
    		@Override
    		public View getView(int _position, View _convertView, ViewGroup _parent) {
    			View view = _convertView;
    			if (view == null) {
    				LayoutInflater vi = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    				view = vi.inflate(R.layout.list_item, null);
    			}
    			
    			//검색목록 타이틀
    			ScoreDto ref   = items.get(_position);
    			if(ref != null){
    				TextView txt_code  = (TextView)view.findViewById(R.id.code);
    				TextView txt_name  = (TextView)view.findViewById(R.id.name);
    				TextView txt_score = (TextView)view.findViewById(R.id.score);
    				if(txt_code != null)
    					txt_code.setText(ref.getCode());
    				if(txt_name != null)
    					txt_name.setText(ref.getName());
    				if(txt_score != null)
    					txt_score.setText(ref.getScore());
    			}
    			return view;
    		}
    	}
    	
    	@Override
    	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    
    		 if (resultCode == RESULT_OK) // 액티비티가 정상적으로 종료되었을 경우
    	        {
    	            if (requestCode == ORDER_CODE) // InformationInput에서 호출한 경우에만 처리합니다.
    	            {
    					Toast.makeText(MainApp.this, "업데이트완료", Toast.LENGTH_SHORT).show();
    					cursor = dbHandler.selectAll();
    		//			arr = new String[cursor.getCount()];
    					arr_list = new ArrayList();
    		//			int count = 0;
    					if(cursor.moveToFirst()){
    						int n_code = cursor.getColumnIndex("code");
    						int n_name = cursor.getColumnIndex("name");
    						int n_score = cursor.getColumnIndex("score");
    						do{
    							String code  = cursor.getString(n_code);
    							String name  = cursor.getString(n_name);
    							String score = cursor.getString(n_score);
    							ScoreDto dto = new ScoreDto(code, name, score);
    							arr_list.add(dto);						
    						}while(cursor.moveToNext());
    						
    						cursor.close();
    						invalidate();
    					}
    	            }
    				
    		}
    		super.onActivityResult(requestCode, resultCode, data);
    	}
        
    }
    

    주석으로 둔 부분이 기존 소스에서 변경된 내용이 되겠다. ListActivity를 사용하다 Activity로 바꿨기 때문에 xml도 바뀌었다.
    ListView의 아이디 부분을 android:id="@+id/list" 로 바꿔주기 바란다.
    새로 추가된 업데이트 화면이다. 기존 UI를 그대로 이용했다. Activity만 따로 불렀을 뿐이다.
    리스트뷰의 아이템을 클릭하면 넘어가게끔 했다.
    이때 ActivityForResult 를 이용해서 성공 실패 여부를 확인해서 반영하게끔 하였다.

    UpdateApp.java
    package epong.dbsample;
    
    import android.app.Activity;
    import android.content.Intent;
    import android.database.Cursor;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;
    
    public class UpdateApp extends Activity implements OnClickListener{
    	EditText edt_name , edt_score;
    	Button  btn_update, btn_cancle;
    	String code ;
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		// TODO Auto-generated method stub
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.update);
    		Intent intent = getIntent();
    		code  = intent.getStringExtra("code");
    		String name  = intent.getStringExtra("name");
    		String score = intent.getStringExtra("score");
    		
    		Log.d("receive", "code : " + code);
    		Log.d("receive", "name : " + name);
    		Log.d("receive", "score : " + score);
    		
    		edt_name  = (EditText)findViewById(R.id.edtName);
    		edt_score = (EditText)findViewById(R.id.edtScore);
    		btn_update = (Button)findViewById(R.id.btnUpdate);
    		btn_update.setOnClickListener(this);
    		btn_cancle = (Button)findViewById(R.id.btnCancle);
    		btn_cancle.setOnClickListener(this);
    		edt_name.setHint(name);
    		edt_score.setHint(score);
    		
    	}
    	@Override
    	public void onClick(View v) {
    		DBHandler dbHandler = new DBHandler(this);
    		switch (v.getId()) {
    		case R.id.btnUpdate:
    			long re = dbHandler.update(code,edt_name.getText().toString(), edt_score.getText().toString());
    			Intent intent = getIntent();
    			if(re == 0){
    				Toast.makeText(UpdateApp.this, "수정 실패", 2000).show();
    				finish();
    			}else{
    				Toast.makeText(UpdateApp.this, "수정 성공", 2000).show();
    				//결과를 반환하여 넘겨준다.
    				setResult(RESULT_OK,intent); 
    				finish(); // 액티비티 종료 
    			}
    			
    			break;
    
    		case R.id.btnCancle:
    			finish();
    			break;
    		}
    		
    	}
    }
    
    

    XML과 DTO클래스 자체는 zip 파일로 같이 첨부하도록 하겠다.
    마지막으로 DBHandler에서 추가된 쿼리이다.
    public long update(String code, String name, String score){
    		ContentValues values = new ContentValues();
    		values.put("name", name);
    		values.put("score", score);
    
    		long result = db.update("tb_score", values, "code = ? ", new String[]{code});
    		return result;
    	}
    

    insert와 다른점은 where 조건문에 대한 내용과 그 조건문에 대입될 파라미터를 String[] 형식으로 넘겨주면 된다는 점이다. 지금은 안드로이드에서 제공하는 쿼리를 이용해서 다 사용해 보고있다. 이전체에 대해 Raw쿼리로 나중에 바꿔보자. 결과화면 바뀐부분은 ListView의 Adapter ListView의 커스텀 레이아웃을 잘 이해 못하시는 분이 계시면 말씀해 주시기 바란다. 커스텀 UI 강의는 많이 있어서 따로 정리하지 않았으나 요청이 생기면 정리하도록 하겠다.

    댓글

COPYRIGHT 2010 EpoNg. ALL RIGHTS RESERVED.