Iqraa
Iqraa

Reputation: 445

How to retrieve varbinary(max) image from SQL Server in android?

I am developing an android application in which I want to retrieve the image stored in SQL server database as shown in screenshot:

enter image description here

I have written a code for that but application will only retrieve the title column value and successfully shows in textview but in imageview nothing displays.Every kind of help is appreciated. Below is my code for that:

public class Menu_listen extends Fragment implements View.OnClickListener {
    Connection con;
    TextView t;
    ImageView img;
    String un,pass,db,ip,in;
    private String abc;

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        getActivity().setTitle("abc");
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        final View InputFragmentView = inflater.inflate(R.layout.menu_1, container, false);

        t = (TextView) InputFragmentView.findViewById(R.id.track_title);
        img=(ImageView) InputFragmentView.findViewById(R.id.track_image);
        ip = "192.168.***.**";
        in="SQLEXPRESS";
        db = "Testaudio";
        un = "**";
        pass = "****";
        Check check1 = new Check();// this is the Asynctask, which is used to process in background to reduce load on app process
        check1.execute("");

        return InputFragmentView;
    }

    public String getAbc() {
        return abc;
    }

    public void setAbc(String abc) {
        this.abc = abc;
    }

    public class Check extends AsyncTask<String,String,String>
    {
        String z = "";
        Boolean isSuccess = false;

        @Override
        protected void onPreExecute()
        {
        }

        @Override
        protected void onPostExecute(String r)
        {
            if(isSuccess)
            {

                Toast.makeText(getActivity() , "Successfull" , Toast.LENGTH_SHORT).show();
                t.setText(getAbc());
                byte[] decodeString = Base64.decode(r, Base64.DEFAULT);
                Bitmap decodebitmap = BitmapFactory.decodeByteArray(decodeString, 0, decodeString.length);
                img.setImageBitmap(decodebitmap);
            }
        }
        @Override
        protected String doInBackground(String... params)
        {
            try
            {
                con = connectionclass(un, pass, db, ip,in);
                if (con == null)
                {
                    z = "Check Your Internet Access!";
                }
                else
                {
                    String query = "select * from getImg";
                    Statement stmt = con.createStatement();
                    ResultSet rs = stmt.executeQuery(query);
                    if(rs != null && rs.next())
                    {
                        z = "successful";
                        isSuccess=true;
                        setAbc(rs.getString(3));
                        z=rs.getString(2);
                    }
                    con.close();
                }
            }
            catch (Exception ex)
            {
                isSuccess = false;
                z = ex.getMessage();
            }
            return z;
        }
    }
    @SuppressLint("NewApi")
    public Connection connectionclass(String user, String password, String database, String server,String instance) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        Connection connection = null;
        String ConnectionURL = null;
        try {
            Class.forName("net.sourceforge.jtds.jdbc.Driver");
            ConnectionURL = "jdbc:jtds:sqlserver://" + server + "/" + database + ";instance=" + instance + ";user=" + user + ";password=" + password + ";";
            connection = DriverManager.getConnection(ConnectionURL);
        } catch (SQLException se) {
            Log.e("error here 1 : ", se.getMessage());
            t.setText(se.getMessage());
        } catch (ClassNotFoundException e) {
            Log.e("error here 2 : ", e.getMessage());
            t.setText(e.getMessage());
        } catch (Exception e) {
            Log.e("error here 3 : ", e.getMessage());
            t.setText(e.getMessage());
        }
        return connection;
    }
}

Upvotes: 1

Views: 3854

Answers (1)

shraddha patel
shraddha patel

Reputation: 41

Here the code i used for my app

This code will take a image from url and convert is to a byte array

byte[] logoImage = getLogoImage(IMAGEURL);

private byte[] getLogoImage(String url){
     try {
             URL imageUrl = new URL(url);
             URLConnection ucon = imageUrl.openConnection();

             InputStream is = ucon.getInputStream();
             BufferedInputStream bis = new BufferedInputStream(is);

             ByteArrayBuffer baf = new ByteArrayBuffer(500);
             int current = 0;
             while ((current = bis.read()) != -1) {
                     baf.append((byte) current);
             }

             return baf.toByteArray();
     } catch (Exception e) {
             Log.d("ImageManager", "Error: " + e.toString());
     }
     return null;
}

To save the image to db i used this code.

 public void insertUser(){
    SQLiteDatabase db               =   dbHelper.getWritableDatabase();

    String delSql                       =   "DELETE FROM ACCOUNTS";
    SQLiteStatement delStmt         =   db.compileStatement(delSql);
    delStmt.execute();

    String sql                      =   "INSERT INTO ACCOUNTS (account_id,account_name,account_image) VALUES(?,?,?)";
    SQLiteStatement insertStmt      =   db.compileStatement(sql);
    insertStmt.clearBindings();
    insertStmt.bindString(1, Integer.toString(this.accId));
    insertStmt.bindString(2,this.accName);
    insertStmt.bindBlob(3, this.accImage);
    insertStmt.executeInsert();
    db.close();

}

To retrieve the image back this is code i used.

public Account getCurrentAccount() {
    SQLiteDatabase db       =   dbHelper.getWritableDatabase();
    String sql              =   "SELECT * FROM ACCOUNTS";
    Cursor cursor           =   db.rawQuery(sql, new String[] {});

    if(cursor.moveToFirst()){
        this.accId             = cursor.getInt(0);
        this.accName           = cursor.getString(1);
        this.accImage          = cursor.getBlob(2);
    }
    if (cursor != null && !cursor.isClosed()) {
        cursor.close();
    }
    db.close();
    if(cursor.getCount() == 0){
        return null;
    } else {
        return this;
    }
}

Finally to load this image to a imageview

logoImage.setImageBitmap(BitmapFactory.decodeByteArray( currentAccount.accImage, 
        0,currentAccount.accImage.length));

Upvotes: 1

Related Questions