Android Studio:本机无法创建新字节[]

时间:2019-03-09 18:54:25

标签: android sqlite bitmap blob

我正在开发一个应用程序,其中必须在SQLite中存储图片和文本,然后检索它们。 我所做的:从相机拍摄照片,对位图进行编码,然后将其保存在blob中。 实际上,我收到此代码错误:Native无法创建新的字节[]。

这是我的数据库类:

public DiaryDatabaseHandler(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
    super(context, DB_NAME, factory, DB_VERSION);


}

@Override
public void onCreate(SQLiteDatabase db) {

    String createDb = "CREATE TABLE "+TABLE_NAME+" ( "+
            COLUMN_ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+
            COLUMN_USERID+ " INTEGER, "+
            COLUMN_TITLE+ " TEXT, "+
            COLUMN_DESCRIPTION+ " TEXT, "+
            COLUMN_PHOTO+ " BLOB NOT NULL);";
    db = getWritableDatabase();
    db.execSQL(createDb);

}

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

    db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);


}

public void addToDiary(diaryObject diaryToAdd){

    SQLiteDatabase db;
    ContentValues cv = new ContentValues();
    cv.put(COLUMN_USERID, diaryToAdd.getUserId());
    cv.put(COLUMN_TITLE,diaryToAdd.getTitle());
    cv.put(COLUMN_DESCRIPTION, diaryToAdd.getDescription());
    cv.put(COLUMN_PHOTO, diaryToAdd.getPhotoEncoded());
    db = getWritableDatabase();
    db.insert(TABLE_NAME,null,cv);
    db.close();

}

public ArrayList<diaryObject> getUserDiary(int userId){

    ArrayList<diaryObject> diaryList = new ArrayList<>();
    SQLiteDatabase db = getWritableDatabase();
    String selectQuery = "SELECT * FROM "+TABLE_NAME+" WHERE "+COLUMN_USERID+" = "+userId+";";
    Cursor cursor = db.rawQuery(selectQuery,null);
    diaryObject diaryToAdd;
    cursor.moveToFirst();

    while(!cursor.isAfterLast()){

        diaryToAdd = new diaryObject();
        diaryToAdd.setUserId(cursor.getInt(cursor.getColumnIndex(COLUMN_USERID)));
        diaryToAdd.setTitle(cursor.getString(cursor.getColumnIndex(COLUMN_TITLE)));
        diaryToAdd.setDescription(cursor.getString(cursor.getColumnIndex(COLUMN_DESCRIPTION)));
        diaryToAdd.setPhotoEncoded(cursor.getBlob(cursor.getColumnIndex(COLUMN_PHOTO)));
        diaryList.add(diaryToAdd);
    }


    cursor.close();
    return diaryList;

}

}

这是我需要存储的对象:

    public diaryObject(byte[] photo, String title, String description, int userId){

    this.photoEncoded = photo;
    this.title = title;
    this.description = description;
    this.userId = userId;


}

然后在此片段中,我提取文字和图片并将其存储在数据库中:

    public void setTitleDescription(){

    String title = titleText.getText().toString();
    String description = descText.getText().toString();
    byte[] picture = encodeBitmap();
    diaryObject diaryToAdd = new diaryObject();
    diaryToAdd.setUserId(SharedPrefManager.getInstance(getActivity()).getId());
    diaryToAdd.setTitle(title);
    diaryToAdd.setDescription(description);
    diaryToAdd.setPhotoEncoded(picture);
    dbHandler.addToDiary(diaryToAdd);

}

public void getPhoto(){
    Intent picIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(picIntent,0);

}

public byte[] encodeBitmap(){
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 0, baos);
    return baos.toByteArray();
}

在此片段中,我显示了列表:

public class UserDiaryList extends Fragment {
private ConstraintLayout layout;
private Button addToDiary;
private ListView diaryListView;
private CustomArrayAdapterDiary diaryAdapter;
public diaryObject diaryToOpen;
public static ArrayList<diaryObject> diaryList;

DiaryDatabaseHandler dbHandler;

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    return inflater.inflate(R.layout.user_list_fragment, null);
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    inizializeComponent();


    addToDiary.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Fragment fragment = new UserAddDiaryFragment();
            FragmentManager manager = getFragmentManager();
            manager.beginTransaction()
                    .replace(R.id.fragmentView, fragment)
                    .commit();

        }
    });

    diaryListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            diaryToOpen = (diaryObject)parent.getItemAtPosition(position);
            OpenDiaryFragment.setDiaryObject(diaryToOpen);
            FragmentManager manager = getFragmentManager();
            manager.beginTransaction()
                    .replace(R.id.fragmentView,new OpenDiaryFragment())
                    .commit();
        }
    });



}

public void inizializeComponent(){

    dbHandler = new DiaryDatabaseHandler(getActivity(),null,null,1);


    diaryList = dbHandler.getUserDiary(SharedPrefManager.getInstance(getActivity()).getId());
    if (diaryList == null){
        diaryList = new ArrayList<>();
    }
    addToDiary = getView().findViewById(R.id.buttonAddToDiary);
    diaryListView = getView().findViewById(R.id.listViewDiary);
    diaryAdapter = new CustomArrayAdapterDiary(getActivity(),diaryList);
    diaryListView.setAdapter(diaryAdapter);

    layout = getView().findViewById(R.id.constraintDiaryList);
}

}

这是适配器:

public class CustomArrayAdapterDiary extends ArrayAdapter<diaryObject> {

private Context mContext;
private ArrayList<diaryObject> diaryList = new ArrayList<>();
private long startClickTime;
public CustomArrayAdapterDiary(@NonNull Context context, ArrayList<diaryObject> list) {
    super(context, 0 , list);
    mContext = context;
    diaryList = list;
}

@NonNull
@Override
public View getView(int position, @Nullable final View convertView, @NonNull ViewGroup parent) {
    View listItem = convertView;
    if(listItem == null){
        listItem = LayoutInflater.from(mContext).inflate(R.layout.diary_custom_adapter,parent,false);
    }


    final diaryObject currentDiary = diaryList.get(position);

    ImageView image = (ImageView)listItem.findViewById(R.id.imageViewDiary);
    byte[] imageAsBytes = currentDiary.getPhotoEncoded();
    ByteArrayInputStream imageStream = new ByteArrayInputStream(imageAsBytes);
    Bitmap imageB = BitmapFactory.decodeStream(imageStream);
    image.setImageBitmap(imageB);

    TextView title = (TextView) listItem.findViewById(R.id.textViewDiaryTitle);
    title.setText(currentDiary.getTitle());

    TextView description = (TextView) listItem.findViewById(R.id.textViewDiaryDescription);
    description.setText(currentDiary.getDescription());


    return listItem;
}

}

错误在以下代码行给出:

diaryToAdd.setPhotoEncoded(cursor.getBlob(cursor.getColumnIndex(COLUMN_PHOTO)));

当我尝试加载byte []时,它位于databseHandler类中。

我不明白问题是什么。我将不胜感激任何答复和建议。

0 个答案:

没有答案