我在尝试从我的sqlite数据库中检索blob时遇到问题,并将其设置为imageview中的位图,这是我的listview使用的布局。数据库中的文本很好,但是当我尝试将imageview设置为从数据库读入的位图时,我收到错误。这是代码:
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.*;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.*;
import android.widget.TabHost.TabSpec;
public class StudentTrackerActivity extends Activity implements OnClickListener {
final static int cameraData = 0;
private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
private static final int REQUEST_CODE = 192837;
private static final String BUFF_INFO = null;
public byte[] imgByte = null;
public final Bitmap imgBitmap = null;
public ImageView imgPic;
public ImageButton imgCamera;
public ImageView imgSpeaker;
public ImageView imgIcon;
public Bitmap bm;
public Intent i;
public ByteArrayOutputStream out = new ByteArrayOutputStream(128);
InputStream is;
StringBuffer sb;
Button btnAddStudentRecord;
boolean bRecordAdded = true;
public ListView list;
public EditText txtStudentName;
public EditText txtDOB;
public EditText txtAddress1;
public EditText txtAddress2;
public EditText txtTown;
public EditText txtPostcode;
public EditText txtPhone;
public TextView txtFname;
public TextView txtDateOfBirth;
public String strStudentName;
public String strDOB;
public String strAddress1;
public String strAddress2;
public String strTown;
public String strPostcode;
public String strPhone;
public String strMatches;
public List<String> results = new ArrayList<String>();
@SuppressWarnings({ "unchecked", "rawtypes" })
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
sb = new StringBuffer();
imgCamera = (ImageButton) findViewById(R.id.imgCamera);
imgPic = (ImageView) findViewById(R.id.imgPic);
imgSpeaker = (ImageView) findViewById(R.id.imgSpeaker);
imgIcon = (ImageView) findViewById(R.id.icon);
btnAddStudentRecord = (Button) findViewById(R.id.btnAddStudentRecord);
txtStudentName = (EditText) findViewById(R.id.txtStudentName);
txtDOB = (EditText) findViewById(R.id.txtDOB);
txtAddress1 = (EditText) findViewById(R.id.txtAddress1);
txtAddress2 = (EditText) findViewById(R.id.txtAddress2);
txtTown = (EditText) findViewById(R.id.txtTown);
txtPostcode = (EditText) findViewById(R.id.txtPostcode);
txtPhone = (EditText) findViewById(R.id.txtPhone);
txtFname = (TextView) findViewById(R.id.txtFname);
// txtDateOfBirth = (TextView) findViewById(R.id.txtDateOfBirth);
list = (ListView) findViewById(R.id.list);
//convert edit text values to string values
strStudentName = txtStudentName.getText().toString();
strDOB = txtDOB.getText().toString();
strAddress1 = txtAddress1.getText().toString();
strAddress2 = txtAddress2.getText().toString();
strTown= txtTown.getText().toString();
strPostcode = txtPostcode.getText().toString();
strPhone = txtPhone.getText().toString();
TabHost th = (TabHost) findViewById(R.id.tabhost);
th.setup();
TabSpec specs = th.newTabSpec("tag1");
specs.setContent(R.id.tab1);
specs.setIndicator("", getResources().getDrawable(R.drawable.student));
th.addTab(specs);
specs = th.newTabSpec("tag2");
specs.setContent(R.id.tab2);
specs.setIndicator("", getResources().getDrawable(R.drawable.camera));
th.addTab(specs);
specs = th.newTabSpec("tag3");
specs.setContent(R.id.tab3);
specs.setIndicator("Tab3");
th.addTab(specs);
specs = th.newTabSpec("tag4");
specs.setContent(R.id.tab4);
specs.setIndicator("Search", getResources().getDrawable(R.drawable.magnify));
th.addTab(specs);
//set listener for speaker button
imgSpeaker.setOnClickListener(new SpeakerButtonHandler());
//set listener for camera button
imgCamera.setOnClickListener(this);
//set listener for add student button
btnAddStudentRecord.setOnClickListener(new AddStuButtonHandler());
//make silhouette default image
is = getResources().openRawResource(R.drawable.silhouette);
bm = BitmapFactory.decodeStream(is);
//display students in listview
DisplayaAllStudents();
}
public void onClick(View v) {
int vNum = v.getId();
switch(vNum){
case R.id.imgCamera:
//capture photo of student
i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, cameraData);
break;
}
}
private void startVoiceRecognitionActivity() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
//intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speech recognition demo");
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
}
public void flushBuffer(){
sb.delete(0, sb.length());
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try{
if(resultCode == RESULT_OK){
Bundle extras = data.getExtras();
bm = (Bitmap)extras.get("data");
imgPic.setImageBitmap(bm);
}
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {
// Fill the list view with the strings the recognizer thought it could have heard
ArrayList<String> matches = data.getStringArrayListExtra(
RecognizerIntent.EXTRA_RESULTS);
//add text to string buffer and display
//it on notepad
//flush string buffer of previous content
flushBuffer();
//remove square brackets
strMatches = matches.toString().replace("[","").replace("]", "");
//add string to string buffer
sb.append(strMatches.toString() + "\n");
//check which edit text field has the
//focus then populate the field with the
//contents of the voice recognition string
if(txtStudentName.isFocused()){
txtStudentName.setText(sb.toString());
}
else if(txtDOB.isFocused()){
txtDOB.setText(sb.toString());
}
else if(txtAddress1.isFocused()){
txtAddress1.setText(sb.toString());
}
else if(txtAddress2.isFocused()){
txtAddress2.setText(sb.toString());
}
else if(txtTown.isFocused()){
txtTown.setText(sb.toString());
}
else if(txtPostcode.isFocused()){
txtPostcode.setText(sb.toString());
}
else if(txtPhone.isFocused()){
txtPhone.setText(sb.toString());
}
}
}catch(Exception ex){
ex.printStackTrace();
}
}
private class AddStuButtonHandler implements OnClickListener{
public void onClick(View v) {
if(v.getId() == R.id.btnAddStudentRecord){
addRecord();
//DisplayaAllStudents();
//Toast.makeText(getApplicationContext(), "Testing!!!", Toast.LENGTH_SHORT).show();
}
}
}
public void addRecord(){
DBAdapter db = new DBAdapter(this);
db.open();
long id;
//prepare and compress bitmap for database insert
bm.compress(CompressFormat.PNG, 100, out);
id = db.insertStudent(txtStudentName.getText().toString(),
txtDOB.getText().toString(),
txtAddress1.getText().toString(),
txtAddress2.getText().toString(),
txtTown.getText().toString(),
txtPostcode.getText().toString(),
txtPhone.getText().toString(),
out.toByteArray()
);
if(bRecordAdded){
Toast.makeText(getApplicationContext(), "Record successfully added", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "Error: could not add record", Toast.LENGTH_SHORT).show();
}
db.close();
}
@SuppressWarnings("unchecked")
public void DisplayaAllStudents(){
DBAdapter db = new DBAdapter(this);
db.open();
Cursor c = db.getAllStudents();
if(c.moveToFirst()){
do{
String stuName = c.getString(c.getColumnIndex(db.KEY_STUDENTNAME));
String stuDOB = c.getString(c.getColumnIndex(db.KEY_DOB));
results.add(" " + stuName.toString() + ", D.O.B: " + stuDOB);
//read image from database and insert into image view
imgByte = c.getBlob(8);
ByteArrayInputStream is = new ByteArrayInputStream(imgByte);
Bitmap picBitmap = BitmapFactory.decodeStream(is);
imgIcon.setImageBitmap(picBitmap);
//display record
//DisplayStudent(c);
}while(c.moveToNext());
}
//bind data to list view
list.setAdapter(new ArrayAdapter<String>(StudentTrackerActivity.this,R.layout.datalayout,R.id.txtFname,results));
db.close();
}
public void DisplayStudent(Cursor c){
Toast.makeText(getApplicationContext(),
"StudentName: " + c.getString(1) + "\n" +
"D.O.B:" + c.getString(2) + "\n" +
"Address1: " + c.getString(3) + "\n" +
"Address2: " + c.getString(4) + "\n" +
"Town: " + c.getString(5) + "\n" +
"Postcode: " + c.getString(6) + "\n" +
"Phone: " + c.getString(7) + "\n" +
"Pic: " + c.getBlob(8)
,
Toast.LENGTH_LONG).show();
}
private class SpeakerButtonHandler implements OnClickListener{
public void onClick(View v) {
if(v.getId() == R.id.imgSpeaker){
startVoiceRecognitionActivity();
}
}
}
}
11-17 13:22:58.506: INFO/System.out(25430): waiting for debugger to settle...
11-17 13:22:58.707: INFO/System.out(25430): waiting for debugger to settle...
11-17 13:22:58.907: INFO/System.out(25430): waiting for debugger to settle...
11-17 13:22:59.109: INFO/System.out(25430): debugger has settled (1463)
11-17 13:22:59.307: ERROR/gralloc(126): [unregister] handle 0x393b98 still locked (state=40000001)
11-17 13:23:00.127: INFO/WeatherClockWidgetProvider(5101): updateAllElements
11-17 13:23:00.127: INFO/WeatherClockWidgetProvider(5101): updateTime
11-17 13:23:00.127: INFO/WeatherClockWidgetProvider(5101): setCalendarInstance
11-17 13:23:00.127: INFO/WeatherClockWidgetProvider(5101): onTimeChanged
11-17 13:23:00.127: INFO/WeatherClockWidgetProvider(5101): mHour01HandIndex = 1
11-17 13:23:00.127: INFO/WeatherClockWidgetProvider(5101): mHour01HandIndex = 3
11-17 13:23:00.127: INFO/WeatherClockWidgetProvider(5101): mHour01HandIndex = 2
11-17 13:23:00.127: INFO/WeatherClockWidgetProvider(5101): mHour01HandIndex = 3
11-17 13:23:00.127: INFO/WeatherClockWidgetProvider(5101): updateTime id = 3
11-17 13:23:00.127: INFO/WeatherClockWidgetProvider(5101): updateCurrentTemperature
11-17 13:23:00.127: INFO/WeatherClockWidgetProvider(5101): changeFtoC
11-17 13:23:00.137: INFO/WeatherClockWidgetProvider(5101): updateCurrentLocal
11-17 13:23:00.147: INFO/WeatherClockWidgetProvider(5101): updateTemperatures
11-17 13:23:00.147: INFO/WeatherClockWidgetProvider(5101): setCalendarInstance
11-17 13:23:00.177: INFO/WeatherClockWidgetProvider(5101): highT = 60
11-17 13:23:00.177: INFO/WeatherClockWidgetProvider(5101): lowT = 47
11-17 13:23:00.177: INFO/WeatherClockWidgetProvider(5101): changeFtoC
11-17 13:23:00.197: INFO/WeatherClockWidgetProvider(5101): changeFtoC
11-17 13:23:00.197: INFO/WeatherClockWidgetProvider(5101): updateDate
11-17 13:23:00.197: INFO/WeatherClockWidgetProvider(5101): setCalendarInstance
11-17 13:23:00.207: INFO/WeatherClockWidgetProvider(5101): updateWeatherDescription
11-17 13:23:00.207: INFO/WeatherClockWidgetProvider(5101): updateUpdatedTime
11-17 13:23:00.207: INFO/WeatherClockWidgetProvider(5101): setCalendarInstance
11-17 13:23:00.207: ERROR/updateUpdatedTime dateString(5101): 11/13/2011
11-17 13:23:00.237: ERROR/updatedTime before(5101): Update: NOV.13 4:14 PM
11-17 13:23:00.237: ERROR/updatedTime end(5101): Update: NOV.13 4:14 PM
11-17 13:23:00.297: INFO/WeatherClockWidgetProvider(5101): bindViews
11-17 13:23:00.297: INFO/WeatherClockWidgetProvider(5101): appWidgetId = 3
11-17 13:23:03.157: WARN/wpa_supplicant(189): Failed to initiate AP scan.
11-17 13:23:05.517: WARN/ActivityManager(126): Launch timeout has expired, giving up wake lock!
11-17 13:23:05.777: WARN/ActivityManager(126): Activity idle timeout for HistoryRecord{447ec880 com.StudentTracker/.StudentTrackerActivity}
11-17 13:23:07.467: WARN/GDataClient(126): Unable to execute HTTP request.java.net.UnknownHostException: Host is unresolved: android.clients.google.com:443
11-17 13:23:09.161: WARN/wpa_supplicant(189): Failed to initiate AP scan.
11-17 13:23:15.162: WARN/wpa_supplicant(189): Failed to initiate AP scan.
堆栈追踪:
StudentTracker_Debug [Android Application]
DalvikVM[localhost:8603]
Thread [<3> main] (Suspended (exception RuntimeException))
ActivityThread.performLaunchActivity(ActivityThread$ActivityRecord, Intent) line: 2496
ActivityThread.handleLaunchActivity(ActivityThread$ActivityRecord, Intent) line: 2512
ActivityThread.access$2200(ActivityThread, ActivityThread$ActivityRecord, Intent) line: 119
ActivityThread$H.handleMessage(Message) line: 1863
ActivityThread$H(Handler).dispatchMessage(Message) line: 99
Looper.loop() line: 123
ActivityThread.main(String[]) line: 4363
Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method]
Method.invoke(Object, Object...) line: 521
ZygoteInit$MethodAndArgsCaller.run() line: 860
ZygoteInit.main(String[]) line: 618
NativeStart.main(String[]) line: not available [native method]
答案 0 :(得分:3)
请勿将图像放入数据库中。它通常只是糟糕的形式,并且会使您的数据库查询变得非常慢。而是将文件路径存储到数据库中的映像并根据需要加载映像。请参阅此link以获取更详细的答案。