Android 正在检索要放入imageview的sqlite blob字段

Android 正在检索要放入imageview的sqlite blob字段,android,sqlite,Android,Sqlite,我在尝试从sqlite数据库检索blob并将其设置为imageview中的位图时遇到问题,imageview是我的listview使用的布局。数据库中的文本很好,但是当我尝试将imageview设置为从数据库中读入的位图时,出现了一个错误。代码如下: import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.util.Arra

我在尝试从sqlite数据库检索blob并将其设置为imageview中的位图时遇到问题,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();


        }

     }



  }

}

堆栈跟踪:

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]  
StudentTracker\u调试[Android应用程序]
DalvikVM[localhost:8603]
线程[main](挂起(异常运行时异常))
ActivityThread.performLaunchActivity(ActivityThread$ActivityRecord,Intent)行:2496
ActivityThread.handleLaunchActivity(ActivityThread$ActivityRecord,Intent)行:2512
ActivityThread.access$2200(ActivityThread,ActivityThread$ActivityRecord,Intent)行:119
ActivityThread$H.handleMessage(消息)行:1863
ActivityThread$H(处理程序)。dispatchMessage(消息)行:99
Looper.loop()行:123
ActivityThread.main(字符串[])行:4363
invokenactive(Object,Object[],Class,Class[],Class,int,boolean)行:不可用[本机方法]
调用(对象,对象…)行:521
ZygoteInit$MethodAndArgsCaller.run()行:860
颧骨单位。主(字符串[])行:618
NativeStart.main(字符串[])行:不可用[本机方法]

不要将图像放入数据库中。一般来说,这是一种糟糕的形式,会使您的数据库查询速度非常慢。相反,将图像的文件路径存储在数据库中,并根据需要加载图像。请参阅此处以获得更详细的答案。

欢迎来到StackOverflow,您有可以发布的堆栈跟踪吗?这只是系统事件的日志。我已经包括了堆栈跟踪
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]