2012-03-23 36 views
1

我正在写一个应用程序,涉及拍摄照片,然后将该照片的URI保存在数据库中。图像URI构成单个条目的一部分(由照片和多个音频文件URI组成的条目)。下面是我到目前为止的代码的应用程序的这一部分:Android:添加到应用程序数据库不工作

数据库处理器

package com.example.HwST_GoMo; 

import java.io.File; 
import java.util.ArrayList; 
import java.util.List; 

import android.content.ContentValues; 
import android.content.Context; 
import android.database.Cursor; 
import android.database.SQLException; 
import android.database.sqlite.SQLiteDatabase; 
import android.database.sqlite.SQLiteOpenHelper; 
import android.os.Environment; 
import android.util.Log; 

public class DatabaseHandler extends SQLiteOpenHelper { 


    private SQLiteDatabase myDataBase; 

    // All Static variables 
    // Database Version 
    private static final int DATABASE_VERSION = 10; 

    // Database Name 
    private static final String DATABASE_NAME = "db"; 

    private static final String DB_PATH = "/mnt/sdcard/HWST/"; 

    // Contacts table name 
    private static final String TABLE_ENTRIES = "Entries"; 

    // Contacts Table Columns names 
    private static final String KEY_ID = "entry_id"; 
    private static final String KEY_IMAGE_URI = "image_uri"; 
    private static final String KEY_AUDIO_URI = "audio_uri"; 

    public DatabaseHandler(Context context) { 
     super(context, DATABASE_NAME, null, DATABASE_VERSION); 
    } 

    // Creating Tables 
    @Override 
    public void onCreate(SQLiteDatabase db) { 
     String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_ENTRIES + "(" 
       + KEY_AUDIO_URI + " TEXT, " + KEY_IMAGE_URI + " TEXT," + KEY_ID + " INTEGER PRIMARY KEY" + 
       ")"; 
     db.execSQL(CREATE_CONTACTS_TABLE); 
    } 

    // Upgrading database 
    @Override 
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
     // Drop older table if existed 
     db.execSQL("DROP TABLE IF EXISTS " + TABLE_ENTRIES); 

     // Create tables again 
     onCreate(db); 
    } 

    public void openDataBase() throws SQLException{ 

     //Open the database 
     String myPath = DB_PATH + DATABASE_NAME; 
     myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS); 

    } 

    public void addEntry(String URI){ 


     //SQLiteDatabase db = this.getWritableDatabase(); 
     myDataBase = this.getWritableDatabase(); 


     ContentValues values = new ContentValues(); 
     //values.put(KEY_IMAGE_URI, entry.getImageUri()); // Contact Name 
     //values.put(KEY_AUDIO_URI, entry.getAudioUri()); // Contact Phone Number 

     values.put(KEY_AUDIO_URI, "LOLOL"); 
     values.put(KEY_IMAGE_URI, URI); 
     values.put(KEY_ID, 265); 

     // Inserting Row 

     long test = myDataBase.insert(TABLE_ENTRIES, null, values); 

     System.out.println("PLEASE REACH THIS also " + test); 

     this.close(); 
     //myDataBase.close(); // Closing database connection 
    } 

    // Getting single entry 
    Entry getEntry(int id) { 
     SQLiteDatabase db = this.getReadableDatabase(); 

     Cursor cursor = db.query(TABLE_ENTRIES, new String[] { KEY_ID, 
       KEY_IMAGE_URI, KEY_AUDIO_URI }, KEY_ID + "=?", 
       new String[] { String.valueOf(id) }, null, null, null, null); 
     if (cursor != null) 
      cursor.moveToFirst(); 

     Entry entry = new Entry(Integer.parseInt(cursor.getString(0)), 
       cursor.getString(1), cursor.getString(2)); 
     // return entry 
     return entry; 
    } 

    // Getting All Entries 
    public List<Entry> getAllEntries() { 
     List<Entry> entryList = new ArrayList<Entry>(); 
     // Select All Query 
     String selectQuery = "SELECT * FROM " + TABLE_ENTRIES; 

     SQLiteDatabase db = this.getWritableDatabase(); 
     Cursor cursor = db.rawQuery(selectQuery, null); 

     // looping through all rows and adding to list 
     if (cursor.moveToFirst()) { 
      do { 
       Entry entry = new Entry(); 
       entry.setID(Integer.parseInt(cursor.getString(0))); 
       entry.setImageUri(cursor.getString(1)); 
       entry.setAudioUri(cursor.getString(2)); 
       // Adding entry to list 
       entryList.add(entry); 
      } while (cursor.moveToNext()); 
     } 

     // return entry list 
     return entryList; 
    } 

    // Updating single entry 
    public int updateEntry(Entry entry) { 
     SQLiteDatabase db = this.getWritableDatabase(); 

     ContentValues values = new ContentValues(); 
     values.put(KEY_IMAGE_URI, entry.getImageUri()); 
     values.put(KEY_AUDIO_URI, entry.getAudioUri()); 

     // updating row 
     return db.update(TABLE_ENTRIES, values, KEY_ID + " = ?", 
       new String[] { String.valueOf(entry.getID()) }); 
    } 

    // Deleting single contact 
    public void deleteEntry(Entry entry) { 
     SQLiteDatabase db = this.getWritableDatabase(); 
     db.delete(TABLE_ENTRIES, KEY_ID + " = ?", 
       new String[] { String.valueOf(entry.getID()) }); 
     db.close(); 
    } 

    // Getting contacts Count 
    public int getEntriesCount() { 
     String countQuery = "SELECT * FROM " + TABLE_ENTRIES; 
     SQLiteDatabase db = this.getReadableDatabase(); 
     Cursor cursor = db.rawQuery(countQuery, null); 
     cursor.close(); 

     // return count 
     return cursor.getCount(); 
    } 
} 

TakePhotographPage

package com.example.HwST_GoMo; 

import java.io.File; 
import java.io.FileOutputStream; 

import android.app.Activity; 
import android.content.ContextWrapper; 
import android.content.Intent; 
import android.graphics.Bitmap; 
import android.graphics.Bitmap.CompressFormat; 
import android.net.Uri; 
import android.os.Bundle; 
import android.os.Environment; 
import android.util.Log; 
import android.view.View; 
import android.widget.Button; 
import android.widget.ImageView; 
import android.widget.TextView; 

public class TakePhotographPage extends Activity { 
    /** Called when the activity is first created. */ 

    private static final int CAMERA_REQUEST = 1888; 
    private ImageView imageView; 

    DatabaseHandler db = new DatabaseHandler(this); 
    private TextView textView; 


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

     Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
     startActivityForResult(cameraIntent, CAMERA_REQUEST); 

     this.imageView = (ImageView)this.findViewById(R.id.photoResultView); 
     this.textView = (TextView)this.findViewById(R.id.textTest); 



     Button button = (Button)findViewById(R.id.back_to_menu); 
     button.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View view) { 
       Intent intent = new Intent(view.getContext(), ControlsPage.class); 
       startActivityForResult(intent, 0); 
       // TODO Auto-generated method stub 
      } 
     });   
    } 

    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     if (requestCode == CAMERA_REQUEST) { 
      Bitmap photo = (Bitmap) data.getExtras().get("data"); 
      imageView.setImageBitmap(photo); 

      int temp = (new File("/mnt/sdcard/HWST/").list().length) +1 ; 
      String fileName = Integer.toString(temp); 

      File file = null; 
      FileOutputStream os; 
      String dirName = "/HWST/"; 
        try { 

          File sdCard = Environment.getExternalStorageDirectory(); 

          System.out.println(sdCard); 
          File dir = new File (sdCard.getAbsolutePath() + dirName); 

          file = new File(dir, fileName + ".png"); 
          System.out.println(file); 


          FileOutputStream outStream = new FileOutputStream(file); 
          photo.compress(Bitmap.CompressFormat.PNG, 100, outStream); 
          outStream.flush(); 
          outStream.close(); 


          DatabaseHandler db = new DatabaseHandler(this); 
          db.openDataBase(); 

          db.addEntry(file.toString()); 

        }catch(Exception e){ 
          System.out.println(e.toString()); 
        } 



      //db.addEntry(new Entry(0, "" + u + "", "test")); 
     } 
    } 
} 

入门级

package com.example.HwST_GoMo; 

public class Entry { 

    //private variables 
    int _id; 
    String _imageUri; 
    String _audioUri; 

    //Empty Constructor 
    public Entry(){ 

    } 

    //constructor 
    public Entry(int id, String imageUri, String audioUri){ 
     this._id = id; 
     this._imageUri = imageUri; 
     this._audioUri = audioUri; 
    } 

    //get ID 
    public int getID(){ 
     return this._id; 
    } 

    //set ID 
    public void setID(int id){ 
     this._id = id; 
    } 

    //get imageUri 
    public String getImageUri(){ 
     return this._imageUri; 
    } 

    //set imageUri 
    public void setImageUri(String imageUri){ 
     this._imageUri = imageUri; 
    } 

    //get audioUri 
    public String getAudioUri(){ 
     return this._audioUri; 
    } 

    //set audioUri 
    public void setAudioUri(String audioUri){ 
     this._audioUri = audioUri; 
    } 

} 

我的问题是,没有什么被添加到我的数据库,而是它似乎被添加到我无法访问/ data/data中的数据库。如果我将KEY_ID设置为我之前没有使用过的号码,然后运行应用程序并拍摄照片,logcat给我提供以下内容:http://img26.imageshack.us/img26/6526/logcat1.png

如果我再次运行该应用程序,使用相同的KEY_ID,以下内容: http://img706.imageshack.us/img706/1857/logcat2.png

PC和手机上的SQLite的管理器应用中使用SQLite数据库浏览器,我看什么都没有输入到数据库中。

第二次输入相同ID时的约束错误使我相信数据正在进入数据库(尽管这是错误的),所以我的问题是,我为强制应用程序做了哪些更改把条目放到“/ mtn/sdcard/HWST/db”而不是“/data/data/com.example.HwST_GoMo/databases/db”的地址处?

对不起,不得不使用图像作为logcat输出,但它不允许我将消息导出到txt文件。

回答

0
// Database Name 
private static final String DATABASE_NAME = "db"; 

// path to db 
private static final String DB_PATH = "/mnt/sdcard/HWST/"; 

// now both combined 
private static final String DB_FILE = DB_PATH + DATABASE_NAME; 

public DatabaseHandler(Context context) { 
    super(context, DB_FILE, null, DATABASE_VERSION); 
} 

构造函数将在您指定的位置创建数据库。如果名称以/(绝对路径)开头,那么数据库将在那里创建。如果你给它别的东西,它会在/data/data/your.package.name/databases/[name]中创建它。该路径是您的应用程序主目录,并且可以在该目录中读取/写入。

另请参见:您应该从DatabaseHandler中将构造函数/ onCreate/onUpgrade中的所有内容都移动到新类中,并使用DatabaseHandlerSQLiteOpenHelper的意图是帮助您获得具有所需表格(创建/升级)的可写入数据库。你最好不要用它来做其他事情。

class TheRealDatabaseHandler { 

    public void addEntry(String URI){ 
     DatabaseHandler helper = new DatabaseHandler(mContext); 
     SQLiteDatabase db = helper.getWritableDatabase(); 
     db.insert... 
    } 

} 
相关问题