gpt4 book ai didi

android - 如何在 SQLite (Android) 中存储 Drawable/Bitmap

转载 作者:行者123 更新时间:2023-11-29 00:21:08 25 4
gpt4 key购买 nike

我想通过 CreateActivity 中的 Bundle 传递 Drawable 的 Int 值。从这个 Int 值(资源 ID)我想用它来创建一个存储在 SQLLITE 数据库中的事件对象。当程序生成 ListView 时,它应该能够使用此 Int 值将其关联的 Drawable 分配给 ListView 的一部分。

**我应该怎么做才能将 Drawable 存储在 SQLite 数据库中或至少将 INT 值存储在数据库中? **

主要 Activity

public class MainActivity extends FragmentActivity implements OnClickListener {

ListView listView;
int lastIndex = -1;
ArrayList<Event> lstEvents = new ArrayList<Event>();

// detail view
TextView tvTitle, tvTime, tvDate;
ImageView ivPic;
View vw_master;

boolean _isBack = true;

ImageButton add;

String title;
String date;
String time;
int resId;

static final int PICK_CONTACT_REQUEST = 0;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

// // get detail controls
tvTitle = (TextView) findViewById(R.id.textViewTitle);
tvDate = (TextView) findViewById(R.id.textViewDate);
tvTime = (TextView) findViewById(R.id.textViewTime);
ivPic = (ImageView) findViewById(R.id.imageView1);

add = (ImageButton) findViewById(R.id.add);
add.setOnClickListener(this);


/////////////////////////////////LISTVIEW////////////////////////////////////////
// Create the adapter to convert the array to views
EventAdapter adapter = new EventAdapter(this, lstEvents);

// attach adapter to a list view
listView = (ListView) findViewById(R.id.listViewFragment);
listView.setAdapter(adapter);
/////////////////////////////////LISTVIEW////////////////////////////////////////




// /////////////////////////////DATABASE/////////////////////////////////////////////
DatabaseHandler db = new DatabaseHandler(this);
// /////////////////////////////DATABASE/////////////////////////////////////////////

List<Event> events = db.getAllContacts();

adapter.addAll(events);
adapter.notifyDataSetChanged();






}

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.add:
Intent intent = new Intent(this, CreateActivity.class);
startActivityForResult(intent, 100);
break;
}
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

// /////////////////////////////DATABASE/////////////////////////////////////////////
DatabaseHandler db = new DatabaseHandler(this);
// /////////////////////////////DATABASE/////////////////////////////////////////////

// Create the adapter to convert the array to views
EventAdapter adapter = new EventAdapter(this, lstEvents);

// attach adapter to a list view
listView = (ListView) findViewById(R.id.listViewFragment);
listView.setAdapter(adapter);

if (requestCode == 100) {
if (resultCode == RESULT_OK) {
Bundle b = data.getExtras();
title = b.getString("TITLE");
time = b.getString("TIME");
date = b.getString("DATE");

// retrieving bitmap from CreateActivity

Bitmap bitmap = (Bitmap) b.getParcelable("DRAWABLE");

// converting from bitmap to drawable
Drawable drawable = new BitmapDrawable(getResources(), bitmap);

// Event newEvent = new Event();
// newEvent.set_date(date);
// newEvent.set_title(title);
// newEvent.set_time(time);

// set drawable
// newEvent.set_drawable(drawable);

// lstEvents.add(newEvent);

// adapter.addAll(lstEvents);
// adapter.notifyDataSetChanged();

///////////////////////////////DATABASE/////////////////////////////////////////////
/**
* CRUD OPERATIONS
*/

Log.e("Insert: ", "Inserting ..");
db.addEvent(new Event(0, title, time, date, drawable));

// Reading all contacts
Log.e("Reading: ", "Reading all contacts..");
// List<Event> events = db.getAllContacts();
List<Event> events = db.getAllContacts();
adapter.addAll(events);
adapter.notifyDataSetChanged();

//logging all events

for (Event ev : events) {
String log = "Id: " + ev.get_Id() + " ,Title: "
+ ev.get_title() + " ,Date: " + ev.get_date();
// Writing Contacts to log
Log.e("Name: ", log);

}

///////////////////////////////DATABASE/////////////////////////////////////////////
}

}
}
}

事件类

public class Event {
public int _id;
public String _title;
public String _time;
public String _date;

//drawable
public String _bitmap;


public Event() {
super();
};

public Event(int id, String title, String time, String date, String bitmap) {
this._id = id;
this._title = title;
this._time = time;
this._date = date;
this._bitmap = bitmap;
};

public Event(JSONObject object){
try {
this._id = object.getInt("id");
this._title = object.getString("title");
this._time = object.getString("time");
this._date = object.getString("date");
} catch (JSONException e) {
e.printStackTrace();
}
}

// Event.fromJson(jsonArray);
public static ArrayList<Event> fromJson(JSONArray jsonObjects) {
ArrayList<Event> users = new ArrayList<Event>();
for (int i = 0; i < jsonObjects.length(); i++) {
try {
users.add(new Event(jsonObjects.getJSONObject(i)));
} catch (JSONException e) {
e.printStackTrace();
}
}
return users;
}



public int get_Id() {
return _id;
}

public void set_Id(int _Id) {
this._id = _Id;
}


public String get_title() {
return _title;
}

public void set_title(String _title) {
this._title = _title;
}

public String get_bitmap() {
return _bitmap;
}

public void set_drawable(String _bitmap) {
this._bitmap = _bitmap;
}

public String get_time() {
return _time;
}

public void set_time(String _time) {
this._time = _time;
}

public String get_date() {
return _date;
}

public void set_date(String _date) {
this._date = _date;
}

}

数据库处理程序

public class DatabaseHandler extends SQLiteOpenHelper {

// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "scheduleManager";

// Contacts table name
private static final String TABLE_EVENTS = "events";


// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "title";
private static final String KEY_TIME = "time";
private static final String KEY_DATE = "date";
private static final String KEY_BITMAP = "bitmap";

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

@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String CREATE_EVENTS_TABLE = "CREATE TABLE " + TABLE_EVENTS + "("
+ KEY_ID + " INTEGER," + KEY_TITLE + " TEXT,"
+ KEY_TIME + " TEXT," + KEY_DATE + " TEXT" + KEY_BITMAP + " TEXT )";
db.execSQL(CREATE_EVENTS_TABLE);

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_EVENTS);

// Create tables again
onCreate(db);

}

/**
* All CRUD(Create, Read, Update, Delete) Operations
*/


//adding an event (NEEDS TO ADD DRAWABLE)
public void addEvent(Event event) {
SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();
values.put(KEY_ID, event.get_Id()); //Event ID
values.put(KEY_TITLE, event.get_title()); // Event Title
values.put(KEY_TIME, event.get_time()); // Event Time
values.put(KEY_DATE, event.get_date()); // Event Date
values.put(KEY_BITMAP, event.get_bitmap()); // Event Drawable

// Inserting Row
db.insert(TABLE_EVENTS, null, values);
db.close(); // Closing database connection
}

// Getting single contact
public Event getEvent(int id) {
SQLiteDatabase db = this.getReadableDatabase();

Cursor cursor = db.query(TABLE_EVENTS, new String[] { KEY_ID,
KEY_TITLE, KEY_TIME, KEY_DATE }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();

Event event = new Event(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2), null, null);
// return contact
return event;
}


// Getting All Contacts
public List<Event> getAllContacts() {
List<Event> eventList = new ArrayList<Event>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_EVENTS;

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

// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Event event = new Event();
event.set_Id(Integer.parseInt(cursor.getString(0)));
event.set_title(cursor.getString(1));
event.set_time(cursor.getString(2));
event.set_date(cursor.getString(3));
// Adding contact to list
eventList.add(event);
} while (cursor.moveToNext());
}

// return contact list
return eventList;
}

// Getting event Count
public int getEventsCount() {
String countQuery = "SELECT * FROM " + TABLE_EVENTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();

// return count
return cursor.getCount();
}

// Updating single contact
public int updateEvent(Event event) {
SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();
values.put(KEY_TITLE, event.get_title());
values.put(KEY_TIME, event.get_time());
values.put(KEY_DATE, event.get_date());

// updating row
return db.update(TABLE_EVENTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(event.get_Id()) });
}

// Deleting single contact
public void deleteEvent(Event event) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_EVENTS, KEY_ID + " = ?",
new String[] { String.valueOf(event.get_Id()) });
db.close();
}
}

创建 Activity

public class CreateActivity extends Activity implements OnClickListener {

EditText etTitle;
Button btDate;
Button btTime;
Button btPic;


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

//onclicklistener
findViewById(R.id.btn_confirm).setOnClickListener(this);
findViewById(R.id.btn_back).setOnClickListener(this);

etTitle = (EditText) findViewById(R.id.editTextTitle);
btDate = (Button) findViewById(R.id.btn_date);
btTime = (Button) findViewById(R.id.btn_time);
btPic = (Button) findViewById(R.id.btn_picture);

}

// Will be called via the onClick attribute
// of the buttons in main.xml
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_confirm:
String title = etTitle.getText().toString();
String time = btTime.getText().toString();
String date = btDate.getText().toString();


Drawable drawable = btPic.getCompoundDrawables()[1];
Log.e("DRAWABLE", "DrawableId" + drawable);
Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();


Log.e("LOG", title);
Log.e("LOG", time);
Log.e("LOG", date);


Bundle newBundle = new Bundle();
newBundle.putString("TITLE", title);
newBundle.putString("TIME", time);
newBundle.putString("DATE", date);

//Trying to pass a drawable from one activity to another
newBundle.putParcelable("DRAWABLE", bitmap);


Intent intent = new Intent(this, MainActivity.class);
intent.putExtras(newBundle);

setResult(RESULT_OK, intent);

finish();

break;

case R.id.btn_back:
finish();
break;
}

}

public void showTimePickerDialog(View v) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getFragmentManager(), "timePicker");
}

public void showDatePickerDialog(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "datePicker");
}

public void showPicturePickerDialog(View v) {
DialogFragment newFragment = new PicturePickerFragment();
newFragment.show(getFragmentManager(), "picturePicker");
}

}

最佳答案

不建议将图像存储在数据库中。您必须将图像存储在内部或外部存储器中,并将图像的引用存储在数据库中。

// GET INT VALUE FROM RESOURCE
int home = R.drawable.home;

// SET IMAGE RESOURCE
img.setImageResource(home);

关于android - 如何在 SQLite (Android) 中存储 Drawable/Bitmap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23115092/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com