如何使用JDBC驱动器将MySql表图像(BLOB)加载到ImageView中

时间:2018-12-20 10:03:28

标签: android android-studio imageview

我有一个正在进行的项目。在这个项目中,我试图通过JDBC驱动程序将登录用户图像从MySQL表获取到ImageView中,在这种情况下,如果我尝试加载图片,则图像将被加载一次和第二次,然后在错误后系统给出错误信息再次,如果我尝试加载图像,则图像正在加载到ImageView中。在这里,我附上代码。

private class findpicture extends  AsyncTask<String, String, String> {

    String msg;
    String searchtext= textView3.getText().toString();

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        Toast.makeText(getApplicationContext(), "Searching username", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
        textView3.setText("");
    }

    @Override
    protected String doInBackground(String... strings) {

        try{

            Class.forName("com.mysql.jdbc.Driver");
            Connection con = (Connection)DriverManager.getConnection(url,user,pass);

            if (con == null){
                msg="Connection error...";
            }else{
                byte b[];
                Blob blob;
                Statement statement= (Statement) con.createStatement();
                ResultSet resultSet = statement.executeQuery("select * from userlogin where name='"+searchtext+"'");

                while (resultSet.next()){
                    blob = resultSet.getBlob("image");
                    b= blob.getBytes(1, (int)blob.length());
                    Bitmap bitmap = BitmapFactory.decodeByteArray(b, 0, b.length);
                    savedphoto.setImageBitmap(bitmap);
                    }
                msg= "user image saved successfully...";

            }

        }catch (Exception e){
            msg="unknown error..."+e;

            System.out.println(e.toString());
        }

        return null;
    }
}
  

错误代码android.view.ViewRootImpl $ CalledFromWrongThreadException:   只有创建视图层次结构的原始线程才能触摸其   视图。

1 个答案:

答案 0 :(得分:0)

您遇到Thread冲突,需要在此处重新检查呼叫和同步的任务, 快速解决您的问题

runOnUiThread(new Runnable() {
    @Override
    public void run() {
        new findpicture().execute();
    }
});