2013-08-28 2 views
0

데이터베이스를 사용할 때 여러 가지 코드를 시도했습니다. 자산 폴더에 복사 한 기존 데이터베이스를 사용하려고합니다. 내 팝업을 SQL 쿼리의 결과를 표시합니다. 내가 시도한 코드는android에서 데이터베이스 연결이 성공했는지 여부를 확인하는 방법은 무엇입니까?

package com.example.singlepop; 

import java.io.IOException; 
import java.util.Calendar; 

import android.os.Bundle; 
import android.app.Activity; 
import android.database.Cursor; 
import android.database.SQLException; 
import android.view.Menu; 

import android.view.Gravity; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.view.ViewGroup.LayoutParams; 
import android.widget.Button; 
import android.widget.LinearLayout; 
import android.widget.PopupWindow; 
import android.widget.TextView; 

public class Single extends Activity { 
    PopupWindow popUp; 
    LinearLayout layout; 
    TextView tv; 
    LayoutParams params; 
    LinearLayout mainLayout; 
    Button but; 
    boolean click = true; 




    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     DataBaseHelper myDbHelper = new DataBaseHelper(this); 
     try { 

      myDbHelper.createDataBase(); 

      } catch (IOException ioe) { 

      throw new Error("Unable to create database"); 

      } 
     try { 

      myDbHelper.openDataBase(); 

      }catch(SQLException sqle){ 

      throw sqle; 

      } 

      popUp = new PopupWindow(this); 
      layout = new LinearLayout(this); 
      mainLayout = new LinearLayout(this); 



      final Calendar cld = Calendar.getInstance(); 

      int time = cld.get(Calendar.HOUR_OF_DAY); 
      if(time==20) 
      { 
       tv = new TextView(this); 
       but = new Button(this); 

      but.setText("Click me for pop up"); 
      but.setOnClickListener(new OnClickListener() { 

      public void onClick(View v) { 
      if (click) { 
      popUp.showAtLocation(layout, Gravity.BOTTOM, 10, 10); 
      popUp.update(50, 50, 300, 80); 
      click = false; 
      } else { 
      popUp.dismiss(); 
      click = true; 
      } 
      } 

      }); 
      params = new LayoutParams(LayoutParams.WRAP_CONTENT, 
      LayoutParams.WRAP_CONTENT); 
      layout.setOrientation(LinearLayout.VERTICAL); 
      //tv.setText("Time is 8 pm"); 

      // display the outcome of the query 
      tv.setText(myDbHelper.thought()); 


      layout.addView(tv, params); 
      popUp.setContentView(layout); 
      // popUp.showAtLocation(layout, Gravity.BOTTOM, 10, 10); 
      mainLayout.addView(but, params); 
      setContentView(mainLayout); 
      } 
      else 
      { 
       tv.setText("NO TIME"); 
      } 




    } 




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

} 

이 코드는 나에게 성공적인 팝업을 제공합니다. 자산 폴더에 복사 된 n 개의 데이터베이스 "MyDatabase"가 있습니다. 내 DataBaseHelper 클래스는

package com.example.singlepop; 

import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 

import android.content.Context; 
import android.database.Cursor; 
import android.database.SQLException; 
import android.database.sqlite.SQLiteDatabase; 
import android.database.sqlite.SQLiteException; 
import android.database.sqlite.SQLiteOpenHelper; 

public class DataBaseHelper extends SQLiteOpenHelper { 
    private static final int _id = 1; 

    //The Android's default system path of your application database. 
    private static String DB_PATH = "/data/data/com.example.singlepop/databases/"; 

    private static String DB_NAME = "MyDatabase"; 

    private SQLiteDatabase myDataBase; 

    private final Context myContext; 

    private static String DB_TABLE = "Totlist"; 

    private static final String tot = null; 

    String des=tot; 

    /** 
     * Constructor 
     * Takes and keeps a reference of the passed context in order to access to the application assets and resources. 
     */ 
    public DataBaseHelper(Context context) { 

    super(context, DB_NAME, null, 1); 
    this.myContext = context; 
    } 

    /** 
     * Creates a empty database on the system and rewrites it with your own database. 
     * */ 
    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 + DB_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; 
    } 

    /** 
     * Copies your database from your local assets-folder to the just created empty database in the 
     * system folder, from where it can be accessed and handled. 
     * This is done by transfering bytestream. 
     * */ 
    private void copyDataBase() throws IOException{ 

    //Open your local db as the input stream 
    InputStream myInput = myContext.getAssets().open(DB_NAME); 

    // Path to the just created empty db 
    String outFileName = DB_PATH + DB_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 + DB_NAME; 
     myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY); 

     } 

    @Override 
    public synchronized void close() { 

    if(myDataBase != null) 
    myDataBase.close(); 

    super.close(); 

    } 

    @Override 
    public void onCreate(SQLiteDatabase db) { 

    } 

    @Override 
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 

    } 

     // This function should return the outcome of the query but below code is wrong 
    public String thought() 
    { 

     String quer="Hello"; 
     String sql = "SELECT * FROM option WHERE id = 1"; 
     Cursor check = myDataBase.rawQuery(sql, null); 
     quer=String.valueOf(check); 
     return quer; 

    } 



} 

rawQuery 난의 setText를 사용 할 수 표시되지 오전 Cursor 형식을 반환합니다. 팝업에서 표시되는 쿼리의 결과를 얻을 수 있도록 어떻게해야합니까? 내가 이것을 실행하면 logcat에 많은 오류가 발생합니다. 그것은 연결에 문제가 될 수 있습니다.

08-28 20:00:57.396: E/Trace(841): error opening trace file: No such file or directory (2) 
08-28 20:00:59.003: E/SQLiteLog(841): (14) cannot open file at line 30176 of [00bb9c9ce4] 
08-28 20:00:59.023: E/SQLiteLog(841): (14) os_unix.c:30176: (2) open(/data/data/com.example.singlepop/databases/MyDatabase) - 
08-28 20:00:59.173: E/SQLiteDatabase(841): Failed to open database '/data/data/com.example.singlepop/databases/MyDatabase'. 
08-28 20:00:59.173: E/SQLiteDatabase(841): android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database 

여전히 오류

답변

0

당신이 얻을 오류 메시지의 많은 데이터베이스 파일 /data/data/com.example.singlepop/databases/MyDatabase이 존재하지 않는 것을 나타냅니다. 그것을 확인할 수 있습니까?

또한 작동하면 Cursor은 쿼리 결과를 나타냅니다. 둘 이상의 레코드가 리턴 될 수 있습니다. 먼저 커서를 읽으려는 행에 놓은 다음 개별 열에 액세스 할 수 있습니다. 예를 들어 (모든 오류 처리를 떠나 테이블이 col1라는 이름의 열이 있다고 가정) : 여기

check.moveToFirst(); 
String col1 = check.getString(check.getColumnIndex("col1")); 
+0

나는 작업 공간으로 들어가서 경로를 따라 갔다. 나는 단지 2 개의 .java 파일을 찾을 수 있지만 MyDatabase는 찾지 못한다. 연결이 설정되지 않았다는 것을 의미합니까 ?? – user2648852

+0

반환 할 열이 두 개 이상인 경우 어떻게 사용해야합니까? – user2648852

+0

다른 열의 마지막 줄을 반복하십시오. – Henry

0

을 내가 당신의 질문을 이해 모르겠지만이야 어떻게 설정을하고자하고 데이터베이스에서 읽어

public class SQLTest extends SQLiteOpenHelper { 
private static final String DATABASE_NAME = "TestDatabase.db"; 
private static final int DATABASE_VERSION = 1; 
private Context context; 

public static final String TABLENAME = "mytable"; 
public static final String COL_ID = "_id"; 
public static final String COL_NAME = "name"; 


public SQLSimple(Context context) { 
    super(context, DATABASE_NAME, null, DATABASE_VERSION); 
    this.context = context; 
} 

@Override 
public void onCreate(SQLiteDatabase db) { 
    String STATEMENT_CREATE = "create table if not exists '"+TABLENAME+"' (" 
     +COL_ID+" integer primary key autoincrement, " 
     +COL_NAME+" text not null, " 
    db.execSQL(STATEMENT_CREATE); 
} 

@Override 
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
    String STATEMENT_DROP = "drop table if exists '"+TABLENAME+"';"; 
    db.execSQL(STATEMENT_DROP); 

    onCreate(db); 
} 

public String readName(int id) { 
    SQLiteDatabase db = getReadableDatabase(); 
    Cursor cursor = null; 
    try { 
     //Return these two columns only. Here, we only have two of course, but in a bigger table this is good for performance. 
     String[] projection = new String[]{COL_ID, COL_NAME}; 

     //The where part of the query that defines what we are looking for 
     String selection = COL_ID + " = ?"; 

     //The data that will replace the ? in the query before. Doing it this way is to prevent injection and escaping errors 
     String selectionArgs[] = new String[]{id+""}; 
     cursor = db.query(TABLENAME, projection, selection, selectionArgs, null, null, null); 

     String name = null; 

     if(cursor.moveToFirst()) { 
      String name = cursor.getString(cursor.getColumnIndex(COL_NAME)); 
     } 

     return name; 
    } finally { 
     //Close the database before returning item, even in the case of an exception 
     if (cursor != null && !cursor.isClosed()) { 
      cursor.close(); 
     } 
     if (db.isOpen()) { 
      db.close(); 
     } 
    } 
} 

이 질문에 대한 답변을 보내 주시면 감사하겠습니다. 그렇지 않다면 물어보십시오.

+0

나는 2 개의 필드 (id와 description)를 가진 데이터베이스를 가지고있다. 나는 sqlite 브라우저를 사용하여이 데이터베이스를 만들었습니다. 내 애플 리케이션 내 데이터베이스의 "설명"필드에 콘텐츠를 표시해야합니다. 내 코드에 표시해야하는 위치를 지정했습니다. – user2648852

+0

내 앱이 아침에 매일 팝을 표시해야합니다. 팝업은 내 데이터베이스의 설명 필드에있는 내용이어야합니다. 내가 필요로하는 thats 모두 – user2648852

+0

오 오. 음, 먼저 앱이 데이터베이스가/data/data/ /database/YourDatabase.db에있을 것으로 기대한다는 것을 알아야합니다. 다른 폴더에서 작동하는 경우 시도해야 할 것입니다. 확실하지 않습니다. 그럼 당신이 올바른 장소에 넣어 가정하고, 내 코드를 가져 가면서 onCreate와 onUpgrade를 비워두고 데이터베이스와 테이블 이름을 변경하고 그에 따라 열 이름을 수정 한 다음 readName (id)을 사용하여 귀하의 설명 (당신은 물론 그 방법의 이름을 바꾸어야합니다). 희망이 도움이됩니다! – metter

1

정확히 1 아무것도 다른 반환해야

select 1; 

이 같은 몇 가지 사소한 SQL을 전송하여 데이터베이스 연결을 테스트하기 쉽고, 데이터베이스에 대한 접속이 없을 때 확실히 실패합니다. 이러한 쿼리는 테이블을 만들거나 액세스 할 수있는 권한을 가지지 않으며, 아무것도 수정하지 않으며 실제 데이터베이스 내용과 독립적으로 작동합니다.

0

데이터베이스 파일이 에셋 폴더에 있습니다. 그리고 createDataBase()으로 전화를 걸어 checkDataBase()을 사용하여 데이터베이스의 존재를 먼저 확인한 다음 copyDataBase()으로 전화하십시오.

/data/data/com.example.singlepop/databases/MyDatabase에서 데이터베이스를 열려고 할 때. checkDataBase()에 copyDatabase()를 호출 할 때까지 데이터베이스가/assets 폴더에 있으므로 예외가 발생합니다.

즉. 열려면 시도하기 전에 error opening trace file: No such file or directory

  • android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
  • 먼저 해당 위치로 데이터베이스를 복사해야합니다

    1. .

      CommonsWare 자신이 권장하는 SQLiteAssetHelper을 사용하는 것이 좋습니다.

    관련 문제