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

글을 수정했는데 원본글과 수정한 글 두개가 목록에 떠요ㅠㅠ [closed]

0 추천
public class ListviewMain extends Activity implements OnClickListener,
  OnItemClickListener, OnItemLongClickListener {
 private final static String TB_NAME = "test";
 public static final String DB_NAME = "test.db";
 public static final int DB_VERSION = 1;

 public static final String KEY_ID = "_id";
 public static final String TITLE = "title";
 public static final String CONTENTS = "contents";
 EditText editText1;
 Button Addbtn;

 SQLiteDatabase db;
 DBManagerHandler handler;
 Button Searchbtn;
 DBHelper dbhelper;
 SimpleCursorAdapter adapter1 = null;

 static ArrayList<String> arrayList;
 static ArrayAdapter<String> adapter;
 ListView listView;
 ClipboardManager cm;
 Intent intent;

 /* basic_info 테이블 생성 쿼리 */
 private static final String Q_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS "
   + TB_NAME + " (_id INTEGER PRIMARY KEY AUTOINCREMENT " + ","
   + "title TEXT " + "," + "contents TEXT" + ");";

 private final String Q_GET_LIST = "SELECT * FROM test"
   + " ORDER BY _id ASC";

 BroadcastReceiver receiver;
 Intent keyboard;

 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.listview_main);

  try {
   keyboard = getIntent();
   if (keyboard.hasExtra("keyboard")) { // 키보드에 의해서 어플이 실행됬으면 true를 반환
             // 아니면false
    String temp = keyboard.getStringExtra("keyboard"); //
    Log.i("ggggg", temp);
   }
  } catch (Exception e) {
   e.setStackTrace(null);
  }
  Searchbtn = (Button) findViewById(R.id.Searchbtn);
  Addbtn = (Button) findViewById(R.id.addbtn);

  arrayList = new ArrayList<String>();
  adapter = new ArrayAdapter<String>(ListviewMain.this,
    android.R.layout.simple_list_item_2, arrayList);

  listView = (ListView) findViewById(R.id.listView1);
  listView.setAdapter(adapter);

  // 기본적인 서비스 만들어보기
  Log.i("TAG", "Controller Activity - startService()");
  Intent myserviceintent = new Intent(this, ServiceApp.class);

  startService(myserviceintent);

  // 버튼들을 implement로 사용하기위해
  Addbtn.setOnClickListener(this);
  Searchbtn.setOnClickListener(this);

  listView.setOnItemClickListener(this);
  /* 리스트뷰 롱클릭시 삭제 다이얼로그 */
  listView.setOnItemLongClickListener(this);

 }// 수정 한뒤

 protected void onResume() {
  super.onResume();
  getDbData();
 }

 public void onBackPressed() {
  Log.i("onBackPressedonBackPressedonBackPressed", "onBackPressed ");
  // Do some stuff
  finish();
  super.onBackPressed();
 }

 private void getDbData() {
  SQLiteDatabase db = null;
  if (db == null) {
   db = openOrCreateDatabase("test.db",
     SQLiteDatabase.CREATE_IF_NECESSARY, null);
  }

  // checkTableIsCreated(db); //db에 solo_info 테이블이 있는지 확인
  db.execSQL(Q_CREATE_TABLE);
  Cursor c = db.rawQuery(Q_GET_LIST, null);
  // startManagingCursor(c);

  listView = (ListView) findViewById(R.id.listView1);
  adapter1 = new SimpleCursorAdapter(getApplicationContext(),
    android.R.layout.simple_list_item_2, c, new String[] { "title",
      "contents" }, new int[] { android.R.id.text1,
      android.R.id.text2 });
  listView.setAdapter(adapter1);

  if (db != null) {
   db.close();
  }
 }

 public static void copytext(String copyContents) {
  Log.i("copytext", "copyContents " + copyContents);

  arrayList.add("_" + copyContents); // 이렇게 보여주기위한문.
  adapter.notifyDataSetChanged();// 어뎁터에게 초기화 됨을 알리는 문

 }

 protected void onActivityResult(int requestCode, int resultCode, Intent Data) {
  super.onActivityResult(requestCode, resultCode, Data);
  String tile = "null";
  String contents = "null";
  Intent intent = Data;
  // if (keyboard.hasExtra("keyboard")) { // 키보드에 의해서 어플이 실행됬으면 true를 반환
  // // 아니면false
  // String temp = keyboard.getStringExtra("keyboard"); //
  // Log.i("ggggg", temp);
  // }
  try {
   tile = intent.getStringExtra("TitleEditStr").toString(); // 제목의 글을 가져오는 문    
   contents = intent.getStringExtra("ContentEditStr").toString(); // 내용의 글을 가져오는 문
                   
  } catch (Exception e) {
   Log.i("여기는 에러", "에러");
   
  }

  switch (requestCode) {
  case 0:
   arrayList.add(tile + "_" + contents); // 이렇게 보여주기위한문.
   adapter.notifyDataSetChanged();// 어뎁터에게 초기화 됨을 알리는 문
   break;
  case 1:
   break;
  default:
   break;
  }

 }

 @Override
 public void onClick(View v) {
  // TODO Auto-generated method stub
  int getId = v.getId();
  switch (getId) {
  case R.id.addbtn:
   intent = new Intent(ListviewMain.this, EditClass.class);

   startActivityForResult(intent, 0); // 에디트클래스의 엑티비티에서 다시
            // 돌아옴으로 포리조트함수사용

   break;
  case R.id.Searchbtn:
   Intent intent = new Intent(ListviewMain.this, ServiceApp.class);

   stopService(intent);
   break;
  default:
   break;
  }
 }

 public void onItemClick(AdapterView<?> parent, View v, int position, long id) {

  // Get the cursor, positioned to the corresponding row in the result set
  Cursor cursor = (Cursor) listView.getItemAtPosition(position);

  // display the selected country
  String tempTitle = cursor.getString(cursor
    .getColumnIndexOrThrow(DBHelper.TITLE));
  Toast.makeText(getApplicationContext(), tempTitle, Toast.LENGTH_SHORT)
    .show();

  String Contents = cursor.getString(cursor
    .getColumnIndexOrThrow(DBHelper.CONTENTS));
  Log.i(tempTitle, Contents);
  // starts a new Intent to update/delete a Country
  // pass in row Id to create the Content URI for a single row
  Intent countryEdit = new Intent(getBaseContext(), SubActivity.class);
  Bundle bundle = new Bundle();
  bundle.putString("mode", "update");
  bundle.putString("tempContents", Contents);
  bundle.putString("tempTitle", tempTitle);
  countryEdit.putExtras(bundle);
  startActivity(countryEdit);

 }

글 수정 코드가 있는곳은 맨 마지막부분 onItemClick() 이부분이에요.

목록에서 글을 누르면 수정을 할 수 있는데 수정을 하고 나면, 수정전 글과 수정 후 글 두개가 목록에 떠요ㅠㅠ

수정하면 수정후 글만 목록에 떠야하는데 어떻게 하면 될까요?ㅜㅜ

질문을 종료한 이유: ㅜㅜ
초보 안드롱 (480 포인트) 님이 2014년 6월 2일 질문
초보 안드롱님이 2014년 6월 5일 closed

1개의 답변

+1 추천
 
채택된 답변
onActivityResult switch 문에 arrayList.add 가 문제인거같은데요 수정할 데이터 인덱스를 가지고 치환해야될거 같습니다
mamondebaltob (32,750 포인트) 님이 2014년 6월 2일 답변
초보 안드롱님이 2014년 6월 3일 채택됨
아 저 result문은 코드에 아무 영향을 안주더라구요 ㅜㅜ 오히려 getdbdata쪽만 실행되는 거라서 지웠습니다 ㅜㅜ 수정 후에 수정 전 문장이 바뀌는 게 안된다면 삭제가 되게 하고 싶은데 delete를 삽입하면 인덱스가 이상해서인지 오류가 뜨더라구요.. 삭제하는 방향으로 방법이 없을까요 ㅜㅜ
아 onResume 에서 DB 호출해 다시 긁어오는 거군요, 근데 이상한게 onItemClick 콜백 부분 보면 수정 액티비티 부를때 타이틀이랑 내용만 보내는거 같은데 수정 액티비티에서 DB 쿼리를 직접 날리는 구조 아닌가요?
코드 해놓고 보니까 수정이라기 보다는 새로 추가 기능이 된것같아요ㅜㅜ 수정이 되는 코드로 바꾸던지 이전 데이터를 삭제하던지 하나를 선택해야 될것같은데 둘다 막막하네요 ㅜㅜ 일단 삭제를 하려고 delete를 넣으면 에러가 나고 ㅜㅜㅜㅜ 게다가 디버그 창에 에러도 안뜨네요..android runtime밖에 안떠요 ㅜㅜ
계속 분석해보니까 코드를 실행할때마다 테이블이 새로 생기면서 새로 id 가 받아지는것같네요 ㅜㅜ 그래서 수정이 아니라 추가가 되는건가봐요.. 버튼을 만드는 방법밖에는 없는 것같아요 ㅜㅜㅜㅜ
...