这是我的下面的代码,浏览图像gellery和选择图像,但如何在数据库中插入图像视图?这个代码成功显示在屏幕上选中的图像但不存储在数据库中如何传递图像参数?在那一行我评论/ 我在这里写的东西 /
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
public class AddEditCountry extends Activity {
private long rowID;
private EditText nameEt;
private EditText capEt;
private EditText codeEt;
private EditText Donedate;
private EditText Notes;
private EditText Person;
private ImageView imageView1;
Bitmap yourSelectedImage;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.add_country);
nameEt = (EditText) findViewById(R.id.Address);
capEt = (EditText) 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);
Button Browse = (Button) findViewById(R.id.Browse);
Browse.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 0);
}
});
Bundle extras = getIntent().getExtras();
if (extras != null)
{
rowID = extras.getLong("row_id");
nameEt.setText(extras.getString("name"));
capEt.setText(extras.getString("cap"));
codeEt.setText(extras.getString("code"));
Donedate.setText(extras.getString("Location"));
Notes.setText(extras.getString("Notes"));
Person.setText(extras.getString("Person"));
imageView1.setImageURI(yourSelectedImage);
}
Button saveButton =(Button) findViewById(R.id.saveBtn);
saveButton.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
if (nameEt.getText().length() != 0)
{
AsyncTask<Object, Object, Object> saveContactTask =
new AsyncTask<Object, Object, Object>()
{
@Override
protected Object doInBackground(Object... params)
{
saveContact();
return null;
}
@Override
protected void onPostExecute(Object result)
{
finish();
}
};
saveContactTask.execute((Object[]) null);
}
else
{
AlertDialog.Builder alert = new
AlertDialog.Builder(AddEditCountry.this);
alert.setTitle(R.string.errorTitle);
alert.setMessage(R.string.errorMessage);
alert.setPositiveButton(R.string.errorButton, null);
alert.show();
}
}
});
}
private void saveContact()
{
DatabaseConnector dbConnector = new DatabaseConnector(this);
if (getIntent().getExtras() == null)
{
/* what i write here for image*/
dbConnector.insertContact(nameEt.getText().toString(),
capEt.getText().toString(),
codeEt.getText().toString(),
Donedate.getText().toString(),
Notes.getText().toString(),
Person.getText().toString(), null
);
}
else
/* what i wirte here for image*/ {
dbConnector.updateContact(rowID,
nameEt.getText().toString(),
capEt.getText().toString(),
codeEt.getText().toString(),
Donedate.getText().toString(),
Notes.getText().toString(),
Person.getText().toString(), null
);
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case 0:
if(resultCode == RESULT_OK){
Uri selectedImage = imageReturnedIntent.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex); // file path of selected image
cursor.close();
// Convert file path into bitmap image using below line.
yourSelectedImage = BitmapFactory.decodeFile(filePath);
// put bitmapimage in your imageview
imageView1.setImageBitmap(yourSelectedImage);
}
}
}
}
答案 0 :(得分:1)
首先在sqlite中创建字段为blob数据类型
获取字节并存储在数据库image.getBytes();
中或者如果你有位图而不是转换成字节数组
并存储到数据库
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();
}
答案 1 :(得分:0)
请使用以下代码将商店图片存入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);
}
}
答案 2 :(得分:0)
我建议避免将图像保存到数据库,而不仅仅是在android上。
这是有道理的,因为它会减慢与数据库相关的任何事情。此外,光标将无法缓存结果,以便在表的行之间移动。
相反,将文件名设置为指向应用存储空间的路径。您还可以添加它存储的位置(内部/外部存储)。