SQLite数据库Android中的图像上传

SQLite数据库Android中的图像上传,android,sqlite,android-gallery,Android,Sqlite,Android Gallery,我有谷歌关于如何插入。但我得不到任何正确的答案。 我必须将图片从gallery插入sqlite数据库。我已尝试。但无法执行图像插入 公共类MainActivity扩展AppCompativeActivity实现AdapterView.OnItemSelectedListener、View.OnClickListener{ private static final int SELECT_PICTURE = 1; protected static ImageView imPhoto; Databas

我有谷歌关于如何插入。但我得不到任何正确的答案。 我必须将图片从gallery插入sqlite数据库。我已尝试。但无法执行图像插入

公共类MainActivity扩展AppCompativeActivity实现AdapterView.OnItemSelectedListener、View.OnClickListener{

private static final int SELECT_PICTURE = 1;
protected static ImageView imPhoto;
DatabaseHelperAdapter databaseHelperAdapter;

Button btnSubmit;

private String selectedImagePath;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ActionBar actionBar = getSupportActionBar();
    actionBar.setTitle("Register");

    databaseHelperAdapter = new DatabaseHelperAdapter(this);



    imPhoto = (ImageView) findViewById(R.id.imPhoto);


    imPhoto.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(
                    Intent.createChooser(intent, "Select Picture"),
                    SELECT_PICTURE);
        }
    });
}

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_PICTURE) {
            Uri selectedImageUri = data.getData();
            selectedImagePath = getPath(selectedImageUri);
            System.out.println("Image Path : " + selectedImagePath);
            imPhoto.setVisibility(View.VISIBLE);
            imPhoto.setImageURI(selectedImageUri);
        }
    }
}

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);
}






//Insert into database
public void addUser(View view) throws IOException {



    byte[] byteImage1;
    FileInputStream instream = new FileInputStream(selectedImagePath);
    BufferedInputStream bif = new BufferedInputStream(instream);
    byteImage1 = new byte[bif.available()];
    bif.read(byteImage1);





    byte[] image = byteImage1;

    long id = databaseHelperAdapter.insertData(fname, lname, password, email, birthday, gender, image);

    if (id < 0) {

        Message.message(this, "Record not inserted");
    } else {
        Intent intent = new Intent(MainActivity.this, Welcome.class);
        startActivity(intent);
        Message.message(this, "Record Inserted Successfully");
    }
}


}
private static final int SELECT\u PICTURE=1;
受保护的静态图像视图imPhoto;
DatabaseHelperAdapter DatabaseHelperAdapter;
按钮BTN提交;
私有字符串selectedImagePath;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar ActionBar=getSupportActionBar();
actionBar.setTitle(“登记簿”);
databaseHelperAdapter=新的databaseHelperAdapter(此);
imPhoto=(ImageView)findViewById(R.id.imPhoto);
imPhoto.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
意图=新意图();
intent.setType(“image/*”);
intent.setAction(intent.ACTION\u GET\u CONTENT);
startActivityForResult(
Intent.createChooser(Intent,“选择图片”),
选择(图片),;
}
});
}
ActivityResult上的公共void(int请求代码、int结果代码、意图数据){
if(resultCode==RESULT\u OK){
if(requestCode==选择图片){
Uri selectedImageUri=data.getData();
selectedImagePath=getPath(selectedImageUri);
System.out.println(“图像路径:”+selectedImagePath);
imPhoto.setVisibility(View.VISIBLE);
imPhoto.setImageURI(selectedImageUri);
}
}
}
公共字符串getPath(Uri){
字符串[]投影={MediaStore.Images.Media.DATA};
Cursor Cursor=managedQuery(uri、投影、null、null、null);
int column_index=游标
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
返回cursor.getString(列索引);
}
//插入数据库
public void addUser(视图)引发IOException{
字节[]byteImage1;
FileInputStream instream=新的FileInputStream(selectedImagePath);
BufferedInputStream bif=新的BufferedInputStream(流内);
byteImage1=新字节[bif.available()];
读取(byteImage1);
字节[]图像=字节图像1;
long id=databaseHelperAdapter.insertData(fname、lname、密码、电子邮件、生日、性别、图像);
if(id<0){
消息。消息(本“未插入记录”);
}否则{
意图=新意图(MainActivity.this、Welcome.class);
星触觉(意向);
Message.Message(此为“已成功插入的记录”);
}
}
}
2] 数据库文件

import java.sql.Blob;

public class DatabaseHelperAdapter {

    public SQLiteDatabase db;
    DatabaseHelper helper;

    public DatabaseHelperAdapter(Context context) {
        helper = new DatabaseHelper(context);
    }

    public long insertData(String fname, String lname, String password, String email, String birthday, String gender, byte[] image) {
        SQLiteDatabase sqLiteDatabase = helper.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(DatabaseHelper.FNAME, fname);
        contentValues.put(DatabaseHelper.LNAME, lname);
        contentValues.put(DatabaseHelper.PASSWORD, password);
        contentValues.put(DatabaseHelper.EMAIL, email);
        contentValues.put(DatabaseHelper.BIRTHDAY, birthday);
        contentValues.put(DatabaseHelper.GENDER, gender);
        contentValues.put(DatabaseHelper.IMAGE, String.valueOf(image));

        long id = sqLiteDatabase.insert(DatabaseHelper.TABLE_NAME, null, contentValues);
        sqLiteDatabase.close();
        return id;
    }

    public String getSinlgeEntry(String email) {
        SQLiteDatabase sqLiteDatabase = helper.getWritableDatabase();
        Cursor cursor = sqLiteDatabase.query(DatabaseHelper.TABLE_NAME, null, DatabaseHelper.EMAIL + " =?", new String[]{email}, null, null, null);
        if (cursor.getCount() < 1) // UserName Not Exist
        {
            cursor.close();
            return "NOT EXIST";
        }
        cursor.moveToFirst();
        String password = cursor.getString(cursor.getColumnIndex(DatabaseHelper.PASSWORD));
        cursor.close();
        return password;
    }

    public DatabaseHelperAdapter open() {

        db = helper.getWritableDatabase();
        return this;
    }

    public void close() {
        db.close();
    }

    class DatabaseHelper extends SQLiteOpenHelper {
        private static final String DATABASE_NAME = "LoginForm";
        private static final String TABLE_NAME = "LoginTable";
        private static final int DATABASE_VERSION = 2;
        private static final String UID = "_id";
        private static final String FNAME = "FName";
        private static final String LNAME = "LName";
        private static final String PASSWORD = "Password";
        private static final String EMAIL = "Email";
        private static final String BIRTHDAY = "Birthday";
        private static final String GENDER = "Gender";
        private static final String IMAGE = "Image";


        private static final String CREATE_TABLE = " CREATE TABLE " + TABLE_NAME + " ( " + UID + " INTEGER PRIMARY KEY AUTOINCREMENT , "
                + FNAME + " VARCHAR(255) , "
                + LNAME + " VARCHAR(255) ,"
                + PASSWORD + " text ,"
                + EMAIL + " VARCHAR(255) UNIQUE ,"
                + BIRTHDAY + " VARCHAR(255) ,"
                + GENDER + " VARCHAR(255)"
                + IMAGE +" BLOB );";
        private static final String DROP_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME;
        private Context context;


        public DatabaseHelper(Context context) {

            super(context, DATABASE_NAME, null, DATABASE_VERSION);
            this.context = context;
            Message.message(context, "Constructor is called");
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            try {

                db.execSQL(CREATE_TABLE);
                Message.message(context, "onCreate is called");
            } catch (SQLException e) {
                Message.message(context, "" + e);
            }
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

            try {
                Message.message(context, "onUpdates is called");
                db.execSQL(DROP_TABLE);
                onCreate(db);
            } catch (SQLException e) {
                Message.message(context, "" + e);
            }

        }

    }
}
导入java.sql.Blob;
公共类数据库HelperAdapter{
公共数据库数据库;
数据库助手;
公共数据库HelperAdapter(上下文){
helper=新数据库helper(上下文);
}
公共长插入数据(字符串fname、字符串lname、字符串密码、字符串电子邮件、字符串生日、字符串性别、字节[]图像){
SQLiteDatabase SQLiteDatabase=helper.getWritableDatabase();
ContentValues ContentValues=新ContentValues();
contentValues.put(DatabaseHelper.FNAME,FNAME);
contentValues.put(DatabaseHelper.LNAME,LNAME);
contentValues.put(DatabaseHelper.PASSWORD,PASSWORD);
contentValues.put(DatabaseHelper.EMAIL,EMAIL);
contentValues.put(DatabaseHelper.BIRTHDAY,BIRTHDAY);
contentValues.put(DatabaseHelper.GENDER,GENDER);
contentValues.put(DatabaseHelper.IMAGE,String.valueOf(IMAGE));
long id=sqLiteDatabase.insert(DatabaseHelper.TABLE_NAME,null,contentValues);
sqLiteDatabase.close();
返回id;
}
公共字符串getSinlgeEntry(字符串电子邮件){
SQLiteDatabase SQLiteDatabase=helper.getWritableDatabase();
Cursor Cursor=sqLiteDatabase.query(DatabaseHelper.TABLE_NAME,null,DatabaseHelper.EMAIL+“=?”,新字符串[]{EMAIL},null,null,null);
if(cursor.getCount()<1)//用户名不存在
{
cursor.close();
返回“不存在”;
}
cursor.moveToFirst();
字符串密码=cursor.getString(cursor.getColumnIndex(DatabaseHelper.password));
cursor.close();
返回密码;
}
公共数据库HelperAdapter open(){
db=helper.getWritableDatabase();
归还这个;
}
公众假期结束(){
db.close();
}
类DatabaseHelper扩展了SQLiteOpenHelper{
私有静态最终字符串数据库\u NAME=“LoginForm”;
私有静态最终字符串表\u NAME=“LoginTable”;
私有静态最终int数据库_VERSION=2;
私有静态最终字符串UID=“\u id”;
私有静态最终字符串FNAME=“FNAME”;
私有静态最终字符串LNAME=“LNAME”;
私有静态最终字符串PASSWORD=“PASSWORD”;
私有静态最终字符串EMAIL=“EMAIL”;
私有静态最终字符串birth=“birth”;
私有静态最终字符串GENDER=“GENDER”;
私有静态最终字符串IMAGE=“IMAGE”;
私有静态最终字符串CREATE_TABLE=“CREATE TABLE”+TABLE_NAME+”(“+UID+”整数主键自动递增,“
+FNAME+“VARCHAR(255),”
+LNAME+“VARCHAR(255),”
+密码+文本,“
+电子邮件+“VARCHAR(255)唯一”
+生日+“瓦尔查尔(255),”
+性别+“VARCHAR(255)”
+图像+“BLOB);”;
私有静态最终字符串DROP\u TABLE=“DROP TABLE IF EXISTS”+TABLE\u NAME;
私人语境;
公共数据库助手(上下文){
super(上下文、数据库名称、null、数据库版本);
this.context=上下文;
 Caused by: java.lang.reflect.InvocationTargetException
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at android.view.View$1.onClick(View.java:4002)
            at android.view.View.performClick(View.java:4756)
            at android.view.View$PerformClick.run(View.java:19749)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'char[] java.lang.String.toCharArray()' on a null object reference
            at java.io.File.fixSlashes(File.java:185)
            at java.io.File.<init>(File.java:134)
            at java.io.FileInputStream.<init>(FileInputStream.java:103)
            at com.example.zeronesnatik.loginform11.MainActivity.addUser(MainActivity.java:170)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at android.view.View$1.onClick(View.java:4002)
            at android.view.View.performClick(View.java:4756)
            at android.view.View$PerformClick.run(View.java:19749)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
09-18 13:01:42.903    2178-2532/? W/ActivityManager﹕ Force finishing activity com.example.zeronesnatik.loginform11/.MainActivity
09-18 13:01:42.962    2178-7631/? I/OpenGLRenderer﹕ Initialized EGL, version 1.4
09-18 13:01:42.973    2178-7631/? W/EGL_emulation﹕ eglSurfaceAttrib not implemented
09-18 13:01:42.973    2178-7631/? W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0x9deff340, error=EGL_SUCCESS
09-18 13:01:43.420    2178-2199/? W/ActivityManager﹕ Activity pause timeout for ActivityRecord{3e0c9d7b u0 com.example.zeronesnatik.loginform11/.MainActivity t43 f}
09-18 13:01:44.059    2178-2334/? W/AudioTrack﹕ AUDIO_OUTPUT_FLAG_FAST denied by client
contentValues.put(DatabaseHelper.IMAGE, String.valueOf(image));
SQLiteStatement insertStmt      =   db.compileStatement("INSERT INTO ....");
insertStmt.clearBindings();
insertStmt.bindBlob(3, (byte[])yourImageData);
insertStmt.executeInsert();