2015년 9월 12일 토요일

DB 사용하기

MyDBOpenHelper.java

public class MyDBOpenHelper extends SQLiteOpenHelper {

 private static final String DATABASE_NAME = "your_db_name";
 private static final int DATABASE_VERSION = 2;
 
 public static final String TABLE_NAME = "yout_table_name";
 
 public static final String ID = "id";
 public static final String VALUE = "value";
 
 
 public MyDBOpenHelper(Context context) {
  super(context, DATABASE_NAME, null, DATABASE_VERSION);
 }

 @Override
 public void onCreate(SQLiteDatabase db) {
  db.execSQL("CREATE TABLE dbTable (" + ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + VALUE + " TEXT);");
 }

 @Override
 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  db.execSQL("DROP TABLE IF EXISTS dbTable");
  onCreate(db);
 }
}



DBActivity.java

public class DBActivity extends FragmentActivity implements DbAddDialogListener {
 MyDBOpenHelper myDBOpenHelper;
 SQLiteDatabase sqdb;

 ListView listView;
 DbAddEditDialog addEditDialog;
 FragmentManager fm;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  requestWindowFeature(Window.FEATURE_NO_TITLE);
  setContentView(R.layout.db_activity_layout);

  addEditDialog = new DbAddEditDialog();
  addEditDialog.setListener(this);
  fm = ((FragmentActivity)this).getSupportFragmentManager();

  myDBOpenHelper = new MyDBOpenHelper(this);
  sqdb = myDBOpenHelper.getWritableDatabase();

  updateList();

  Button addBtn = (Button)findViewById(R.id.addBtn);
  addBtn.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
    try {
     addEditDialog.setMsg("");
     addEditDialog.setDbId(null);
     addEditDialog.show(fm, null);
    } 
    catch (ClassCastException e) { }
   }
  });
 }

 private void updateList() {
  List<MyItem> list = new ArrayList<MyItem>();

  Cursor c = sqdb.query(MyDBOpenHelper.TABLE_NAME, 
    new String[] {MyDBOpenHelper.ID, MyDBOpenHelper.VALUE}, 
    null, null,null,null,null);

  while (c.moveToNext()) {
   int id = c.getInt(c.getColumnIndex(MyDBOpenHelper.ID));
   String value = c.getString(c.getColumnIndex(MyDBOpenHelper.VALUE));
   
   MyItem item = new MyItem();
   item.setId(id);
   item.setTitle(value);
   list.add(item);
  }
  c.close();
  
  CustomAdapter adapter = new CustomAdapter(this, R.layout.db_list_view_item, list);
  listView = (ListView)findViewById(R.id.listView1);
  listView.setAdapter(adapter);
 }

 class MyItem {
  private Integer id;
  private String title;
  public Integer getId() { return id; }
  public String getTitle() { return title; }
  public void setId(Integer id) { this.id = id; }
  public void setTitle(String title) { this.title = title; }
 }

 class CustomAdapter extends ArrayAdapter<MyItem> {
  private List<MyItem> items;
  private int layoutResource;
  public CustomAdapter(Context context, int layoutResource, List<MyItem> items) {
   super(context, layoutResource, items);
   this.items =  items;
   this.layoutResource = layoutResource;
  }

  @Override        
  public View getView(int position, View convertView, ViewGroup parent) {
   if (convertView == null) {
    LayoutInflater layoutInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    convertView = layoutInflater.inflate(layoutResource, null);
   }

   final MyItem myItem = items.get(position);                 
   if (myItem != null) {
    TextView title = (TextView)convertView.findViewById(R.id.textView1);                         
    if (title != null){                             
     title.setText(myItem.getTitle());           
    }
    Button editBtn = (Button)convertView.findViewById(R.id.editBtn);
    editBtn.setOnClickListener(new OnClickListener() {
     @Override
     public void onClick(View v) {
      addEditDialog.setMsg(myItem.getTitle());
      addEditDialog.setDbId(myItem.getId());
      addEditDialog.show(fm, null);
     }
    });
    Button deleteBtn = (Button)convertView.findViewById(R.id.deleteBtn);
    deleteBtn.setOnClickListener(new OnClickListener() {
     @Override
     public void onClick(View v) {
      sqdb.delete(MyDBOpenHelper.TABLE_NAME, MyDBOpenHelper.ID + " = ?", new String[] { String.valueOf(myItem.getId()) });
      updateList();
     }
    });
   }                 
   return convertView;         
  } 
 }

 @Override
 public void okClicked(String str, Integer id) {
  if (id == null) {
   ContentValues values = new ContentValues();  
   values.put(MyDBOpenHelper.VALUE, str);  
   sqdb.insert(MyDBOpenHelper.TABLE_NAME, null, values);  
  }
  else {
   ContentValues values = new ContentValues();  
   values.put(MyDBOpenHelper.ID, id);  
   values.put(MyDBOpenHelper.VALUE, str);  
   sqdb.update(MyDBOpenHelper.TABLE_NAME, values, MyDBOpenHelper.ID + " = ?", new String[] { String.valueOf(id) });
  }
  updateList();
 }
}



DbAddEditDialog.java

public class DbAddEditDialog extends DialogFragment {
 String msg;
 Integer dbId; 
 DbAddDialogListener listener;
 
 public Integer getDbId() { return dbId; }
 public String getMsg() { return msg; }
 public void setDbId(Integer dbId) { this.dbId = dbId; }
 public void setMsg(String msg) { this.msg = msg; }
 public void setListener(DbAddDialogListener listener) { this.listener = listener; }
 
 public interface DbAddDialogListener {
  public void okClicked(String str, Integer id);
 }
 
 @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        LayoutInflater li = LayoutInflater.from(getActivity());
  View promptsView = li.inflate(R.layout.dialog_layout, null);

  AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
  alertDialogBuilder.setView(promptsView);

  if (dbId != null) {
   TextView textView = (TextView)promptsView.findViewById(R.id.textView1);
   textView.setText("edit the db data");
  }
  
  final EditText userInput = (EditText) promptsView.findViewById(R.id.editTextDialogUserInput);
  userInput.setText(msg);
  alertDialogBuilder
   .setCancelable(false)
   .setPositiveButton("OK",new OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
     listener.okClicked(userInput.getText().toString(), dbId);
    }
   })
   .setNegativeButton("Cancel",
     new DialogInterface.OnClickListener() {
       public void onClick(DialogInterface dialog,int id) {
        dialog.cancel();
       }
     });

  AlertDialog alertDialog = alertDialogBuilder.create();

  return alertDialog;
    }
}



dialog_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout_root"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:padding="10dp" >
 
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Insert into DB"
        android:textAppearance="?android:attr/textAppearanceLarge" />
 
    <EditText
        android:id="@+id/editTextDialogUserInput"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
 
        <requestFocus />
 
    </EditText>
 
</LinearLayout>



db_activity_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/header" >

        <Button
            android:id="@+id/addBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:text="Add" />

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@+id/addBtn"
            android:layout_alignBottom="@+id/addBtn"
            android:layout_centerHorizontal="true"
            android:text="Database" />
        
    </RelativeLayout>

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

</LinearLayout>

댓글 없음:

댓글 쓰기