안드로이드 개발 질문/답변
(글 수 45,052)
SQLite를 이용해서 승패를 보여주기만 하는 View Class 와
DB관련 일만 하는 DBScore 라는 Class가 있습니다.
그런데 View Class에서 DBScore에서 리턴되는 String 값을 받지를 못하네요.
int 값들은 return 해준 값을 제대로 받아오는데.. String 값만 제대로 받아오지 못합니다..
혹시나 해서, int 값들을 모조리 String 형식으로 바꾼다음 View Class에서 받아오려니 ... 모두 Null 가리키더군요..
점수보여주는 ScoreView 클래스입니다.
public class ScoreView extends Activity {
private rps_media BGMplay; private ScoreDB score; private TextView UserTextView,WinTextView,LoseTextView,DrawTextView; public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.score_layout); BGMplay=new rps_media(this); BGMplay.PlaySoundTrack(this,5); score=new ScoreDB(); //Create TextView UserTextView=(TextView)this.findViewById(R.id.UserID); WinTextView=(TextView)this.findViewById(R.id.WinID); LoseTextView=(TextView)this.findViewById(R.id.LoseID); DrawTextView=(TextView)this.findViewById(R.id.DrawID); //ReadTextScore(); // Log.i("jjjj", "username value : "+score.getUserName()); UserTextView.setText(score.getUserName()); WinTextView.setText(String.valueOf(score.getWinScore())); LoseTextView.setText(String.valueOf(score.getLoseScore())); DrawTextView.setText(String.valueOf(score.getDrawScore())); } public boolean onKeyDown(int keyCode, KeyEvent event){ if(keyCode==KeyEvent.KEYCODE_BACK){ BGMplay.stopSound(); Intent intent=new Intent(this, com.claner.rps_main.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } return true; } }//End of Class
DB 관련 일만하는 DBScore 입니다.
public class ScoreDB extends Activity { private final static String DB_NAME = "score.db"; private final static String DB_TABLE="rps"; private final static int DB_VERSION=1; private SQLiteDatabase db; private static int w,l,d; private static String namestr; //Initiate public void onCreate(Bundle SavedInstanceState){ super.onCreate(SavedInstanceState); //Create DB DBHelper dbHelper=new DBHelper(this); db=dbHelper.getWritableDatabase(); }
//Score Initiate public void SetScoreInit(){ try{ writeDB("User",0,0,0); }catch (Exception e){ } } //Set Name public void SetName(String name){ try{ writeDB(name,w,l,d); }catch (Exception e){ } } //Set Score public void SetScore(int GameResult){ if(GameResult==0){ //Draw d=getDrawScore()+1; try{ writeDB("user",w,l,d); }catch (Exception e){ } }else if(GameResult==1){ //Win w=getWinScore()+1; try{ writeDB("user",w,l,d); }catch (Exception e){ } }else { //Lose l=getLoseScore()+1; try{ writeDB("user",w,l,d); }catch (Exception e){ } } } //Get Score,Name public String getUserName(){ try{ readDB(); }catch(Exception e){ } return namestr; } public int getWinScore(){ try{ readDB(); }catch (Exception e){ } return w; } public int getLoseScore(){ try{ readDB(); }catch (Exception e){ } return l; } public int getDrawScore(){ try{ readDB(); }catch(Exception e){ } return d; } //Write DataBase private void writeDB(String Username1, int win, int lose, int draw)throws Exception{ ContentValues values=new ContentValues(); values.put("DB_ID",0); values.put("USERNAME",Username1); values.put("WIN", win); values.put("LOSE",lose); values.put("DRAW",draw); long colNum=db.update(DB_TABLE,values,null,null); if(colNum==0) db.insert(DB_TABLE, "",values); } //DB Read private void readDB() throws Exception{ Cursor c=db.query(DB_TABLE,new String[]{"DB_ID", "USERNAME", "WIN", "LOSE", "DRAW"}, null, null, null, null, null); if(c.getCount()==0) throw new Exception(); c.moveToFirst(); namestr=c.getString(0); w=c.getInt(1); l=c.getInt(2); d=c.getInt(3); c.close(); } //DataBase Helper private static class DBHelper extends SQLiteOpenHelper{ //DB Helper public DBHelper (Context context){ super(context, DB_NAME, null, DB_VERSION); } //DB Create public void onCreate(SQLiteDatabase db){ db.execSQL("create table if not exists " + DB_TABLE + "(DB_ID primary key,USERNAME TEXT, WIN INTEGER, LOSE INTEGER, DRAW INTEGER )"); } //DB Upgrade public void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion){ db.execSQL("drop table if exists " + DB_TABLE ); onCreate(db); }//End of onUpgrade }//End of DBHelper }//End of Class
원래. String 값을 다른 Class 에서 받아오질 못한다면.. 이 2개를 합쳐야 할까요...?
2011.02.09 17:33:44
죄송합니다만, 제가 잘 모르는 건지.... Activity를 상속받은 클래스를 모조
(
new
ScoreDB() 요렇게 하면,
onCreate가 실행될지...
)
처럼사용가능한가요? 단지 디비에서 값만 가져오실거라면 SQLiteOpenHelper를 쓰시는게 더 낳을듯.. 왜 숫자만 값을 가져오는 지 모르겠네요. 숫자는 값을 제데로(0이외값을 넣어도) 가져오는지... 의문이네요.
2011.02.09 17:59:36
제가 ScoreDB를 Acitivity를 상속하는 바람에 생겼던 문제였네요... ㅠㅠ
숫자만 넘어왔던것은 실제로 DB에서 값을 넘겨준게 아니라...
ScoreDB가 Acitivity를 상속했기때문에 new ScoreDB 하면.. 하나의 Activity가 돌면서 거기 있었던 정적 변수를 넘겨줬었네요...
DB -> 정적변수 -> 다른Class에 넘김 이렇게 했는데... Acitivity가 살아있는동안엔.. DB에 저장된 값과 정적변수에 저장된 값이 같기때문에.. 실제론... DB에선 가져온게 아니라..그냥 변수값만 넘겨줬네요 ㅡㅡ;..
일종의 ..트릭? 이었습니다.... 전 DB에서 값을 가져오는줄 알았는데....ㅎㅎ
컬럼 인덱스가 안 맞아서 그러는거겠죠.
인덱스만 맞으면 안 나올 이유는 없습니다.
컬럼 인덱스를 직접 넣는것보단 다음 코드를 사용하는것을 추천드립니다.
c.getString(c.getColumnIndex("컬럼명"))