如何实现SQLite数据库存储位图图像和文本? [英] How to implement SQLite database to store Bitmap Image and Text?

查看:129
本文介绍了如何实现SQLite数据库存储位图图像和文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我正在开发一个Android应用程序,该应用程序侦听传入的whatsapp通知,并使用NotificationListenerService在listView中显示它.我在sqlite数据库中需要帮助来存储通知和检索数据并在listView中显示.数据是一个位图图像和文本字符串... 以下是我正在尝试的代码.

hello all i am developing an android application which listen to incoming whatsapp notification and show it in listView using NotificationListenerService. i need help in sqlite database to store notifications and retrieve data and show in listView. data is one Bitmap image and text string... following is code am trying..

databaseHandler

databaseHandler

public class DatabaseHandler extends SQLiteOpenHelper{
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "wnoti";
//  table name
private static final String TABLE_NOTI = "noti";
//table attributes
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_POTO = "poto";

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

}
//create table
@Override
public void onCreate(SQLiteDatabase db){
    String CREATE_TABLE=" CREATE TABLE "+TABLE_NOTI + "("
            + KEY_ID +" INTEGER PRIMARY KEY,"
            + KEY_NAME +" TEXT,"
            + KEY_POTO  +" BLOB" + ")";
    db.execSQL(CREATE_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_NOTI);

    // Create tables again
    onCreate(db);
}
//Insert values to the table contacts
public void addContacts(Model model){
    SQLiteDatabase db = this.getReadableDatabase();
    ContentValues values=new ContentValues();

    values.put(KEY_NAME, model.getName());
    values.put(KEY_POTO, model.getImage());


    db.insert(TABLE_NOTI, null, values);
    db.close();
}

public List<Model> getAllnoti() {
    List<Model> notiList = new ArrayList<Model>();
    // Select All Query
    String selectQuery = "SELECT  * FROM " + TABLE_NOTI;

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

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            Model model = new Model();
            model.setID(Integer.parseInt(cursor.getString(0)));
            model.setName(cursor.getString(1));
            model.setImage(cursor.getBlob(2));


            // Adding notification to list
            notiList.add(model);
        } while (cursor.moveToNext());
    }

    // return notification list
    return notiList;
}
}


my model class 

在没有sqlite数据库的情况下我第一次使用Bitmap imaBitmap 然后我将其更改为byte [] ...

1st when i am working without sqlite database i use Bitmap imaBitmap then i change it to byte[]...

public class Model {
String name;
byte[] imaBitmap;
int _id;

public Model(){

}
public Model(int id,String name,byte[] imaBitmap)
{
    this._id=id;
    this.name=name;
    this.imaBitmap=imaBitmap;
}
public Model(String name,byte[] imaBitmap){
    this.name=name;
    this.imaBitmap=imaBitmap;
}
// getting ID
public int getID(){
    return this._id;
}

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

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public byte[] getImage() {
    return imaBitmap;
}

public void setImage(byte[] imaBitmap) {
    this.imaBitmap = imaBitmap;
}
}

现在这是问题所在... 我只想要此数据String title = intent.getStringExtra("title"); String text = intent.getStringExtra("text"); byte[] byteArray = intent.getByteArrayExtra("icon"); 进入我的数据库,我的脑子完全被挡住了.........

now here is the problem.... i just want this dataString title = intent.getStringExtra("title"); String text = intent.getStringExtra("text"); byte[] byteArray = intent.getByteArrayExtra("icon"); into my db my mind is totally blocked..................

public class MainActivity extends Activity {
  private DatabaseHandler db;
ListView list;
CustomListAdapter adapter;
ArrayList<Model> modelList;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    modelList = new ArrayList<Model>();
    adapter = new CustomListAdapter(getApplicationContext(), modelList);
    list = (ListView) findViewById(R.id.list);
    list.setAdapter(adapter);
    LocalBroadcastManager.getInstance(this).registerReceiver(onNotice, new IntentFilter("Msg"));

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.action_settings:
            Intent intent = new Intent(
                    "android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"
            );
            startActivity(intent);
            return true;
        default:
            return super.onOptionsItemSelected(item);

    }
}

private BroadcastReceiver onNotice = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        // String pack = intent.getStringExtra("package");
        String title = intent.getStringExtra("title");
        String text = intent.getStringExtra("text");
        //int id =intent.getIntExtra("icon",0);
        Context remotePackageContext = null;
        try {
        //                    remotePackageContext = 
        getApplicationContext().createPackageContext(pack, 0);
        //                Drawable icon = 
         remotePackageContext.getResources().getDrawable(id);
        //                if(icon !=null) {
       //                    ((ImageView) 
          findViewById(R.id.imageView)).setBackground(icon);
            //}
            byte[] byteArray = intent.getByteArrayExtra("icon");
         //   Bitmap bmp = null;
          //  if (byteArray != null) {
           //     bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);

          //  }

            Model model = new Model();
          //  model.setName(title + "" + text);
           // model.setImage(byteArray);
              db.addContacts(new Model(title + "" + text,byteArray));
            Toast.makeText(getApplicationContext(),"Saved ",Toast.LENGTH_LONG).show();

            if (modelList != null) {
                modelList.add(model);
                adapter.notifyDataSetChanged();
            } else {
                modelList = new ArrayList<Model>();
                modelList.add(model);
                adapter = new CustomListAdapter(getApplicationContext(), modelList);
                list = (ListView) findViewById(R.id.list);
                list.setAdapter(adapter);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    };
    }

我认为我做错了很多事情,我正在学习android plz教我

i think i am doing many things wrong i am learning android plz teach me

推荐答案

如果图像很小,则可以通过android.util.Base64编码将其隐藏在String中,并将此字符串放入在SQLite数据库中:

If your image is really small you can covert it in a String by means of android.util.Base64 encoding and put this string in SQLite database:

public static String getPngAsString(Bitmap bitmap){
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 0, bos);
    byte[] bitmapBytes = bos.toByteArray();
    return Base64.encodeToString(bitmapBytes, Base64.NO_WRAP);
}

这篇关于如何实现SQLite数据库存储位图图像和文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆