Android 如何实现SQLite数据库来存储位图图像和文本?

Android 如何实现SQLite数据库来存储位图图像和文本?,android,listview,android-sqlite,notification-listener,Android,Listview,Android Sqlite,Notification Listener,大家好,我正在开发一个android应用程序,它监听传入的whatsapp通知,并使用NotificationListenerService在listView中显示它。我需要sqlite数据库中的帮助来存储通知、检索数据并在listView中显示。数据是一个位图图像和文本字符串。。。 下面是我正在尝试的代码 数据库处理程序 public class DatabaseHandler extends SQLiteOpenHelper{ // Database Version private stat

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

数据库处理程序

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 
现在问题来了。。。。 我只想要这个数据
stringtitle=intent.getStringExtra(“title”);
String text=intent.getStringExtra(“文本”);
字节[]byteArray=intent.getByteArrayExtra(“图标”)
在我的数据库中,我的大脑完全被阻塞了

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();
        }
    }
    };
    }
公共类MainActivity扩展活动{
专用数据库处理程序数据库;
列表视图列表;
自定义列表适配器;
ArrayList模型列表;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
modelList=新的ArrayList();
adapter=新的CustomListAdapter(getApplicationContext(),modelList);
list=(ListView)findViewById(R.id.list);
list.setAdapter(适配器);
LocalBroadcastManager.getInstance(this.registerReceiver)(onNotice,newintentfilter(“Msg”);
}
@凌驾
公共布尔onCreateOptions菜单(菜单){
getMenuInflater().充气(右菜单菜单菜单主菜单);
返回true;
}
@凌驾
公共布尔值onOptionsItemSelected(菜单项项){
开关(item.getItemId()){
案例R.id.action\u设置:
意图=新意图(
“android.settings.ACTION\u NOTIFICATION\u LISTENER\u设置”
);
星触觉(意向);
返回true;
违约:
返回super.onOptionsItemSelected(项目);
}
}
private BroadcastReceiver onNotice=新的BroadcastReceiver(){
@凌驾
公共void onReceive(上下文、意图){
//字符串包=intent.getStringExtra(“包”);
字符串标题=intent.getStringExtra(“标题”);
String text=intent.getStringExtra(“文本”);
//int id=intent.getIntExtra(“图标”,0);
Context-remotePackageContext=null;
试一试{
//remotePackageContext=
getApplicationContext().createPackageContext(包,0);
//可绘制图标=
remotePackageContext.getResources().getDrawable(id);
//如果(图标!=null){
//((图像视图)
findViewById(R.id.imageView)).setBackground(图标);
//}
字节[]byteArray=intent.getByteArrayExtra(“图标”);
//位图bmp=null;
//if(byteArray!=null){
//bmp=BitmapFactory.decodeByteArray(byteArray,0,byteArray.length);
//  }
模型=新模型();
//model.setName(title+“”+text);
//model.setImage(byteArray);
db.addContacts(新型号(标题+“”+文本,byteArray));
Toast.makeText(getApplicationContext(),“已保存”,Toast.LENGTH_LONG.show();
如果(modelList!=null){
添加(模型);
adapter.notifyDataSetChanged();
}否则{
modelList=新的ArrayList();
添加(模型);
adapter=新的CustomListAdapter(getApplicationContext(),modelList);
list=(ListView)findViewById(R.id.list);
list.setAdapter(适配器);
}
}捕获(例外e){
e、 printStackTrace();
}
}
};
}

我认为我做了很多错事我在学习android plz teach me

在SQL中存储
位图
图像实际上是一个不好的想法

我的建议是在线保存图像,并将URL链接保存到数据库中

您可以从数据库中获取URL,并使用
Picasso
()将其显示在应用程序中


另外,请记住在应用程序中请求internet许可以从url加载图像。

在SQL中存储
位图
图像实际上是一个不好的想法

我的建议是在线保存图像,并将URL链接保存到数据库中

您可以从数据库中获取URL,并使用
Picasso
()将其显示在应用程序中


此外,请记住在应用程序中请求internet许可以从url加载图像。

如果图像非常小,则可以通过
android.util.Base64
编码将其转换为
字符串,并将该字符串放入
SQLite
数据库:

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

如果您的图像非常小,您可以通过
android.util.Base64
编码将其转换为
字符串
,并将该字符串放入
SQLite
数据库:

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

按名称创建一个类BitmapBase64.class,并在需要时使用。任何一种转换方式都可以完成

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;
import java.io.ByteArrayOutputStream;

public class BitmapBase64
{
    public static Bitmap convert(String base64Str) throws IllegalArgumentException
    {
        byte[] decodedBytes = Base64.decode(
            base64Str.substring(base64Str.indexOf(",")  + 1),
            Base64.DEFAULT
        );
        return BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.length);
    }

    public static String convert(Bitmap bitmap)
    {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);    
        return Base64.encodeToString(outputStream.toByteArray(), Base64.DEFAULT);
    }    
}
用法:

Bitmap bitmap = BitmapBase64.convert(BASE_64_STRING);

String base64String = BitmapBase64.convert(BITMAP);

但是,如果图像很小,则建议使用在线存储和检索。处理位图时,要小心内存不足,因为这是经常发生的。

按名称创建一个类BitmapBase64.class,并在需要时使用。任何一种转换方式都可以完成

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;
import java.io.ByteArrayOutputStream;

public class BitmapBase64
{
    public static Bitmap convert(String base64Str) throws IllegalArgumentException
    {
        byte[] decodedBytes = Base64.decode(
            base64Str.substring(base64Str.indexOf(",")  + 1),
            Base64.DEFAULT
        );
        return BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.length);
    }

    public static String convert(Bitmap bitmap)
    {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);    
        return Base64.encodeToString(outputStream.toByteArray(), Base64.DEFAULT);
    }    
}
用法:

Bitmap bitmap = BitmapBase64.convert(BASE_64_STRING);

String base64String = BitmapBase64.convert(BITMAP);

但是,如果图像很小,则建议使用在线存储和检索。在处理位图时,请小心内存不足。我建议不要将图像存储在数据库中,因为光标可以存储的最大大小有限制,这可能会导致大型查询的效率低下。最好将映像作为文件存储在应用程序本地存储中,并将引用映像文件的URI存储在db中;(
…用SQLite数据库存储位图图像…
这是个糟糕的主意。有解决方案吗