2014-06-17 2 views
0

나는 Awal.java라는 이름의 활동과 코드가 있습니다내 활동은 내 데이터베이스에 연결할 수 없습니다

public class Awal extends Activity implements OnItemClickListener { 


    private Cursor kategori; 
    private MyDatabase db; 
    private List<String> ktg; 



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

      setContentView(R.layout.activity_main); 


      db = new MyDatabase(this, null); 
      ktg = db.getKategori(); 



      String namaKtg[] = ktg.toArray(new String[ktg.size()]); 

      ListView listView = (ListView) findViewById(R.id.list); 
      listView.setAdapter(new ArrayAdapter<String>(this, R.layout.list, R.id.label, namaKtg)); 
      listView.setOnItemClickListener(this); 

    } 



    @Override 
    protected void onDestroy() { 
     super.onDestroy(); 
     kategori.close(); 
     db.close(); 
    } 

    public void onItemClick(AdapterView<?> adapter, View v, int pos, long l) { 

     Intent intent = new Intent(Awal.this,Detail.class); 
     intent.putExtra("namaKategori", adapter.getItemAtPosition(pos).toString()); 
     startActivity(intent); 
    } 

} 

또한 databaseHelper 이름 MyDatabase.java을 여기에 코드입니다 :

package com.mroring.belajarperancis; 

import java.io.File; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 
import java.util.ArrayList; 
import java.util.List; 

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

public class MyDatabase extends SQLiteOpenHelper { 
    // Variable declaration 
    private static String DB_PATH = "/data/data/com.mroring.belajarperancis/databases/"; 
    public static String DB_NAME = "MY_DATABASE"; 
    private final Context myContext; 
    private String strMypath; 


    public MyDatabase(Context context, String DB_NAME) { 
     super(context, DB_NAME, null, 1); 
     this.myContext = context; 
     try { 
      MyDatabase.DB_NAME = DB_NAME; 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

    public void createDatabase() throws IOException { 
     try { 
      // check if the database exists 
      boolean dbExist = checkDatabase(); 
      if (!dbExist) { 
       // database is not present copy databse 
       this.getReadableDatabase(); 
       try { 
        copyDatabse(DB_NAME); 
       } catch (IOException e) { 
       } 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

    /** 
    * 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() { 
     try { 
      File dbFile = new File(DB_PATH + DB_NAME); 
      return dbFile.exists(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     return 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. 
    * */ 
    public void copyDatabse(String DB_NAME) throws IOException { 
     try { 
      // Open your local db as the input stream 
      Input`enter code here`Stream 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 * 2]; 
      int length; 
      while ((length = myInput.read(buffer)) > 0) { 
       try { 
        myOutput.write(buffer, 0, length); 
       } catch (Exception e) { 
       } 
      } 
      if (myOutput != null) { 
       myOutput.flush(); 
       myOutput.close(); 
      } 
      if (myInput != null) 
       myInput.close(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

    /** 
    * This function is used to open the database 
    * 
    * @throws SQLException 
    */ 
    public void openDatabase() throws SQLException { 
     SQLiteDatabase checkDB = null; 
     // Open the database 
     try { 
      strMypath = DB_PATH + DB_NAME; 
      checkDB = SQLiteDatabase.openDatabase(strMypath, null, 
        SQLiteDatabase.OPEN_READWRITE); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     if (checkDB != null) { 
      checkDB.close(); 
     } 
    } 


     public List<String> getKategori() { 
      String query = "SELECT _id FROM kategori"; 
      List<String> kategori = new ArrayList<String>(); 

      SQLiteDatabase db = getReadableDatabase(); 
      Cursor cursor = db.rawQuery(query, null); 

      //looping through 
      if (cursor.moveToFirst()) { 
       do { 
        kategori.add(cursor.getString(0)); // add id & nama 
       } 
       while (cursor.moveToNext()); 
      } 

      cursor.close(); 
      db.close(); 
      return kategori; 
     } 

     public List<List<String>> getDetail(String namaKategori) { 
      String query = "select pra, ina, baca from kata,kategori where kata.id_kategori=kategori._id and kategori.nama = '"+namaKategori+"'"; 
      List<List<String>> detail = new ArrayList<List<String>>(); 

      SQLiteDatabase db = getReadableDatabase(); 
      Cursor cursor = db.rawQuery(query, null); 

      //looping 
      if (cursor.moveToFirst()) { 

       do { 
        List<String> item = new ArrayList<String>(); 
        item.add(cursor.getString(0)); //add french word 
        item.add(cursor.getString(1)); //add indonesian word 
        item.add(cursor.getString(2)); //add baca 
        detail.add(item); 
       } 
       while (cursor.moveToNext()); 
      } 
      cursor.close(); 
      db.close(); 
      return detail; 
     } 

    @Override 
    public void onCreate(SQLiteDatabase db) { 
     // TODO Auto-generated method stub 
     try { 
      copyDatabse(DB_NAME); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 

    @Override 
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
     // TODO Auto-generated method stub 
    } 

} 

그리고이 조합은 항상 오류를 만들고 여기에 오류가 있습니다 :

06-18 01:23:01.694: E/AndroidRuntime(17219): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mroring.belajarperancis/com.mroring.belajarperancis.Awal}: android.database.sqlite.SQLiteException: no such table: kategori: , while compiling: SELECT _id FROM kategori 
06-18 01:23:01.694: E/AndroidRuntime(17219): Caused by: android.database.sqlite.SQLiteException: no such table: kategori: , while compiling: SELECT _id FROM kategori 

나는 'MY_DATABASE 'in .../BelajarPerancis/assets/databases/MY_DATABASE 그리고/BelajarPerancis/assets/MY_DATABASE (DB를 두 곳에 넣으려고했습니다).

DDMS에서 데이터베이스를 가져 오려고 시도했지만 동일한 내용/테이블을 가진 동일한 데이터베이스를 반환하고 테이블 '분류'가 있습니다.

내 '카테고리'테이블에 '_id'필드가 있으며 여기에 3 Rows returned from: select nama from kategori; (took 5ms)이라는 증거가 있습니다.

답변

0
    당신은 및 쿼리에 당신이 'kategori'할 String query = "SELECT _id FROM kategori"; 같은 테이블 이름에서 데이터를 얻기 위해 노력하고 내가 코드 생성 'kategori'테이블을 볼 수 db = new MyDatabase(this, null);
  1. 줄에 널 (null)로 데이터베이스 이름을 전달하는
  2. 되지는

변경 db = new MyDatabase(this, null);db = new MyDatabase(this, "SOME_DATABASE_NAME");

에 다음 데이터베이스에서 테이블을 생성하는 코드를 작성할 .. 존재한다.

활동 출시 db.getKategori();onCreate() 방법에서 호출되기 때문에 작동하지 않으며 예외를 던지고있다. 이 당신을 도움이되기를 바랍니다

http://www.vogella.com/tutorials/AndroidSQLite/article.html을 통해

는 이동하시기 바랍니다!

+0

고맙습니다! 아주 아주 많이 !! –

+0

나는 'null'을 내 데이터베이스 이름으로 바꿨다. 고마워. 신의 축복이 있기를 바랍니다. D –

0

데이터베이스를 만드시겠습니까?

절대 경로를 사용하여 데이터베이스 파일을 가져 오기 때문에이 경우 가장 좋은 방법은 Google 표준으로 데이터베이스를 만드는 것입니다. 당신은 당신이 모든 방법으로 사용해야 대문자의 첫 문자로 사용하는 경우

How do I create a database in android?

당신은, 당신의 테이블도 이름을 확인할 수 있습니다 : 어떻게의 여기

는 것을, 좋은 답변입니다 시각.

att.

관련 문제