显示数据库中的数据

时间:2018-03-04 11:30:28

标签: android sqlite android-sqlite

如何从android SQLite数据库中检索图库的随机图片,并将其显示在名称和价格的另一个Activity中?当我点击“个人资料”按钮时,我的应用程序崩溃,但数据已成功添加。

我的代码是:

MainActivity类:

public class MainActivity extends AppCompatActivity {

    EditText edtName, edtPrice;
    Button btnChoose, btnAdd, btnList;
    ImageView imageView;
    Uri imageuri;
    final int REQUEST_CODE_GALLERY = 999;
    private static final int pick_image = 100;

    public static SQLiteHelper sqLiteHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        edtName = (EditText) findViewById(R.id.edtName);
        edtPrice = (EditText) findViewById(R.id.edtPrice);
        btnChoose = (Button) findViewById(R.id.btnChoose);
        btnAdd = (Button) findViewById(R.id.btnAdd);
        btnList = (Button) findViewById(R.id.btnList);
        imageView = (ImageView) findViewById(R.id.imageView);

        sqLiteHelper = new SQLiteHelper(this, "FoodDB.sqlite", null, 1);

        sqLiteHelper.queryData("CREATE TABLE IF NOT EXISTS FOOD(Id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, price VARCHAR, image BLOB)");

        btnChoose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
                startActivityForResult(gallery,pick_image);
            }
        });

        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try{
                    sqLiteHelper.insertData(
                            edtName.getText().toString().trim(),
                            edtPrice.getText().toString().trim(),
                            imageViewToByte(imageView)
                    );
                    Toast.makeText(getApplicationContext(), "Added successfully!", Toast.LENGTH_SHORT).show();
                   // edtName.setText("");
                    //edtPrice.setText("");
                   // imageView.setImageResource(R.mipmap.ic_launcher);
                    String s = "iqra";   //why we take string whrn we take only next button,is it necessary to take the string?
                    Intent i = new Intent(MainActivity.this, foodprofile.class);
                    Bundle bun = new Bundle();
                    bun.putString("name", s);
                    i.putExtras(bun);
                    startActivity(i);
                }
                catch (Exception e){
                    e.printStackTrace();

                }

            }
  });


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK && requestCode == pick_image){
            imageuri = data.getData();
            imageView.setImageURI(imageuri);
        }
    }

    public static byte[] imageViewToByte(ImageView image) {
        Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        //bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 0, stream);
        byte[] byteArray = stream.toByteArray();
        return byteArray;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == REQUEST_CODE_GALLERY){
            if(grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                startActivityForResult(intent, REQUEST_CODE_GALLERY);
            }
            else {
                Toast.makeText(getApplicationContext(), "You don't have permission to access file location!", Toast.LENGTH_SHORT).show();
            }
            return;
        }

        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }


}

SQLitehelper类:

public class SQLiteHelper extends SQLiteOpenHelper {
    public SQLiteHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    public void queryData(String sql){
        SQLiteDatabase database = getWritableDatabase();
        database.execSQL(sql);
    }

    public void insertData(String name, String price, byte[] image){
        SQLiteDatabase database = getWritableDatabase();
        String sql = "INSERT INTO FOOD VALUES (NULL, ?, ?, ?)";

        SQLiteStatement statement = database.compileStatement(sql);
        statement.clearBindings();

        statement.bindString(1, name);
        statement.bindString(2, price);
        statement.bindBlob(3, image);

        statement.executeInsert();
    }

    public void updateData(String name, String price, byte[] image, int id) {
        SQLiteDatabase database = getWritableDatabase();

        String sql = "UPDATE FOOD SET name = ?, price = ?, image = ? WHERE id = ?";
        SQLiteStatement statement = database.compileStatement(sql);

        statement.bindString(1, name);
        statement.bindString(2, price);
        statement.bindBlob(3, image);
        statement.bindDouble(4, (double)id);

        statement.execute();
        database.close();
    }

    public  void deleteData(int id) {
        SQLiteDatabase database = getWritableDatabase();

        String sql = "DELETE FROM FOOD WHERE id = ?";
        SQLiteStatement statement = database.compileStatement(sql);
        statement.clearBindings();
        statement.bindDouble(1, (double)id);

        statement.execute();
        database.close();
    }

    public Cursor getData(){
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor res = db.rawQuery("Select * from food ",null);
        return res;
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }
}

    foodprofile
public class foodprofile extends AppCompatActivity {
     SQLiteHelper sqLiteHelper;
    Button profile;
    TextView txtresult1,txtresult2,txtresult6;
    ImageView imgvresult;
    Uri imageuri;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_foodprofile);
        txtresult1 = (TextView) findViewById(R.id.name);
        txtresult2 = (TextView) findViewById(R.id.price);
        imgvresult = (ImageView) findViewById(R.id.image) ;
        profile = (Button) findViewById(R.id.btnprofile);
    }
    public void profile(View v) {
        if(v.getId()==R.id.btnprofile) {
            Cursor res = sqLiteHelper.getData();
            StringBuffer stringbuffer = new StringBuffer();
            Toast pass =  Toast.makeText(foodprofile.this,"inserted successfully", Toast.LENGTH_SHORT);
            pass.show();


                    txtresult1.setText("  " + res.getString(0) );
                    txtresult2.setText("  "   + res.getString(1) );
                    imgvresult.setImageURI(imageuri);
                  //  imgvresult.setImageResource(res.getString(2),R.mipmap.ic_launcher);
                     //imgvresult.setImageResource(res.getBlob(0x2));
                    txtresult6.setText("-------------------------"  + "\n");


                //txtresult.setText(stringbuffer.toString());
                Toast pass1= Toast.makeText(foodprofile.this, "retrieve successfully", Toast.LENGTH_SHORT);
                pass1.show();
            }


    }
}

foodprofile.xml:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#ffffff" >
        <Button
            android:id="@+id/btnprofile"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="profile"
            android:background="@color/colorPrimaryDark"

            android:onClick="profile"/>
       <ImageView
           android:id="@+id/image"
           android:layout_marginTop="55dp"
           android:layout_width="match_parent"
           android:layout_height="200dp" />
        <TextView
            android:id="@+id/name"
            android:textColor="#000"
            android:textStyle="bold"
            android:textSize="30dp"
            android:layout_width="match_parent"
            android:layout_height="fill_parent"
            android:layout_marginTop="300dp"/>
        <TextView
            android:id="@+id/price"
            android:textColor="#000"
            android:textStyle="bold"
            android:textSize="30dp"
            android:layout_width="match_parent"
            android:layout_height="fill_parent"
            android:layout_marginTop="350dp"/>


    </RelativeLayout>

</ScrollView>

1 个答案:

答案 0 :(得分:0)

你需要: -

  • a)通过getBlob()然后
  • 获取一个字节数组
  • b)将字节数组转换为位图然后
  • c)使用位图设置ImageView

以下内容: -

public void profile(View v) {
    if(v.getId()==R.id.btnprofile) {
        Cursor res = sqLiteHelper.getData();
        StringBuffer stringbuffer = new StringBuffer();
        Toast pass =  Toast.makeText(foodprofile.this,"inserted successfully", Toast.LENGTH_SHORT);
        pass.show();
        txtresult1.setText("  " + res.getString(0) );
        txtresult2.setText("  "   + res.getString(1) );
        // get the Blob
        byte[] my_bytearray = res.getBlob(2);
        // convert byte array into a bitmap
        Bitmap bmp = BitmapFactory.decodeByteArray(my_bytearray, 0, my_bytearray.length);
        // apply the image to the image view
        imgvresult.setImageBitmap(Bitmap.createScaledBitmap(bmp, image.getWidth(),
            image.getHeight(), false)));
        Toast pass1= Toast.makeText(foodprofile.this, "retrieve successfully", Toast.LENGTH_SHORT);
            pass1.show();
        }
}

注释

  • 存储图像可能存在问题且效率低下。如果图像大于约100k,建议将图像存储为文件,然后将图像的路径存储在数据库中。
  • 上述代码原则上尚未经过测试,因此可能会出现输入错误。