这是我的源代码是不是从gellery上传图片并保存在sql lite中请帮帮我,我做错了什么?我读了这个示例代码http://androidhub4you.blogspot.com/2012/09/hello-friends-today-i-am-going-to-share.html是采取硬代码图像我在此代码中添加浏览按钮从自己选择和显示图像
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
public class SQLiteDemoActivity extends Activity {
final int SELECT_PHOTO = 0;
ArrayList<Contact> imageArry = new ArrayList<Contact>();
ContactImageAdapter adapter;
Button BrowseButton;
DataBaseHandler db;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
db = new DataBaseHandler(this);
//get image from drawable
//Bitmap image = BitmapFactory.decodeResource(getResources(),R.drawable.facebook);
BrowseButton=(Button)findViewById(R.id.BrowseButton);
BrowseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
// in onCreate or any event where your want the user to
// select a file
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent
imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case SELECT_PHOTO:
if(resultCode == RESULT_OK){
Uri selectedImage = imageReturnedIntent.getData();
InputStream imageStream = null;
try {
imageStream = getContentResolver().openInputStream(
selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap bmp = BitmapFactory.decodeStream(imageStream);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] imageInByte = stream.toByteArray();
Log.d("Insert: ", "Inserting ..");
db.addContact(new Contact("FaceBook", imageInByte));
//display main List view bcard and contact name
//Reading all contacts from database
List<Contact> contacts = db.getAllContacts();
for (Contact cn : contacts) {
String log = "ID:" + cn.getID() + " Name: " + cn.getName()
+ " ,Image: " + cn.getImage();
//Writing Contacts to log
Log.d("Result: ", log);
//add contacts data in arrayList
imageArry.add(cn);
}
adapter = new ContactImageAdapter(this, R.layout.screen_list,
imageArry);
ListView dataList = (ListView) findViewById(R.id.list);
dataList.setAdapter(adapter);
try {
stream.close();
stream = null;
} catch (IOException e) {
e.printStackTrace();
}
//convert bitmap to byte
}
}
}
}
private static final int DATABASE_VERSION = 1;
//Database Name
private static final String DATABASE_NAME = "imagedb";
//Contacts table name
private static final String TABLE_CONTACTS = "contacts";
//Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_IMAGE = "image";
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_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_IMAGE + " BLOB" + ")";
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_CONTACTS);
//Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
public// Adding new contact
void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact._name); // Contact Name
values.put(KEY_IMAGE, contact._image); // Contact Phone
//Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
//Getting single contact
Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_IMAGE }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getBlob(1));
//return contact
return contact;
}
//Getting All Contacts
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
//Select All Query
String selectQuery = "SELECT * FROM contacts ORDER BY name";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
//looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setImage(cursor.getBlob(2));
//Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
//close inserting data from database
db.close();
//return contact list
return contactList;
}
//Updating single contact
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_IMAGE, contact.getImage());
//updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}
//Deleting single contact
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
db.close();
}
//Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
//return count
return cursor.getCount();
}
}
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class ContactImageAdapter extends ArrayAdapter<Contact>{
Context context;
int layoutResourceId;
//BcardImage data[] = null;
ArrayList<Contact> data=new ArrayList<Contact>();
public ContactImageAdapter(Context context, int layoutResourceId, ArrayList<Contact>
data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ImageHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ImageHolder();
holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle);
holder.imgIcon = (ImageView)row.findViewById(R.id.imgIcon);
row.setTag(holder);
}
else
{
holder = (ImageHolder)row.getTag();
}
Contact picture = data.get(position);
holder.txtTitle.setText("facebook");
//convert byte to bitmap take from contact class
byte[] outImage=picture._image;
ByteArrayInputStream imageStream = new ByteArrayInputStream(outImage);
Bitmap theImage = BitmapFactory.decodeStream(imageStream);
holder.imgIcon.setImageBitmap(theImage);
return row;
}
static class ImageHolder
{
ImageView imgIcon;
TextView txtTitle;
}
}
public class Contact {
// private variables
int _id;
String _name;
byte[] _image;
// Empty constructor
public Contact() {
}
// constructor
public Contact(int keyId, String name, byte[] image) {
this._id = keyId;
this._name = name;
this._image = image;
}
// constructor
public Contact(String contactID, String name, byte[] image) {
this._name = name;
this._image = image;
}
// constructor
public Contact(String name, byte[] image) {
this._name = name;
this._image = image;
}
// getting ID
public int getID() {
return this._id;
}
// setting id
public void setID(int keyId) {
this._id = keyId;
}
// getting name
public String getName() {
return this._name;
}
// setting name
public void setName(String name) {
this._name = name;
}
// getting phone number
public byte[] getImage() {
return this._image;
}
// setting phone number
public void setImage(byte[] image) {
this._image = image;
}
}
答案 0 :(得分:0)
Are you got any solution or not? I am owner of given above URL "Androidhub4you.com".
If you still stuck please try my idea just make a new activity and add button for take picture from camera or gallery what ever you want after that pass this image to next activity through Intent and get it some thing like that-
Intent intent=getIntent();
Bitmap photo = intent.getExtra("image");
and now use this bitmap to instead of below Bitmap image.
DataBaseHandler db = new DataBaseHandler(this);
// get image from drawable
Bitmap image = BitmapFactory.decodeResource(getResources(),
R.drawable.facebook);
Here I can't post my blog url but you can search on my blog for camera/gallery code. Just merge two code.
试试以下链接希望它能帮助您 - Click here!
Thanks,
答案 1 :(得分:0)
mdb=new MyDataBase(getApplicationContext());
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, PICK_PHOTO_REQUEST_CODE);
} });
breg.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
db=mdb.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put("image", img);
db.insert("tableimage", null, cv);
Toast.makeText(MainActivity.this, "inserted successfully", Toast.LENGTH_SHORT).show() }
});
bselect.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
db=mdb.getWritableDatabase();
String[] col={"image"};
c=db.query("tableimage", col, null, null, null, null, null);
if(c!=null){
c.moveToFirst();
do{
img=c.getBlob(c.getColumnIndex("image"));
}while(c.moveToNext());
}
Bitmap b1=BitmapFactory.decodeByteArray(img, 0, img.length);
imge.setImageBitmap(b1) } });
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_PHOTO_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
Uri chosenImageUri = data.getData();
selectedImagePath = getPath(chosenImageUri); //for getting the image path
image.setVisibility(View.VISIBLE);
image.setImageURI(chosenImageUri);
String[] filePathColumn = { MediaStore.Images.Media.DATA };
System.out.println("reached......2");
Cursor cursor = getContentResolver().query(chosenImageUri,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);
// testimage.setImageBitmap(yourSelectedImage);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
yourSelectedImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
img = stream.toByteArray();
System.out.println("****************"+img.toString());
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
MyDataBase .java
public class MyDataBase extends SQLiteOpenHelper{
private static String dbname="images";
private static int dbversion=2;
public MyDataBase(Context context) {
super(context, dbname, null, dbversion);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table tableimage(image blob);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists tableimage");
onCreate(db);
}
}