2012-02-18 29 views
0

データベースからデータを取得したい。 私のコードで何を変更する必要がありますか? 私のクラスはボタンクリック時にsqliteデータベースからデータを取得する方法

public class Assessment extends Activity 
{ 
    private static String DB_PATH = "/data/data/+com.comply.assessment()+/Database/"; 
    private static final String DATABASE_NAME = "LMS_MST"; 
    SQLiteDatabase db; 
    TextView mod_code,qst_code,question_id,question,qst_opt1,qst_opt2,qst_opt3,qst_opt4,correct_ans,user_ans; 
    Cursor cursor; 
    private Button start_test; 
     @SuppressWarnings("unused") 

    ListView li; 
    ArrayList<String> it_info; 
    ArrayAdapter<String> aa; 

    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     db= openOrCreateDatabase(AppConstants.DATABASE_NAME, Context.MODE_PRIVATE, null); 

     db.close(); 

     initControls(); 
    } 

    protected void initControls() { 
     // TODO Auto-generated method stub 
     start_test=(Button)findViewById(R.id.start_test); 
     start_test.setOnClickListener(new OnClickListener() 
      { 
       public void onClick(View v) 
       { 
        Intent intent1= new Intent(Assessment.this,Get_Assessment.class); 
        startActivity(intent1); 
       } 
      }); 
    } 
    protected void DoWork() 
    { 
     SQLiteDatabase db= null; 
     String TableName = "lms_mst"; 

     try { 
      db = this.openOrCreateDatabase("LMS_MST", MODE_PRIVATE, 
       null); 
      db.execSQL("DROP TABLE IF EXISTS lms_mst"); 

      db.execSQL("create table IF NOT EXISTS " 
        +AppConstants.TABLE_NAME 
        +"(id INTEGER primary key AUTOINCREMENT,qst_mod_code TEXT,qst_prg_code TEXT,qst_question TEXT,qst_code TEXT,qst_opt1 TEXT,qst_opt2 TEXT,qst_opt3 TEXT,qst_opt4 TEXT,qst_opt01 TEXT,qst_opt02 TEXT,qst_opt03 TEXT,qst_opt04 TEXT,qst_corctopt TEXT,user_code TEXT,qst_company_code TEXT,qst_Marks TEXT);"); 
     } 
     catch(Exception e) { 
      Log.e("Error", "Error", e); 
      } finally { 
      if (db != null) 
      db.close(); 
      } 
     } 
    } 

で、私のdbhelperクラスは、リンクのいずれかの種類がかなりの量になる

public class MyOpenHelper extends SQLiteOpenHelper 
{ 
    private static String DB_PATH = "/data/data/+com.comply.assessment()+/databases/"; 
    private static final String DATABASE_NAME = "LMS_MST"; 
    private static final int DATABASE_VERSION = 1; 
    private SQLiteDatabase db; 
    private final Context myContext; 
    public static final String TABLE_NAME = "LMS_MST"; 
    private static final String COLUMN_ID = "_id"; 
    private static final String QST_CODE="QST_CODE"; 
    private static final String QST_PRG_CODE="QST_PRG_CODE"; 
    private static final String QST_MOD_CODE="QST_MOD_CODE"; 
    private static final String QST_QUESTION="QST_QUESTION"; 
    private static final String QST_OPT1="QST_OPT1"; 
    private static final String QST_OPT2="QST_OPT2"; 
    private static final String QST_OPT3="QST_OPT3"; 
    private static final String QST_OPT4="QST_OPT4"; 
    private static final String QST_OPT01="QST_OPT01"; 
    private static final String QST_OPT02="QST_OPT02"; 
    private static final String QST_OPT03="QST_OPT03"; 
    private static final String QST_OPT04="QST_OPT04"; 
    private static final String QST_CORCTOPT="QST_CORCTOPT"; 
    private static final String USER_CODE="USER_CODE"; 

    public MyOpenHelper(Context context) 
    { 
     super(context,DATABASE_NAME,null,1); 
     this.myContext = context; 

    } 
    /* @Override   
    public void onCreate(SQLiteDatabase db) 
    {     
     db.execSQL("CREATE TABLE " + TABLE_NAME        
       + "(_id INTEGER PRIMARY KEY AUTOINCREMENT, "        
       + QST_CODE+ " TEXT, "  
       + QST_PRG_CODE+ " TEXT" + QST_MOD_CODE+ " TEXT" + QST_QUESTION+ " TEXT" + 
       QST_OPT1+ " TEXT" + QST_OPT2+ " TEXT" + QST_OPT3+ " TEXT" + QST_OPT4+ " TEXT" +  
       QST_OPT01+ " TEXT" + QST_OPT02+ " TEXT" + QST_OPT03+ " TEXT" + QST_OPT04+ " TEXT" + QST_CORCTOPT+ " TEXT" + USER_CODE+ " TEXT" + ");");    
    }*/ 
     public void createDataBase() throws IOException{ 

      boolean dbExist = checkDataBase(); 

      if(dbExist){ 
       //do nothing - database already exist 
      }else{ 

       //By calling this method and empty database will be created into the default system path 
        //of your application so we are gonna be able to overwrite that database with our database. 
       this.getReadableDatabase(); 

       try { 

        copyDataBase(); 

       } catch (IOException e) { 

        throw new Error("Error copying database"); 

       } 
      } 

     } 

     /** 
     * Check if the database already exist to avoid re-copying the file each time you open the application. 
     * @return true if it exists, false if it doesn't 
     */ 
     private boolean checkDataBase(){ 

      SQLiteDatabase checkDB = null; 

      try{ 
       String myPath = DB_PATH + DATABASE_NAME; 
       checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY); 

      }catch(SQLiteException e){ 

       //database does't exist yet. 

      } 

      if(checkDB != null){ 

       checkDB.close(); 

      } 

      return checkDB != null ? true : false; 
     } 
       private void copyDataBase() throws IOException 
       {   
        //Open your local db as the input stream  
        InputStream myInput = myContext.getAssets().open(DATABASE_NAME);   
        // Path to the just created empty db   
        String outFileName = DB_PATH + DATABASE_NAME;   
        //Open the empty db as the output stream   
        OutputStream myOutput = new FileOutputStream(outFileName);   
        //transfer bytes from the inputfile to the outputfile   
        byte[] buffer = new byte[1024];   
        int length;   
        while ((length = myInput.read(buffer))>0) 
        {    
         myOutput.write(buffer, 0, length);  
         }    
        //Close the streams   
        myOutput.flush();   
        myOutput.close();   
        myInput.close();   
        } 

       public void openDataBase() throws SQLException 
       {  
        //Open the database 
        String myPath = DB_PATH + DATABASE_NAME; 
        db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY); 
        } 
       @Override  
       public synchronized void close() 
       {   
        if(db != null)    
         db.close();   
        super.close(); 
       } 

       @Override 
      public void onCreate(SQLiteDatabase db) 
       { 
       // TODO Auto-generated method stub 

      } 

    @Override 
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)  
    { 
     String sql = myContext.getString(R.string.app_name);  
     db.beginTransaction();  
     try   
     {   
      db.execSQL(sql);  
      db.setTransactionSuccessful(); 
      }catch(SQLException e)  
      {      
       System.out.println("Error Upgrading tables...");  
       }  
      finally  
      {    
       db.endTransaction();  
       }  
      onCreate(db); 

    } 
    public Cursor getData()  
    {  int qst_code=1; 

    //Creates the query String. Query is static in DataCursor inner class  
    String sql = "SELECT * FROM lms_mst_questionbank ";  
    //Create an array of String to specify values for ?'s in the sql Query   
    String sqlArgs[] = new String[]{Integer.toString(qst_code) };  
    //Creates a cursor using the SQLiteDatabase object's rawQuery method  
    Cursor c = db.rawQuery(sql,sqlArgs);  
    //The cursor is returned  
    return c; 
     /*Cursor cursor = getReadableDatabase(). 
     rawQuery("select * from lms_mst_questionbank where _id = ?", new String[] { COLUMN_ID }); 
     return cursor;*/ 
    } 


} 

です。

答えて

0

アプリケーションにDBサポートを追加すると、私はいつもthis postを参照します。それがあなたにも役立つことを願っています!

0

パブリッククラスListActivityアクティビティ{

List<Question> quesList; 
DataBaseHandler db = new DataBaseHandler(this); 
ArrayAdapter<String>adapter; 
ArrayList<HashMap<String,String>>alist; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_list); 
    ListView lv = (ListView)findViewById(R.id.secondlist); 
    alist = new ArrayList<HashMap<String,String>>(); 
    quesList = db.getAllQuestions(); 
    for(int i=0;i<db.rowcount();i++){ 
     HashMap<String,String>hm = new HashMap<String,String>(); 
     hm.put("question", quesList.get(i).getQuestion()); 
     hm.put("rightans", quesList.get(i).getCorrectoption()); 
     alist.add(hm); 
    } 
    String[]from = {"question","rightans"}; 
    int[]to = {R.id.listtext,R.id.listtextans}; 
    SimpleAdapter adapter = new SimpleAdapter(getApplicationContext(), alist, R.layout.listitemoflist, from, to); 
    lv.setAdapter(adapter); 

    /*List<String> listTitle = new ArrayList<String>(); 

    for (int i = 0; i < quesList.size(); i++) { 
     listTitle.add(i, quesList.get(i).getQuestion()); 
     listTitle.add(quesList.get(i).getCorrectoption()); 
    } 

    adapter = new ArrayAdapter<String>(this, R.layout.listitemoflist,R.id.listtext, listTitle); 

    lv.setAdapter(adapter);*/ 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.list, menu); 
    return true; 
} 

}

+0

してください、いくつかの説明を追加する拡張あなたのコードに – Alex

0
  String uname = username.getText().toString(); 
      String pword = password.getText().toString(); 
      String cpword = cpassword.getText().toString(); 
      if(uname.equals("") && pword.equals("") && cpword.equals("")){ 
       Toast.makeText(getApplicationContext(), "failed updation", Toast.LENGTH_SHORT).show(); 
      } 
      if(!pword.equals(cpword)){ 
       Toast.makeText(getApplicationContext(), "Password does not match" 
         , Toast.LENGTH_SHORT).show(); 
      } 
      else{ 
       loginDataBaseAdapter.updateEntry(uname, pword); 
       Toast.makeText(getApplicationContext(), "Account Successfully Updated" 
         , Toast.LENGTH_SHORT).show(); 

       Intent i = new Intent(UpdatePassword.this, 
         LoginActivity.class); 
       startActivity(i); 
       finish(); 
      } 
関連する問題