Android 如何在sqllite数据库中保存图像?

Android 如何在sqllite数据库中保存图像?,android,Android,这是我的代码,下面是浏览imagew gellery并选择图像,但如何在数据库中插入图像视图?此代码成功地在屏幕上显示选定的图像但未存储在数据库中如何传递图像参数?在我评论的那一行/我在这里写的东西/ 导入android.app.Activity; 导入android.app.AlertDialog; 导入android.content.Intent; 导入android.database.Cursor; 导入android.graphics.Bitmap; 导入android.graphics

这是我的代码,下面是浏览imagew gellery并选择图像,但如何在数据库中插入图像视图?此代码成功地在屏幕上显示选定的图像但未存储在数据库中如何传递图像参数?在我评论的那一行/我在这里写的东西/

导入android.app.Activity;
导入android.app.AlertDialog;
导入android.content.Intent;
导入android.database.Cursor;
导入android.graphics.Bitmap;
导入android.graphics.BitmapFactory;
导入android.net.Uri;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.provider.MediaStore;
导入android.view.view;
导入android.view.view.OnClickListener;
导入android.widget.Button;
导入android.widget.EditText;
导入android.widget.ImageView;
导入android.widget.Toast;
公共课堂扩展活动{
私人长罗威德;
私有编辑文本名称;
私人编辑文本capEt;
私人编辑文本代码集;
私人编辑;
私人编辑文本注释;
私人编辑;
私有ImageView imageView1;
位图您选择的图像;
@凌驾
创建时的公共void(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.add_country);
nameEt=(EditText)findViewById(R.id.Address);
capEt=(编辑文本)findViewById(R.id.Stage);
codeEt=(EditText)findViewById(R.id.Dueby);
Donedate=(EditText)findViewById(R.id.Donedate);
Notes=(EditText)findViewById(R.id.Notes);
Person=(EditText)findViewById(R.id.Person);
imageView1=(ImageView)findViewById(R.id.imageView1);
按钮浏览=(按钮)findViewById(R.id.Browse);
Browse.setOnClickListener(新视图.OnClickListener()
{
公共void onClick(视图v)
{               
意向意向=新意向(意向.行动\u获取\u内容);
intent.setType(“image/*”);
startActivityForResult(意向,0);
}
});        
Bundle extras=getIntent().getExtras();
如果(附加值!=null)
{
rowID=extras.getLong(“row_id”);
setText(extras.getString(“name”);
capEt.setText(附加getString(“cap”);
codeEt.setText(extras.getString(“代码”);
setText(extras.getString(“位置”);
Notes.setText(extras.getString(“Notes”);
Person.setText(extras.getString(“Person”);
imageView1.setImageURI(您选择的图像);
}
按钮saveButton=(按钮)findViewById(R.id.saveBtn);
saveButton.setOnClickListener(新的OnClickListener(){
公共void onClick(视图v)
{
if(nameEt.getText().length()!=0)
{
AsyncTask saveContactTask=
新建异步任务()
{
@凌驾
受保护对象doInBackground(对象…参数)
{
saveContact();
返回null;
}
@凌驾
受保护的void onPostExecute(对象结果)
{
完成();
}
}; 
saveContactTask.execute((Object[])null;
}
其他的
{
AlertDialog.Builder alert=新建
AlertDialog.Builder(AddEditCountry.this);
alert.setTitle(R.string.errorTitle);
alert.setMessage(R.string.errorMessage);
alert.setPositiveButton(R.string.errorButton,null);
alert.show();
}
} 
});
}
私有void saveContact()
{
DatabaseConnector dbConnector=新的DatabaseConnector(此);
if(getIntent().getExtras()==null)
{
/*我在这里为图片写的内容*/
dbConnector.insertContact(nameEt.getText().toString(),
capEt.getText().toString(),
codeEt.getText().toString(),
Donedate.getText().toString(),
Notes.getText().toString(),
Person.getText().toString(),null
);
}
其他的
/*我在这里写的是什么图片*/{
dbConnector.updateContact(rowID,
nameEt.getText().toString(),
capEt.getText().toString(),
codeEt.getText().toString(),
Donedate.getText().toString(),
Notes.getText().toString(),
Person.getText().toString(),null
);
}
}
ActivityResult上受保护的void(int-requestCode、int-resultCode、Intent-ImageReturnedContent){
super.onActivityResult(请求代码、结果代码、图像返回内容);
开关(请求代码){
案例0:
if(resultCode==RESULT\u OK){
Uri selectedImage=imageReturnedIntent.getData();
字符串[]filePathColumn={MediaStore.Images.Media.DATA};
Cursor Cursor=getContentResolver().query(selectedImage,filePathColumn,null,null);
cursor.moveToFirst();
int columnIndex=cursor.getColumnIndex(filePathColumn[0]);
String filePath=cursor.getString(columnIndex);//所选图像的文件路径
cursor.close();
//使用下线将文件路径转换为位图图像。
您选择的edimage=BitmapFactory.decodeFile(文件路径);
//在imageview中放置bitmapimage
图像视图1.设置图像位图(您选择的图像);
}
}
}
}

请使用下面的代码将图像存储到sqlite数据库中,它将解决您的问题

MySQLActivity.java:-

public class MySQLActivity extends Activity implements OnClickListener
{
    protected static TextView textView;
    protected static ImageView bmImage;
    protected Button start;

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

        bmImage = (ImageView)findViewById(R.id.imageView1);
        textView = (TextView) findViewById(R.id.textView1);

        start = (Button) findViewById(R.id.button1);
        start.setOnClickListener(this); 

        DownloadFile();
    }

    public void onClick(View v) 
    {
        SQLiteDatabase myDb;       
        String MySQL;
        int icount;
        byte[] byteImage1 = null;
        byte[] byteImage2 = null;
        MySQL="create table emp1(_id INTEGER primary key autoincrement, fio TEXT not null, picture BLOB);";
        myDb = openOrCreateDatabase("/sdcard/Nick/MyWeatherDB.db", Context.MODE_PRIVATE, null);

        String s=myDb.getPath();
        textView.append("\r\n" + s+"\r\n");       
        myDb.execSQL("delete from emp1");
        ContentValues newValues = new ContentValues();
        newValues.put("fio", "Иванов Петр Сергеевич");

        /////////// insert picture to blob field ///////////////////// 
        try
        {
            FileInputStream instream = new FileInputStream("/sdcard/Dipak/Keshariya.png"); 
            BufferedInputStream bif = new BufferedInputStream(instream); 
            byteImage1 = new byte[bif.available()]; 
            bif.read(byteImage1); 
            textView.append("\r\n" + byteImage1.length+"\r\n"); 
            newValues.put("picture", byteImage1); 

            long ret = myDb.insert("emp1", null, newValues); 
            if(ret<0) textView.append("\r\n!!! Error add blob filed!!!\r\n");
        } catch (IOException e) {
            textView.append("\r\n!!! Error: " + e+"!!!\r\n");   
        }

        ////////////Read data ////////////////////////////  
        Cursor cur = myDb.query("emp1",null, null, null, null, null, null);
        cur.moveToFirst();
        while (cur.isAfterLast() == false)
        {
            textView.append("\r\n" + cur.getString(1)+"\r\n");
            cur.moveToNext();
        }

        ///////Read data from blob field////////////////////
        cur.moveToFirst();
        byteImage2=cur.getBlob(cur.getColumnIndex("picture"));
        bmImage.setImageBitmap(BitmapFactory.decodeByteArray(byteImage2, 0, byteImage2.length));
        textView.append("\r\n" + byteImage2.length+"\r\n"); 

        //////////////////////////    
        cur.close();
        myDb.close();
  }

  public void DownloadFile() 
  {   
      Bitmap bitmap1 = null;                    
      bitmap1 = BitmapFactory.decodeFile("/sdcard/Dipak/Dipak.jpg"); //weather.png");
      bmImage.setImageBitmap(bitmap1);
  }
}
公共类MySQLActivity扩展活动实现OnClickListener
{
受保护的静态文本视图文本视图;
受保护的静态图像视图bmImage;
保护按钮启动;
@凌驾
创建时的公共void(Bundle savedInstanceState){
超人
public class MySQLActivity extends Activity implements OnClickListener
{
    protected static TextView textView;
    protected static ImageView bmImage;
    protected Button start;

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

        bmImage = (ImageView)findViewById(R.id.imageView1);
        textView = (TextView) findViewById(R.id.textView1);

        start = (Button) findViewById(R.id.button1);
        start.setOnClickListener(this); 

        DownloadFile();
    }

    public void onClick(View v) 
    {
        SQLiteDatabase myDb;       
        String MySQL;
        int icount;
        byte[] byteImage1 = null;
        byte[] byteImage2 = null;
        MySQL="create table emp1(_id INTEGER primary key autoincrement, fio TEXT not null, picture BLOB);";
        myDb = openOrCreateDatabase("/sdcard/Nick/MyWeatherDB.db", Context.MODE_PRIVATE, null);

        String s=myDb.getPath();
        textView.append("\r\n" + s+"\r\n");       
        myDb.execSQL("delete from emp1");
        ContentValues newValues = new ContentValues();
        newValues.put("fio", "Иванов Петр Сергеевич");

        /////////// insert picture to blob field ///////////////////// 
        try
        {
            FileInputStream instream = new FileInputStream("/sdcard/Dipak/Keshariya.png"); 
            BufferedInputStream bif = new BufferedInputStream(instream); 
            byteImage1 = new byte[bif.available()]; 
            bif.read(byteImage1); 
            textView.append("\r\n" + byteImage1.length+"\r\n"); 
            newValues.put("picture", byteImage1); 

            long ret = myDb.insert("emp1", null, newValues); 
            if(ret<0) textView.append("\r\n!!! Error add blob filed!!!\r\n");
        } catch (IOException e) {
            textView.append("\r\n!!! Error: " + e+"!!!\r\n");   
        }

        ////////////Read data ////////////////////////////  
        Cursor cur = myDb.query("emp1",null, null, null, null, null, null);
        cur.moveToFirst();
        while (cur.isAfterLast() == false)
        {
            textView.append("\r\n" + cur.getString(1)+"\r\n");
            cur.moveToNext();
        }

        ///////Read data from blob field////////////////////
        cur.moveToFirst();
        byteImage2=cur.getBlob(cur.getColumnIndex("picture"));
        bmImage.setImageBitmap(BitmapFactory.decodeByteArray(byteImage2, 0, byteImage2.length));
        textView.append("\r\n" + byteImage2.length+"\r\n"); 

        //////////////////////////    
        cur.close();
        myDb.close();
  }

  public void DownloadFile() 
  {   
      Bitmap bitmap1 = null;                    
      bitmap1 = BitmapFactory.decodeFile("/sdcard/Dipak/Dipak.jpg"); //weather.png");
      bmImage.setImageBitmap(bitmap1);
  }
}
 public static byte[] getBitmapAsByteArray(Bitmap bitmap, boolean type) {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    if (type) {
        bitmap.compress(CompressFormat.PNG, 0, outputStream);
    } else {
        bitmap.compress(CompressFormat.JPEG, 0, outputStream);
    }
    return outputStream.toByteArray();
}