如何在Android图像视图中检索图像

时间:2018-06-21 19:23:22

标签: android android-studio

请处理一个班级项目,我将很快提交,我需要您的帮助。am试图将以varbinary格式保存在sql server 2016中的图像导入到我的android image view.i中,此级别的库存同时,我需要帮助来克服它。我也检查了google和youtube,但是我发现的答案并没有帮助我。数据库表中的其他值被检索到,但当我查看日志文件时,该图像告诉我它没有适配器您可以在代码中看到我的适配器已附加。请帮助。下面是我的代码 使用jtds连接到数据库

package com.example.abun.shoprite1;


import java.lang.String; 
import java.io.File;
import android.annotation.SuppressLint;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import static java.nio.file.Files.size;
import java.sql.*;
import java.util.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.StrictMode;
import android.util.Log;


public class ConnectionClass {

String url;
String serverName;
String instanceName;
String databaseName;
String userName;
String password;
String port;
String sql;

ConnectionClass() {

    serverName = "192.168.80.1";
    port ="1433";
    //instanceName = "";
    databaseName = "shoprite";
    userName = "abun2";
    password = "shoprite";
}
private String getConnectionUrl() {
    // Constructing the connection string
    return url + serverName +" ;DatabaseName = " +databaseName +";user="+userName + ";password="+password +";";
}

//private String getConnectionUrl() {
// Constructing the connection string
//return url + serverName  +" ;DatabaseName = " +databaseName+"; integratedSecurity=true";
//}

@SuppressLint("NewApi")
public Connection getConnection() throws SQLException, ClassNotFoundException {

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
    String ConnUrl;
    //String conny= "jdbc:jtds:sqlserver://"+ serverName+ ":" +port+ ";"+ " ;DatabaseName = " +databaseName+"; integratedSecurity=true";
    ConnUrl="jdbc:jtds:sqlserver://" + serverName+ ":" +port+ ";"+ "databaseName=" + databaseName + ";user=" + userName + ";password=" + password + ";";
    Connection con =null;
    try {
        Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
        con = DriverManager.getConnection(ConnUrl);
        //con = DriverManager.getConnection(conny);
        //""+"jdbc:jtds:sqlserver://127.0.0.1/shoprite; integrated security=true"
        // Establishing the connection
        //con = DriverManager.getConnection(getConnectionUrl());
        //con = DriverManager.getConnection(ConnUrl);
        if(con != null){
            System.out.println("Connection Successful!");
        }
        else{
            System.out.println(" no Connection ");
        }
    }catch(SQLException se){
        Log.e("ERROR--",se.getMessage());
        Log.e("ERROR--",se.getSQLState());
        Log.e("ERROR--",se.getLocalizedMessage());
        Log.e("ERROR--",se.getCause().toString());
        Log.e("ERROR--",se.getStackTrace().toString());

    }catch(ClassNotFoundException se){
        Log.e("ERROR--",se.getMessage());
        Log.e("ERROR--",se.getLocalizedMessage());

    }catch(Exception se){
        Log.e("ERROR--",se.getMessage());
        Log.e("ERROR--",se.getLocalizedMessage());

    }
    return con;
}

public boolean verifyCustomer(String username,String password)throws SQLException{
    Connection con1;
    ResultSet resultSet = null;
    String query = "select * from Customer_Details where Customer_Name =? and Password=?";
    try {
        con1 = getConnection();
        PreparedStatement stmt = con1.prepareStatement(query,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
        stmt.setString(1, username);
        stmt.setString(2, password);

        resultSet = stmt.executeQuery();
        if(resultSet.next()){
            return true;
        }else{
            return false;
        }
    }catch(Exception e){
        return false;
    } finally {

        if(resultSet != null)
            resultSet.close();
    }
}

public boolean verifyEmployee(String username,String password)throws SQLException{
    Connection con1;
    ResultSet resultSet = null;
    String query = "select * from Employee_Details where Employee_Name =? and Designation=?";
    try {
        con1 = getConnection();
        PreparedStatement stmt = con1.prepareStatement(query,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
        stmt.setString(1, username);
        stmt.setString(2, password);

        resultSet = stmt.executeQuery();
        if(resultSet.next()){
            return true;
        }else{
            return false;
        }
    }catch(Exception e){
        return false;
    } finally {

        if(resultSet != null)
            resultSet.close();
    }
}

public boolean insertDataCustomer(String name, String gender,String address,int phone,
                                  String DOB,String password,String email,int creditcard,String creditCardType){
    Connection con1;
    String query = "insert into Customer_Details(Customer_Name,Gender,Address,Phone,DOB,Password,CreditCardNo,CreditCardType) values( ?, ?, ?, ?,?,?,?,?)";
    try {
        con1 = getConnection();
        PreparedStatement stmt = con1.prepareStatement(query);
        stmt.setString(1, name);
        stmt.setString(2, gender);
        stmt.setString(3, address);
        stmt.setInt(4, phone);
        stmt.setString(5, DOB);
        stmt.setString(6, password);
        //stmt.setString(7, email);
        stmt.setInt(7, creditcard);
        stmt.setString(8, creditCardType);

        long ent= stmt.executeUpdate();
        if(ent == -1)
            return false;
        else
            return true;

    }catch(Exception e){
        // System.out.println(e.getMessage());
        Log.e( "error here: ",e.getMessage());
        Log.e( "error here: ",e.getLocalizedMessage());
        Log.e( "error here: ",e.getCause().toString());
        return  false;
    }
}

public boolean insertDataEmployee(String ID, String name, String gender,
                                  String DOB,String Designation,String address,String email,String phone){
    Connection con1;
    String query = "insert into Employee_Details(ID,name,gender,DOB,Designation,address,email,phone) values(?, ?, ?, ?, ?,?,?,?)";
    try {
        con1 = getConnection();
        PreparedStatement stmt = con1.prepareStatement(query);
        stmt.setString(1, name);
        stmt.setString(2, gender);
        stmt.setString(3, DOB);
        stmt.setString(4, Designation);
        stmt.setString(5, address);
        stmt.setString(6, email);
        stmt.setString(7, phone);


        long ent= stmt.executeUpdate();
        if(ent == -1)
            return false;
        else
            return true;

    }catch(Exception e){
        // System.out.println(e.getMessage());
        Log.e( "error here: ",e.getMessage());
        return  false;
    }
}

public void veiwOrders()throws SQLException{
    Connection con1;
    ResultSet resultSet = null;
    String query = "select * from Order_Details";
    try {
        con1 = getConnection();
        PreparedStatement stmt = con1.prepareStatement(query,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);

        resultSet = stmt.executeQuery();
        if(resultSet.next()){
            while(resultSet.next()){

            }
        }
    }catch(Exception e){
        //return false;
    } finally {

        if(resultSet != null)
            resultSet.close();
    }
}
}

下面是我的活动课     包com.example.abun.shoprite1;

/**
* Created by Abun on 5/12/2018.
*/
import android.app.Activity;
import android.app.ProgressDialog;
import android.support.annotation.RequiresPermission.Write;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.MenuItem;
import android.os.AsyncTask;
import android.support.design.widget.NavigationView;
import android.content.Intent;
//import android.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.View;
import android.support.v7.app.ActionBar;
import android.widget.Toast;

import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

public class productPage extends AppCompatActivity  {

private RecyclerView mRecycler;

private RecyclerView.LayoutManager mLayoutManager;

private RecyclerView.Adapter mAdapter;
private DrawerLayout mDrawerLayout;
private ArrayList<String> mData;
private ArrayList<ProductPageRetrive> data;
ConnectionClass db;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.productpage1);
    db = new ConnectionClass();


    data = new ArrayList<ProductPageRetrive>();
    mData = new ArrayList<>();
    for (int i = 0;i<30;i++){
        mData.add("new title"+i);
    }

    SyncData orderData = new SyncData();
    orderData.execute("");
    mRecycler = (RecyclerView) findViewById(R.id.recycler_view);
    mRecycler.setHasFixedSize(true);
    mLayoutManager = new LinearLayoutManager(productPage.this,LinearLayoutManager.HORIZONTAL,false);
    mRecycler.setLayoutManager(mLayoutManager);
    mAdapter = new MainAdapter(data,productPage.this);
    mRecycler.setAdapter(mAdapter);

    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    ActionBar actionbar = getSupportActionBar();
    actionbar.setDisplayHomeAsUpEnabled(true);
    actionbar.setHomeAsUpIndicator(R.mipmap.ic_launcher);

    mDrawerLayout = findViewById(R.id.drawer_layout);
    mDrawerLayout.addDrawerListener(
            new DrawerLayout.DrawerListener() {
                @Override
                public void onDrawerSlide(View drawerView, float slideOffset) {
                    // Respond when the drawer's position changes
                }

                @Override
                public void onDrawerOpened(View drawerView) {
                    // Respond when the drawer is opened
                }

                @Override
                public void onDrawerClosed(View drawerView) {
                    // Respond when the drawer is closed
                }

                @Override
                public void onDrawerStateChanged(int newState) {
                    // Respond when the drawer motion state changes
                }
            }
    );


    NavigationView navigationView = findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(
            new NavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(MenuItem menuItem) {
                    // set item as selected to persist highlight
                    menuItem.setChecked(true);
                    // close drawer when item is tapped
                    mDrawerLayout.closeDrawers();

                    // Add code here to update the UI based on the item selected
                    // For example, swap UI fragments here

                    return true;
                }
            });





}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            mDrawerLayout.openDrawer(GravityCompat.START);
            return true;
    }
    return super.onOptionsItemSelected(item);
}

private class SyncData extends AsyncTask<String ,String,String>{
    String msg="Internet/DB_Credentials/Windows_FireWall_TurnOn Error, see android monitor in the buttom for details";
    ProgressDialog progress;
    boolean success = false;

    @Override
    protected void onPreExecute(){
        progress = ProgressDialog.show(productPage.this,"Synchronising","RecyclerView loading! please wait...",true);
    }

    @Override
    protected String doInBackground(String...strings){
        try {
            Connection con = db.getConnection();
            ResultSet resultSet = null;
            if (con == null) {

                msg="No Data found";
                success = false;
            }else{
                String query = "SELECT * FROM Product_Details";
                PreparedStatement stmt = con.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);


                resultSet = stmt.executeQuery();
                while (resultSet.next()) {
                    try {

                        data.add(new ProductPageRetrive(resultSet.getBinaryStream("Image"), resultSet.getInt("Price"), resultSet.getInt("Discount")));

                    }catch(Exception ex){
                        ex.printStackTrace();
                    }
                }
                msg ="found";
                success=true;
            }
        }catch(Exception e){
            e.printStackTrace();
            //Write write = new StringWriter();
            //e.printStackTrace(new PrintWriter(write));
            //msg=writer.toString();
            success=false;
        }
        return msg;
    }

    @Override
    protected void onPostExecute(String msg){
        progress.dismiss();
        Toast.makeText(productPage.this,msg+"",Toast.LENGTH_LONG).show();
        if(success == true){



            mAdapter.notifyDataSetChanged();

        }else{
            try{

            }catch (Exception e){

            }

        }
    }
}

}
下面的

是数组数据的数据对象;     包com.example.abun.shoprite1;

import java.io.InputStream;
import java.sql.Blob;
import java.sql.ResultSet;

/**
* Created by Abun on 6/14/2018.
*/

public class ProductPageRetrive {

private int price;
private int rating;
private String img1;
private InputStream ism;
private ResultSet rs;


public ProductPageRetrive(InputStream is, int money, int rate){
    this.ism=is;
    this.price=money;
    this.rating=rate;
}

public int getRating() {
    return rating;
}

public void setRating(int rating) {
    this.rating = rating;
}

public int getPrice() {
    return price;
}

public void setPrice(int price) {
    this.price = price;
}

public String getImg1() {
    return img1;
}

public void setImg1(String img1) {
    this.img1 = img1;
}

public InputStream getIsm() {
    return ism;
}

public void setIsm(InputStream ism) {
    this.ism = ism;
}
}

下面是我的适配器类     包com.example.abun.shoprite1;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.widget.RecyclerView;
import android.util.Base64;
import java.io.FileOutputStream;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.SQLException;
import java.util.ArrayList;
import com.squareup.picasso.Picasso;
import android.content.Context;

/**
* Created by Abun on 6/13/2018.
*/


public class MainAdapter extends  RecyclerView.Adapter<MainAdapter.ViewHolder> {

private ArrayList<String> mData;
private ArrayList<ProductPageRetrive> Data;
private Context ct1;

public MainAdapter(ArrayList<String> Data1){

    this.mData=Data1;
}

public MainAdapter(ArrayList<ProductPageRetrive> Data, Context ct)
{
    this.Data=Data;
    this.ct1 =ct;
}

@Override
public MainAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.contain,parent,false);
    // set the view size, margin,padding and layout parameters
    ViewHolder vh = new ViewHolder(v);
    return vh;
}

@Override
public void onBindViewHolder(MainAdapter.ViewHolder holder, int position) {
    int py =Data.get(position).getRating();
    String pp = py +"";
    holder.mtitle.setText(pp);

    try {
        InputStream is = Data.get(position).getIsm();
        OutputStream os = new FileOutputStream(new File("photo1.jpg"));
        byte[] content = new byte[1024];
        int size = 0;
        while((size=is.read(content))!=-1){
            os.write(content,0,size);
        }
        os.close();
        is.close();
        //Picasso.get().load("file:photo1.jpg").into(holder.img);

        Picasso.get().load("file:photo1.jpg").into(holder.img);


    }catch (Exception e){

    }
    /*byte[] decorde = Base64.decode(Data.get(position).getImg1(),Base64.DEFAULT);
    Bitmap mp = BitmapFactory.decodeByteArray(decorde,0,decorde.length);
    holder.img.setImageBitmap(mp);*/

}

@Override
public int getItemCount() {
    return Data.size();
}

public class ViewHolder extends RecyclerView.ViewHolder{
    public TextView mtitle;
    public TextView mtitle1;
    public ImageView img;
    public View layout;

    public ViewHolder(View itemView){
        super(itemView);
        layout = itemView;
        mtitle = (TextView) itemView.findViewById(R.id.mtitle);
        img = (ImageView) itemView.findViewById(R.id.imaging);
    }
}
}

0 个答案:

没有答案